Curso SQL ORACLE02
Curso SQL ORACLE02
Curso SQL ORACLE02
s
a
h
s)
e
a ide
u
g
u
ta 11g:
G
s
t
Oracle Database
SQL
e
n
g
e
Fundamentals
ra@ StudII
r
a
leg e this
i
(
s Guide
ez oStudent
l
u
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
D49994GC11
Edition 1.1
May 2009
D60300
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Authors
Chaitanya Koratamaddi
Brian Pottle
Technical Contributors
and Reviewers
Claire Bennett
Ken Cooper
Yanti Chang
Laszlo Czinkoczki
Burt Demchick
Gerlinde Frenzen
Joel Goodman
Laura Garza
Richard Green
Nancy Greenberg
Akira Kinutani
Wendy Lo
Isabelle Marchand
Timothy Mcglue
Alan Paulson
Srinivas Putrevu
Bryan Roberts
Clinton Shaffer
Abhishek Singh
Jenny Tsai Smith
James Spiller
Lori Tritz
Lex van der Werff
Marcie Young
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
go -tran
IiEditors
on
n
Nita Pavitran
Arijit Ghosh
Raj Kumar
Graphic Designer
Satish Bettegowda
Publishers
Syed Ali
Jayanthy Keshavamurthy
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Contents
Introduction
Lesson Objectives I-2
Lesson Agenda I-3
Course Objectives I-4
Course Prerequisites I-5
Course Agenda I-6
Lesson Agenda I-7
Human Resources (HR) Schema Used in This Course I-8
Appendixes Used in This Course I-9
Development Environments I-10
Lesson Agenda I-11
Review of Restricting Data I-12
Review of Sorting Data I-13
Review of SQL Functions I-14
Review of Single-Row Functions I-15
Review of Types of Group Functions I-16
Review of Using Subqueries I-17
Review of Manipulating Data I-18
Lesson Agenda I-19
Oracle Database 11g SQL Documentation I-20
Additional Resources I-21
Summary I-22
Practice I: Overview I-23
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
1
iii
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
iv
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
USER_OBJECTS View 3-9
leg e this
i
(
Lesson Agenda 3-10
ez o us
l
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
Types of Multitable INSERT Statements 4-18
s)
e
a ide
Multitable INSERT Statements 4-19
u
g
ta t Gu
Unconditional INSERT ALL 4-21
s
e
g den
Conditional INSERT ALL: Example 4-23
@
ra Stu
r
Conditional INSERT ALL 4-24
a
leg e this
i
Conditional INSERT FIRST: Example 4-25
(
ez o us
l
Conditional INSERT FIRST 4-26
nz se t
o
Pivoting INSERT 4-28
a G licen
r
Lesson Agenda 4-31
r
a 4-32ble
g
MERGE Statement
e
L fera
eStatement
MERGE
d
s Syntax 4-33
o
n
g
a
i
r
-tRows: Example 4-34
I Merging
n
o
Lesson
n Agenda 4-37
vi
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
FROM_TZ 5-25
e
a ide
u
g
TO_TIMESTAMP 5-26
u
a
t
G
s
t
e
TO_YMINTERVAL 5-27
g den
@
TO_DSINTERVAL 5-28
ra Stu
r
a
Daylight Saving Time 5-29
leg e this
i
(
Quiz 5-31
ez o us
l
Summary 5-32
nz se t
o
Practice 5: Overview
en
a G li5-33
c
r
r
a ble
g
e
6 Retrieving
L feData
ra Using Subqueries
eObjectives
d
s
o tran 6-2
g
i
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
viii
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
Review of the HAVING Clause E-5
s
e
g den
GROUP BY with ROLLUP and CUBE Operators E-6
@
ra Stu
r
ROLLUP Operator E-7
a
leg e this
i
ROLLUP Operator: Example E-8
(
ez o us
l
CUBE Operator E-9
nz se t
CUBE Operator: Example o
E-10
G cen
aE-11
r
GROUPING Function
r
li
a
e
g
l
e raExample
b
GROUPINGLFunction:
E-12
e
e
f
GROUPING
o d traSETS
ns E-13
g
i
- SETS: Example E-15
I GROUPING
n
o
n
Composite
Columns E-17
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
Appendix H: Oracle Database Architectural Components
e
a ide
u
Objectives H-2
g
ta t Gu
s
Oracle Database Architecture: Overview H-3
e
g den
@
Oracle Database Server Structures H-4
ra Stu
r
a
Connecting to the Database H-5
g this
leH-6
i
(
Interacting with an Oracle Database
e
z
s
e
l
u
Oracle Memory Architecture
z H-8
to
n
e
o
Process Architecture
G H-10
ns
e
a
c
r
Database Writer
r Process
li H-12
a
e
g
l
Log
e Process
LWriter
ab H-13
r
e
e
f
s Process H-14
o d Checkpoint
n
g
a
i
r
Monitor Process H-15
t
I on-System
Process
Monitor Process H-16
n
xi
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Index
Additional Practices
Additional Practice Solutions
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
xii
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Introduction
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Lesson Objectives
After completing this lesson, you should be able to do the
following:
Discuss the goals of the course
Describe the database schema and tables that are used in
the course
Identify the available environments that can be used in the
course
a
s
a
Review some of the basic concepts of SQL
)h
es e
a
gu uid
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 2
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 3
Cas Training
Course Objectives
After completing this course, you should be able to do the
following:
Control database access to specific objects
Add new users with different levels of access privileges
Manage schema objects
Manage objects with data dictionary views
a
Manipulate large data sets in the Oracle database by using
s
a
subqueries
)h
s
e
a ide
Manage data in different time zones
u
g
ta t Gu
s
e
Write multiple-column subqueries g
n
e
@
d
ra Stu
r
Use scalar and correlated subqueries
a
g this
lesupport
i
(
Use the regular expression
z
se in SQL
le to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
de nsfe
o
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 4
Cas Training
Course Prerequisites
The Oracle Database 11g: SQL Fundamentals I course is a
prerequisite for this course.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Course Prerequisites
o tran
Required
for this course is Oracle Database 11g: SQL Fundamentals I.
Iig preparation
onn
This course offers you an introduction to Oracle Database 11g database technology. In this course,
you learn the basic concepts of relational databases and the powerful SQL programming language.
This course provides the essential SQL skills that enable you to write queries against single and
multiple tables, manipulate data in tables, create database objects, and query metadata.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 5
Cas Training
Course Agenda
Day 1:
Introduction
Controlling User Access
Managing Schema Objects
Managing Objects with Data Dictionary Views
Day 2:
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 6
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 7
Cas Training
LOCATIONS
location_id
street_address
postal_code
city
state_province
country_id
JOB_HISTORY
employee_id
start_date
end_date
job_id
department_id
EMPLOYEES
employee_id
first_name
last_name
email
phone_number
hire_date
job_id
salary
commission_pct
manager_id
department_id
COUNTRIES
a
s
a
)h
s
e
a ide
JOBS
u
g
u
taREGIONS
G
s
t
e
g den
@
JOB_GRADES
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L (HR)
eSchema
f
d
Human Resources
Description
s
o tran
g
i
TheI
Human n
Resources
(HR) schema is part of the Oracle Sample Schemas that can be installed in an
no This course uses data from the HR schema.
Oracle database.
job_id
job_title
min_salary
max_salary
country_id
country_name
region_id
region_id
region_name
grade_level
lowest_sal
highest_sal
Table descriptions
The EMPLOYEES table contains information about all the employees such as their first and last
names, job IDs, salaries, hire dates, department IDs, and manager IDs. This table is a child of the
DEPARTMENTS table.
The DEPARTMENTS table contains information such as the department ID, department name,
manager ID, and location ID. This table is the primary key table to the EMPLOYEES table.
The LOCATIONS table contains department location information. It contains location ID, street
address, city, state province, postal code, and country ID information. It is the primary key table
to the DEPARTMENTS table and is a child of the COUNTRIES table.
The COUNTRIES table contains the country names, country IDs, and region IDs. It is a child of
the REGIONS table. This table is the primary key table to the LOCATIONS table.
The REGIONS table contains region IDs and region names of the various countries. It is a
primary key table to the COUNTRIES table.
The JOB_GRADES table identifies a salary range per job grade. The salary ranges do not
overlap.
The JOB_HISTORY table stores job history of the employees.
The JOBS table contains job titles and salary ranges.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 8
Cas Training
a ide
u
Appendix H: Oracle Database Architectural
Components
g
u
a
t
G
s
t
e
n
g
a@ Stude
r
r
a
g
e
his
l
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 9
Cas Training
Development Environments
There are two development environments for this course:
Primary tool is Oracle SQL Developer
SQL*Plus command line interface may also be used
a
s
a
h
)
s
e
SQL *Plus a
SQL Developer
e
u
d
i
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eEnvironments
d
Development
o trans
g
i
SQL
IDeveloper
onn
This course has been developed using Oracle SQL Developer as the tool for running the SQL
statements discussed in the examples in the slide and the practices.
SQL Developer version 1.2 is shipped with Oracle Database 11g, and is the default tool for this
class.
In addition, SQL Developer version 1.5.3 is also available on the classroom machine, and may
be installed for use. At the time of publication for this course, version 1.5.3 was the latest release
of SQL Developer.
SQL*Plus
The SQL*Plus environment may also be used to run all SQL commands covered in this course.
Note:
See Appendix C for information on using SQL Developer, including simple instructions on
installing version 1.5.3.
See Appendix D for information on using SQL*Plus.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 10
Cas Training
Lesson Agenda
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Lesson Agenda
igo -tranprovide a brief overview of some of the basic concepts that you learned in the
TheI
next fewnslides
no Oracle Database 11g: SQL Fundamentals I.
course titled
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 11
Cas Training
Meaning
BETWEEN
...AND...
IN(set)
a
s
a
)h
s
e
LIKE
Match a character pattern
a ide
u
g
ta t Gu
s
e
Use logical conditions to combine thegresulteof
n two
@
d
tu result based
component conditions and produce
ra a single
r
S
a
on those conditions.
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
de nsfeand
Review ofoRestricting
Sorting Data
g
a
i
r
You
-t the rows that are returned from the query by using the WHERE clause. A WHERE
Ican restrict
n
o
n a condition that must be met, and it directly follows the FROM clause.
clause contains
The WHERE clause can compare values in columns, literal values, arithmetic expression, or functions.
It consists of three elements:
Column name
Comparison condition
Column name, constant, or list of values
You use comparison conditions in the WHERE clause in the following format:
... WHERE expr operator value
Apart from those mentioned in the slide, you use other comparison conditions such as =, <, >, <>,
<=, and >=.
Three logical operators are available in SQL:
AND
OR
NOT
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 12
Cas Training
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nData
Review ofoSorting
s
g
a
i
r
TheI
order ofnrows
-t that are returned in a query result is undefined. The ORDER BY clause can be used
o
n rows. If you use the ORDER BY clause, it must be the last clause of the SQL statement.
to sort the
You can specify an expression, an alias, or a column position as the sort condition.
Syntax
SELECT
FROM
[WHERE
[ORDER BY
expr
table
condition(s)]
{column, expr, numeric_position} [ASC|DESC]];
In the syntax:
ORDER BY
Specifies the order in which the retrieved rows are displayed
ASC
Orders the rows in ascending order (This is the default order.)
DESC
Orders the rows in descending order
If the ORDER BY clause is not used, the sort order is undefined, and the Oracle server may not fetch
rows in the same order for the same query twice. Use the ORDER BY clause to display the rows in a
specific order.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 13
Cas Training
Functions
s
a
h
Multiple-rows)
Single-row
e e
a
functions
functions
u
ag Guid
t
s
t result
e eone
n
g
Return one result
Return
d of rows
tuset
ra@ S
per row
per
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Functions
Review ofoSQL
s
n
g
a
i
r
t of functions:
There
I are otwon-types
n
Single-row functions
Multiple-row functions
Single-Row Functions
These functions operate on single rows only and return one result per row. There are different types
of single-row functions such as character, number, date, conversion, and general functions.
Multiple-Row Functions
Functions can manipulate groups of rows to give one result per group of rows. These functions are
also known as group functions.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 14
Cas Training
Character
General
Single-row
functions
Number
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
n
g
Conversion
Date de
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
de nsfeFunctions
Review ofoSingle-Row
ig -are
tradifferent types of single-row functions:
TheI
following
n
no
Character functions: ccept character input and can return both character and number values
Number functions: Accept numeric input and return numeric values
Date functions: Operate on values of the DATE data type (All date functions return a value of
the DATE data type except the MONTHS_BETWEEN function, which returns a number.)
Conversion functions: Convert a value from one data type to another
General functions:
- NVL
- NVL2
- NULLIF
- COALESCE
- CASE
- DECODE
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 15
Cas Training
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
Group
functions
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de ofnsGroup
Review ofoTypes
Functions
g
a
i
r
-t accepts an argument. The following table identifies the options that you can
Each
Iof theonfunctions
n syntax:
use in the
Function
Description
AVG([DISTINCT|ALL]n)
COUNT({*|[DISTINCT|ALL]expr})
MAX([DISTINCT|ALL]expr)
MIN([DISTINCT|ALL]expr)
STDDEV([DISTINCT|ALL]x)
SUM([DISTINCT|ALL]n)
VARIANCE([DISTINCT|ALL]x)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 16
Cas Training
Syntax:
SELECT select_list
FROM
table
WHERE expr operator
(SELECT select_list
FROM
table );
a
s
a
)h
s
e
Single-row subquery
Multiple-row subquery
a ide
u
g
Returns only one row
tarow t Gu
Returns more than one
s
e
g den
@
tu
ra Scomparison
r
Uses single-row comparison
Uses a
multiple-row
operators
leg e this
i
operators
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Subqueries
Review ofoUsing
s
n
g
a
i
r
t
-powerful
You
statements out of simple ones by using subqueries. Subqueries are useful
Ican build
n
o
n
when a query is based on a search criterion with unknown intermediate values.
Types of subqueries:
You can place the subquery in a number of SQL clauses, including the following:
WHERE clause
HAVING clause
FROM clause
The subquery (inner query) executes once before the main query (outer query). The result of the
subquery is used by the main query.
A single-row subquery uses a single-row operator such as =, >, <, >=, <=, and <>. With a multiplerow subquery, you use a multiple-row operator such as IN, ANY, and ALL.
Example: Display details of employees whose salary is equal to the minimum salary.
SELECT last_name, salary, job_id
FROM
employees
WHERE salary = (SELECT MIN(salary)
FROM
employees );
In the example, the MIN group function returns a single value to the outer query.
Note: In this course, you learn how to use multiple-column subqueries. Multiple-column subqueries
return more than one column from the inner SELECT statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 17
Cas Training
Description
a
s
a
)h
Modifies existing rows in the table
UPDATE
s
e
a ide
Removes existing rows from the table agu
DELETE
u
t
G
s
t
e
n
g conditionally
Updates, inserts, or deletes @
a row
MERGE
e
d
ra Stu
r
into/from a table
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsferData
Review ofoManipulating
g want-trtoaadd, update, or delete data in the database, you execute a DML statement. A
When
Iiyou
noofnDML statements that form a logical unit of work is called a transaction. You can add
collection
INSERT
new rows to a table by using the INSERT statement. With the following syntax, only one row is
inserted at a time.
INSERT INTO table [(column [, column])]
VALUES
(value[, value...]);
You can use the INSERT statement to add rows to a table where the values are derived from existing
tables. In place of the VALUES clause, you use a subquery. The number of columns and their data
types in the column list of the INSERT clause must match the number of values and their data types
in the subquery.
The UPDATE statement modifies specific rows if you specify the WHERE clause.
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
You can remove existing rows by using the DELETE statement. You can delete specific rows by
specifying the WHERE clause in the DELETE statement.
DELETE [FROM] table
[WHERE condition];
You learn about the MERGE statement in the lesson titled Manipulating Large Data Sets.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 18
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 19
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L11gsfSQL
eraDocumentation
d
Oracle Database
o tran
Navigate
to access the Oracle Database 11g
Iig toonhttp://www.oracle.com/pls/db111/homepage
n
documentation library.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 20
Cas Training
Additional Resources
For additional information about the new Oracle 11g SQL, refer
to the following:
Oracle Database 11g: New Features eStudies
Oracle by Example series (OBE): Oracle Database 11g
http://www.oracle.com/technology/obe/11gr1_db/index.htm
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 21
Cas Training
Summary
In this lesson, you should have learned the following:
The course objectives
The sample tables used in the course
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 22
Cas Training
Practice I: Overview
This practice covers the following topics:
Running the SQL Developer online tutorial
Starting SQL Developer and creating a new database
connection and browsing the HR tables
Executing SQL statements using the SQL Worksheet
Reviewing the basic concepts of SQL
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Practice I:
Overview
o tran
In this
Iigpractice,
n- you use SQL Developer to execute SQL statements to examine data in the HR
o
n
schema.
Note: All written practices use SQL Developer as the development environment. Although it is
recommended that you use SQL Developer, you can also use the SQL*Plus environment that is
available in this course.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 23
Cas Training
Practice I
This is the first of many practices in this course. The solutions (if you require them) can be
found in Appendix A. Practices are intended to cover most of the topics that are presented in
the corresponding lesson.
Accessing SQL Developer resources
1. Access the SQL Developer home page.
a. Access the online SQL Developer Home Page available at:
http://www.oracle.com/technology/products/database/sql_developer/index.html
b. Bookmark the page for easier future access.
2. Access the SQL Developer tutorial available online at:
http://st-curriculum.oracle.com/tutorial/SQLDeveloper/index.htm
Then review the following sections and associated demos:
a. What to Do First
b. Working with Database Objects
a
c. Accessing Data
s
a
)h
Starting SQL Developer, Creating and Testing a New SQL Developer Database
s
e
a ide
Connection, and Connecting to your oraxx account
u
g
3. Start up SQL Developer using the Desktop icon.
ta t Gu
s
e
g den
4. Create a database connection using the following information:
@
a Stu
a. Connection Name: myconnection
arr
is
z
n
c. Password: oraxx Go
se
a
en
tr
I
n
5. Test the
no new connection. If the status is Success, connect to the database using this new
connection.
a. Click the Test button in the New/Select Database Connection window.
b. If the status is Success, click the Connect button.
Browsing the Tables
6. Browse the structure of the EMPLOYEES table and display its data.
a. Expand the myconnection connection by clicking the plus sign next to it.
b. Expand the Tables icon by clicking the plus sign next to it.
c. Display the structure of the EMPLOYEES table.
7. View the data of the DEPARTMENTS table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 24
Cas Training
Practice I (continued)
Using the SQL Worksheet
8. Execute some basic SELECT statements to query the data in the EMPLOYEES table in the SQL
Worksheet area. Use both the Execute Statement (or press [F9]) and the Run Script (or press
[F5]) icons to execute the SELECT statements. Review the results of both methods of executing
the SELECT statements on the appropriate tabbed pages.
a. Write a query to select the last name and salary for any employee whose salary is less than
or equal to $3,000.
b. Write a query to display last name, job ID, and commission for all employees who are not
entitled to receive a commission.
9. Set your script pathing preference to D:\labs\SQL2.
a. Select Tools > Preferences > Database > Worksheet Parameters.
b. Enter the value in the Select default path to look for scripts field.
10. Enter the following in the Enter SQL Statement box.
a
s
SELECT employee_id, first_name, last_name,
a
)h
s
FROM
employees;
e
aitem.
e
11. Save the SQL statement to a script file using the File > Save As menu
u
d
i
g
ta t Gu
a. Select File > Save As.
s
e
g den
b. Name the file intro_test.sql.
@
ra Stu
r
c. Place the file under your D:\labs\labs a
folder.
12. Open and run confidence.sql from(your
folder, and observe the output.
ilegD:\Labs\labs
this
le to us
Quiz
z
1. What condition do you use o
tondisplaysrows
e based on a range of values?
G
n
e
_____________________________________________________________________
a
arr ble licoperation is also referred to as:
2. The characterepatternmatching
g
_____________________________________________________________________
e L sfera
d
3. Group
an return one result per row. True/False.
igo functions
r
t
I_____________________________________________________________________
nonfunction converts mixed case or lowercase character strings to uppercase?
4. Which
_____________________________________________________________________
5. Which among the following are group functions?
a. MAX
b. TRUNC
c. STDDEV
d. MOD
e. CONCAT
f. SUM
_____________________________________________________________________
6. What is the default sorting order of rows?
_____________________________________________________________________
7. You can sort by a column that is not in the SELECT list. True/False.
_____________________________________________________________________
8. You cannot specify a column position as the sort expression. True/False.
_____________________________________________________________________
9. Which statement do you use to modify existing rows in a table?
_____________________________________________________________________
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 25
Cas Training
Practice I (continued)
Quiz (continued)
10. What happens if you do not specify the WHERE clause in a DELETE statement?
__________________________________________________________________________
11. Consider a SELECT statement that consists of three query blocks: the outer query and two
inner queries. If both the inner queries return single values, what do you call such a SQL
statement?
__________________________________________________________________________
12. You can use subqueries only in the WHERE clause but not in the HAVING clause. True/False.
__________________________________________________________________________
13. Observe the following SELECT statement. What happens when there is no employee named
Kiran?
SELECT last_name, job_id
FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = Kiran);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
__________________________________________________________________________
@
ra Stu
r
a
s which the WHERE or HAVING
14. The subqueries are processed first by the Oracle
eg server,
hiafter
l
i
t
(
e
clause uses the results. True/False. ez
l to us
z
__________________________________________________________________________
on nse
G
ce
ra
i
r
l
a
eg rable
L
de nsfe
o
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II I - 26
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Differentiate system privileges from object privileges
Grant privileges on tables
Grant roles
Distinguish between privileges and roles
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
InIthis
n- you learn how to control database access to specific objects and add new users
o
n
with different levels of access privileges.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 2
Cas Training
Lesson Agenda
System privileges
Creating a role
Object privileges
Revoking object privileges
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 3
Cas Training
Database
administrator
a
s
a
)h
Users
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Access
era
f
d
s
Controlling
User
igo -tranenvironment, you want to maintain security of the database access and use.
InIamultiple-user
nonserver database security, you can do the following:
With Oracle
Control database access.
Give access to specific objects in the database.
Confirm given and received privileges with the Oracle data dictionary.
Database security can be classified into two categories: system security and data security.
System security covers access and use of the database at the system level, such as the username
and password, the disk space allocated to users, and the system operations that users can
perform. Database security covers access and use of the database objects and the actions that
those users can perform on the objects.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 4
Cas Training
Privileges
Database security:
System security
Data security
gu uid
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Privileges
o ran
ig nis-tthe
A Iprivilege
right to execute particular SQL statements. The database administrator (DBA)
o
n
is a high-level user with the ability to create users and grant users access to the database and its
objects. Users require system privileges to gain access to the database and object privileges to
manipulate the content of the objects in the database. Users can also be given the privilege to
grant additional privileges to other users or to roles, which are named groups of related
privileges.
Schemas
A schema is a collection of objects such as tables, views, and sequences. The schema is owned
by a database user and has the same name as that user.
A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type. An object privilege provides the user the ability to perform a
particular action on a specific schema object.
For more information, see the Oracle Database 2 Day DBA 11g Release 1 (11.1) reference
manual.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 5
Cas Training
System Privileges
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
System Privileges
o
an system privileges are available for users and roles. Typically, system
Iigthanon100-trdistinct
More
n are provided by the DBA.
privileges
Typical DBA Privileges
System Privilege
Operations Authorized
CREATE USER
DROP USER
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 6
Cas Training
Creating Users
The database administrator (DBA) creates users with the CREATE
USER statement.
CREATE USER user
IDENTIFIED BY
password;
CREATE USER demo
IDENTIFIED BY demo;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
CreatingoUsers
ig creates
trathe user by executing the CREATE USER statement. The user does not have
IDBA
The
n
no at this point. The DBA can then grant privileges to that user. These privileges
any privileges
determine what the user can do at the database level.
The slide gives the abridged syntax for creating a user.
In the syntax:
user
Is the name of the user to be created
Password
Specifies that the user must log in with this password
For more information, see the Oracle Database11g SQL Reference.
Note: Starting Oracle Database 11g, passwords are case sensitive. Uppercase and lowercase
characters are different characters when used in a password.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 7
Cas Training
CREATE
CREATE
CREATE
CREATE
CREATE
SESSION
TABLE
SEQUENCE
VIEW
PROCEDURE
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
ePrivileges
d
Typical User
o trans
g
i
- creates a user, the DBA can assign privileges to that user.
I theoDBA
After
n n
System Privilege
Operations Authorized
CREATE SESSION
CREATE TABLE
CREATE SEQUENCE
CREATE VIEW
CREATE PROCEDURE
In the syntax:
privilege
user
|role|PUBLIC
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nPrivileges
GrantingoSystem
s
g
a
i
r
-t the GRANT statement to allocate system privileges to the user. After the user has
IDBAouses
The
n
n the privileges, the user can immediately use those privileges.
been granted
In the example in the slide, the demo user has been assigned the privileges to create sessions,
tables, sequences, and views.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 9
Cas Training
Lesson Agenda
System privileges
Creating a role
Object privileges
Revoking object privileges
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 10
Cas Training
What Is a Role?
Users
Manager
a
s
a
)h
s
e
a ide
u
g
Privileges
ta t Gu
s
e
g denprivileges
Allocating privileges
Allocating
@
ra Stuwith a role
r
without a role
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
What Is a
Role?
o tran
igis a nnamed
- group of related privileges that can be granted to the user. This method makes
A Irole
o
n
it easier to revoke and maintain privileges.
A user can have access to several roles, and several users can be assigned the same role. Roles
are typically created for a database application.
Creating and Assigning a Role
First, the DBA must create the role. Then the DBA can assign privileges to the role and assign
the role to users.
Syntax
CREATE
ROLE role;
In the syntax:
role
Is the name of the role to be created
After the role is created, the DBA can use the GRANT statement to assign the role to users as
well as assign privileges to the role.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 11
Cas Training
Create a role:
a
s
a
)h
s
Grant a role to users:
e
a ide
u
g
ta t Gu
GRANT manager TO BELL, KOCHHAR;
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L era
Creatingoa d
Role nsf
ig -intrathe slide creates a manager role and then enables manager to create tables and
Iexample
The
on
views. n
It then grants Bell and Kochhar the role of managers. Now Bell and Kochhar can create
tables and views.
If users have multiple roles granted to them, they receive all the privileges associated with all the
roles.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 12
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LPassword
era
f
d
s
Changing
Your
n
aan
igo creates
r
t
IDBA
The
account and initializes a password for every user. You can change your
n
o
n
password by using the ALTER USER statement.
The slide example shows that the demo user changes his password by using the ALTER USER
statement.
Syntax
ALTER USER user IDENTIFIED BY password;
In the syntax:
user
password
Although this statement can be used to change your password, there are many other options. You
must have the ALTER USER privilege to change any other option.
For more information, see the Oracle Database11g SQL Reference manual.
Note: SQL*Plus has a PASSWORD command (PASSW) that can be used to change the password
of a user when the user is logged in. This command is not available in SQL Developer.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 13
Cas Training
Lesson Agenda
System privileges
Creating a role
Object privileges
Revoking object privileges
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 14
Cas Training
Object Privileges
Object
privilege
Table
View
Sequence
ALTER
DELETE
INDEX
a
s
a
)h
s
e
REFERENCES
a ide
u
g
ta t Gu
s
SELECT
e
g den
@
ra Stu
r
a
UPDATE
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Object Privileges
igo -tranis a privilege or right to perform a particular action on a specific table, view,
AnI
object privilege
noorn procedure. Each object has a particular set of grantable privileges. The table in the
sequence,
INSERT
slide lists the privileges for various objects. Note that the only privileges that apply to a
sequence are SELECT and ALTER. UPDATE, REFERENCES, and INSERT can be restricted by
specifying a subset of updatable columns.
A SELECT privilege can be restricted by creating a view with a subset of columns and granting
the SELECT privilege only on the view. A privilege granted on a synonym is converted to a
privilege on the base table referenced by the synonym.
Note: With the REFERENCES privilege, you can ensure that other users can create FOREIGN
KEY constraints that reference your table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 15
Cas Training
Object Privileges
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Privileges
s
GrantingoObject
n
g
a
i
r
-t privileges are available for different types of schema objects. A user
I oobject
Different
n
n has all object privileges for schema objects contained in the users schema. A user
automatically
can grant any object privilege on any schema object that the user owns to any other user or role.
If the grant includes WITH GRANT OPTION, then the grantee can further grant the object
privilege to other users; otherwise, the grantee can use the privilege but cannot grant it to other
users.
In the syntax:
object_priv
Is an object privilege to be granted
ALL
Specifies all object privileges
columns
Specifies the column from a table or view on which
privileges are granted
ON object
Is the object on which the privileges are granted
TO
Identifies to whom the privilege is granted
PUBLIC
Grants object privileges to all users
WITH GRANT OPTION
Enables the grantee to grant the object privileges to other
users and roles
Note: In the syntax, schema is the same as the owners name.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 16
Cas Training
GRANT
ON
TO
select
employees
demo;
GRANT
ON
TO
demo, manager;
gua ide
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Guidelines
an on an object, the object must be in your own schema, or you must have
igo -privileges
r
t
ITo grant
n
nogranted
been
the object privileges WITH GRANT OPTION.
An object owner can grant any object privilege on the object to any other user or role of the
database.
The owner of an object automatically acquires all object privileges on that object.
The first example in the slide grants the demo user the privilege to query your EMPLOYEES
table. The second example grants UPDATE privileges on specific columns in the
DEPARTMENTS table to demo and to the manager role.
For example, if your schema is oraxx, and the demo user now wants to use a SELECT
statement to obtain data from your EMPLOYEES table, then the syntax he or she must use is:
SELECT
* FROM oraxx.employees;
Alternatively, the demo user can create a synonym for the table and issue a SELECT statement
from the synonym:
CREATE SYNONYM emp FOR oraxx.employees;
SELECT * FROM emp;
Note: DBAs generally allocate system privileges; any user who owns an object can grant object
privileges.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 17
Cas Training
GRANT
ON
TO
WITH
select, insert
departments
demo
GRANT OPTION;
s
a
h
GRANT select
s)
e
a ide
ON
alice.departments
u
g
ta t Gu
TO
PUBLIC;
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Passingo
OndYournPrivileges
traOPTION Keyword
IigGRANT
WITH
n
no
A privilege that is granted with the WITH GRANT OPTION clause can be passed on to other
users and roles by the grantee. Object privileges granted with the WITH GRANT OPTION
clause are revoked when the grantors privilege is revoked.
The example in the slide gives the demo user access to your DEPARTMENTS table with the
privileges to query the table and add rows to the table. The example also shows that user1 can
give others these privileges.
PUBLIC Keyword
An owner of a table can grant access to all users by using the PUBLIC keyword.
The second example allows all users on the system to query data from Alices DEPARTMENTS
table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 18
Cas Training
Description
ROLE_SYS_PRIVS
ROLE_TAB_PRIVS
USER_ROLE_PRIVS
USER_SYS_PRIVS
a
s
a
)h
s
e
USER_TAB_PRIVS_RECD Object privileges granted to the user a
e
u
d
i
g
ta t Gofuthe users
s
the columns
USER_COL_PRIVS_MADE Object privileges granted on
e
g den
objects
@
ra Stu
r
a
is to the user on specific
USER_COL_PRIVS_RECD Object privileges
eg granted
h
l
i
t
(
e
columns
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfPrivileges
era
d
Confirming
Granted
o tran
igattempt
- to perform an unauthorized operation, such as deleting a row from a table for
If Iyou
non
USER_TAB_PRIVS_MADE
which you do not have the DELETE privilege, the Oracle server does not permit the operation to
take place.
If you receive the Oracle server error message Table or view does not exist, then you have
done either of the following:
Named a table or view that does not exist
Attempted to perform an operation on a table or view for which you do not have the
appropriate privilege
The data dictionary is organized in tables and views and contains information about the
database. You can access the data dictionary to view the privileges that you have. The table in
the slide describes various data dictionary views.
You learn more about data dictionary views in the lesson titled Managing Objects with Data
Dictionary Views.
Note: The ALL_TAB_PRIVS_MADE dictionary view describes all the object grants made by
the user or made on the objects owned by the user.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 19
Cas Training
Lesson Agenda
System privileges
Creating a role
Object privileges
Revoking object privileges
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 20
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Privileges
era
f
d
s
Revoking
Object
n
aprivileges
igoremove
r
t
Ican
You
granted to other users by using the REVOKE statement. When you
n
o
n
use the REVOKE statement, the privileges that you specify are revoked from the users you name
and from any other users to whom those privileges were granted by the revoked user.
In the syntax:
CASCADE
Is required to remove any referential integrity constraints made to
the CONSTRAINTS object by means of the REFERENCES privilege
For more information, see the Oracle Database11g SQL Reference.
Note: If a user were to leave the company and you revoke his or her privileges, you must regrant
any privileges that this user may have granted to other users. If you drop the user account
without revoking privileges from it, then the system privileges granted by this user to other users
are not affected by this action.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 21
Cas Training
select, insert
departments
demo;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Privileges
era (continued)
f
d
s
Revoking
Object
igo -intrathenslide revokes SELECT and INSERT privileges given to the demo user on
Iexample
The
non
the DEPARTMENTS
table.
Note: If a user is granted a privilege with the WITH GRANT OPTION clause, that user can also
grant the privilege with the WITH GRANT OPTION clause, so that a long chain of grantees is
possible, but no circular grants (granting to a grant ancestor) are permitted. If the owner revokes
a privilege from a user who granted the privilege to other users, then the revoking cascades to all
the privileges granted.
For example, if user A grants a SELECT privilege on a table to user B including the WITH
GRANT OPTION clause, user B can grant to user C the SELECT privilege with the WITH
GRANT OPTION clause as well, and user C can then grant to user D the SELECT privilege. If
user A revokes privileges from user B, then the privileges granted to users C and D are also
revoked.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 22
Cas Training
Quiz
Which of the following statements are true?
1. After a user creates an object, the user can pass along any
of the available object privileges to other users by using
the GRANT statement.
2. A user can create roles by using the CREATE ROLE
statement to pass along a collection of system or object
privileges to other users.
a
s
a
3. Users can change their own passwords.
)h
s
e
those
4. Users can view the privileges granted to them
aand
e
u
d
i
g
that are granted on their objects.
Gu
sta
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e3, L4 sfera
d
Answers:
1,
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 23
Cas Training
Summary
In this lesson, you should have learned about statements that
control access to the database and database objects.
Statement
Action
CREATE USER
GRANT
a
s
a
)h
s
e
Changes a users password
ALTER USER
a ide
u
g
ta t Gu
Removes privileges on an object from
users
REVOKE
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
o tran
Iigestablish
DBAs
n- initial database security for users by assigning privileges to the users.
o
n
The DBA creates users who must have a password. The DBA is also responsible for
CREATE ROLE
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 24
Cas Training
Practice 1: Overview
This practice covers the following topics:
Granting other users privileges to your table
Modifying another users table through the privileges
granted to you
Creating a synonym
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Practiceo1:dOverview
an students for this exercise about controlling access to database objects.
r
t
Iigup owith
Team
other
n n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 25
Cas Training
Practice 1
To complete question 8 and the subsequent ones, you need to connect to the database using
SQL Developer. If you are already not connected, perform the following tasks:
A. Click the SQL Developer desktop icon.
B. In the Connections Navigator, use the oraxx account and the corresponding password
provided by your instructor to log on to the database.
1. What privilege should a user be given to log on to the Oracle server? Is this a system
privilege or an object privilege?
_______________________________________________________________________
2. What privilege should a user be given to create tables?
_______________________________________________________________________
3. If you create a table, who can pass along privileges to other users on your table?
_______________________________________________________________________
a
4. You are the DBA. You are creating many users who require the same system privileges.
s
a
What should you use to make your job easier?
)h
s
e
_______________________________________________________________________
a ide
u
g
5. What command do you use to change your password?
ta t Gu
s
e
g den
_______________________________________________________________________
@
6. User1 is the owner of the EMP table and grants the
tuprivilege to User2 by using the
raDELETE
r
S
a
s
g the
WITH GRANT OPTION clause. User2 then
privilege on EMP to User3.
hiDELETE
legrants
i
t
(
e
z
User1 now finds that User3 has theleprivilege
and
s revokes it from User2. Which
u
o
z table?
t
user can now delete from thenEMP
e
o
s
G cen
_______________________________________________________________________
a
r
r
li privilege to update data in the DEPARTMENTS table. You
7. You want to grant
SCOTT
the
a
e
g
l
e SCOTT
also want to
Lenable
ab to grant this privilege to other users. What command do you
r
e
e
f
use?
o d trans
g
i
I_______________________________________________________________________
no
n
8. Grant another user query privilege on your table. Then, verify whether that user can use the
privilege.
Note: For this exercise, team up with another group. For example, if you are user ora21,
team up with another user ora22.
a. Grant another user privilege to view records in your REGIONS table. Include an option
for this user to further grant this privilege to other users.
b. Have the user query your REGIONS table.
c. Have the user pass on the query privilege to a third user (for example, ora23).
d. Take back the privilege from the user who performs step b.
Note: Each team can run exercises 9 and 10 independently.
9. Grant another user query and data manipulation privileges on your COUNTRIES table.
Make sure that the user cannot pass on these privileges to other users.
10. Take back the privileges on the COUNTRIES table granted to another user.
Note: For exercises 11 through 17, team up with another group.
11. Grant another user access to your DEPARTMENTS table. Have the user grant you query
access to his or her DEPARTMENTS table.
12. Query all the rows in your DEPARTMENTS table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 26
Cas Training
Practice 1 (continued)
13. Add a new row to your DEPARTMENTS table. Team 1 should add Education as department
number 500. Team 2 should add Human Resources as department number 510. Query the
other teams table.
a
s
a
14. Create a synonym for the other teams DEPARTMENTS table.
h
s) synonym.
15. Query all the rows in the other teams DEPARTMENTS table by usinge
your
a ide
u
g
Team 1 SELECT statement results:
u
ta
es ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 27
Cas Training
Practice 1 (continued)
16. Revoke the SELECT privilege from the other team.
17. Remove the row you inserted into the DEPARTMENTS table in step 13 and save the
changes.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 1 - 28
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Add constraints
Create indexes
Create indexes using the CREATE TABLE statement
a
s
a
)h
s
e
a ide
u
Create and use external tables
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
aninformation about creating indexes and constraints, and altering existing objects.
igo contains
r
t
This
Ilesson
on
You alsonlearn about external tables, and the provision to name the index at the time of creating a
primary key constraint.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 2
Cas Training
Lesson Agenda
Creating indexes
s
a
h
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Using the CREATE TABLE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 3
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eStatement
d
ALTER TABLE
o trans
g
i
After
Iyou ocreate
n- a table, you may need to change the table structure because you omitted a column,
n
your column definition needs to be changed, or you need to remove columns. You can do this by
using the ALTER TABLE statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 4
Cas Training
a
s
a
h
s
e
a ide
u
g
ta t Gu
ALTER TABLE table
s
e
g den
DROP
(column);
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eStatement
d
ALTER TABLE
o trans (continued)
g
i
You
columns
to a table, modify columns, and drop columns from a table by using the
Ican add
non
ALTER TABLE statement.
In the syntax:
table
ADD|MODIFY|DROP
column
datatype
DEFAULT expr
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 5
Cas Training
Adding a Column
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eAdding
d
Guidelines
for
o trans a Column
g
i
- or modify columns.
IYou cannadd
o
n
You cannot specify where the column is to appear. The new column becomes the last column.
The example in the slide adds a column named JOB_ID to the DEPT80 table. The JOB_ID column
becomes the last column in the table.
Note: If a table already contains rows when a column is added, then the new column is initially null
or takes the default value for all the rows. You can add a mandatory NOT NULL column to a table
that contains data in the other columns only if you specify a default value. You can add a NOT NULL
column to an empty table without the default value.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 6
Cas Training
Modifying a Column
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
ModifyingoadColumn
n
acolumn
ig modify
r
t
You
a
definition by using the ALTER TABLE statement with the MODIFY clause.
Ican
n
o
n
Column modification can include changes to a columns data type, size, and default value.
Guidelines
You can increase the width or precision of a numeric column.
You can increase the width of character columns.
You can decrease the width of a column if:
- The column contains only null values
- The table has no rows
- The decrease in column width is not less than the existing values in that column
You can change the data type if the column contains only null values. The exception to this is
CHAR-to-VARCHAR2 conversions, which can be done with data in the columns.
You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2 column
to the CHAR data type only if the column contains null values or if you do not change the size.
A change to the default value of a column affects only subsequent insertions to the table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 7
Cas Training
Dropping a Column
Use the DROP COLUMN clause to drop columns you no longer
need from the table:
ALTER TABLE
DROP COLUMN
dept80
job_id;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Droppingoa d
Column
an from a table by using the ALTER TABLE statement with the DROP COLUMN
ig drop -atcolumn
r
You
Ican
on
clause. n
Guidelines
The column may or may not contain data.
Using the ALTER TABLE DROP COLUMN statement, only one column can be dropped at a time.
The table must have at least one column remaining in it after it is altered.
After a column is dropped, it cannot be recovered.
A column cannot be dropped if it is part of a constraint or part of an index key unless the
cascade option is added.
Dropping a column can take a while if the column has a large number of values. In this case, it
may be better to set it to be unused and drop it when there are fewer users on the system to avoid
extended locks.
Note: Certain columns can never be dropped, such as columns that form part of the partitioning key
of a partitioned table or columns that form part of the primary key of an index-organized table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 8
Cas Training
ALTER
SET
OR
ALTER
SET
TABLE <table_name>
UNUSED(<column_name>);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
ALTER TABLE <table_name>
e
g den
DROP UNUSED COLUMNS;
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
SET UNUSED
Option
n
aoption
igoUNUSED
r
t
TheI
SET
marks one or more columns as unused so that they can be dropped when
non
TABLE <table_name>
UNUSED COLUMN <column_name>;
the demand on system resources is lower. Specifying this clause does not actually remove the target
columns from each row in the table (that is, it does not restore the disk space used by these columns).
Therefore, the response time is faster than if you executed the DROP clause. Unused columns are
treated as if they were dropped, even though their column data remains in the tables rows. After a
column has been marked as unused, you have no access to that column. A SELECT * query will not
retrieve data from unused columns. In addition, the names and types of columns marked unused will
not be displayed during a DESCRIBE statement, and you can add to the table a new column with the
same name as an unused column. The SET UNUSED information is stored in the
USER_UNUSED_COL_TABS dictionary view.
Note: The guidelines for setting a column to be UNUSED are similar to those for dropping a column.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 9
Cas Training
DROP UNUSED COLUMNS Option
DROP UNUSED COLUMNS removes from the table all columns currently marked as unused. You can
use this statement when you want to reclaim the extra disk space from unused columns in the table. If
the table contains no unused columns, the statement returns with no errors.
ALTER TABLE dept80
SET
UNUSED (last_name);
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 10
Cas Training
Lesson Agenda
Creating indexes
s
a
h
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Using the CREATE TABLE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 11
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
Adding aoConstraint
ig add a-constraint
tra
You
for existing tables by using the ALTER TABLE statement with the ADD
Ican
n
o
n
clause.
In the syntax:
table
constraint
type
column
The constraint name syntax is optional, although recommended. If you do not name your constraints,
the system generates constraint names.
Guidelines
You can add, drop, enable, or disable a constraint, but you cannot modify its structure.
You can add a NOT NULL constraint to an existing column by using the MODIFY clause of the
ALTER TABLE statement.
Note: You can define a NOT NULL column only if the table is empty or if the column has a value for
every row.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 12
Cas Training
Adding a Constraint
Add a FOREIGN KEY constraint to the EMP2 table indicating that
a manager must already exist as a valid employee in the EMP2
table.
ALTER TABLE emp2
MODIFY employee_id Primary Key;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de ns(continued)
Adding aoConstraint
ig example
train the slide modifies the EMP2 table to add a PRIMARY KEY constraint on the
TheI
first
n
no column. Note that because no constraint name is provided, the constraint is
EMPLOYEE_ID
ALTER TABLE emp2
ADD CONSTRAINT emp_mgr_fk
FOREIGN KEY(manager_id)
REFERENCES emp2(employee_id);
automatically named by the Oracle server. The second example in the slide creates a FOREIGN KEY
constraint on the EMP2 table. The constraint ensures that a manager exists as a valid employee in the
EMP2 table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 13
Cas Training
ON DELETE CASCADE
Delete child rows when a parent key is deleted:
ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fk
FOREIGN KEY (Department_id)
REFERENCES departments(department_id) ON DELETE CASCADE;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
ON DELETE
CASCADE
o tran
igDELETE
TheI
ON
n- CASCADE action allows parent key data that is referenced from the child table to
o
n
be deleted, but not updated. When data in the parent key is deleted, all rows in the child table that
depend on the deleted parent key values are also deleted. To specify this referential action, include
the ON DELETE CASCADE option in the definition of the FOREIGN KEY constraint.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 14
Cas Training
Deferring Constraints
Constraints can have the following attributes:
DEFERRABLE or NOT DEFERRABLE
INITIALLY DEFERRED or INITIALLY IMMEDIATE
ALTER TABLE dept2
ADD CONSTRAINT dept2_id_pk
PRIMARY KEY (department_id)
DEFERRABLE INITIALLY DEFERRED
Deferring constraint on
creation
a
s
a
)h
s
e
Changing
specific
a aattribute
SET CONSTRAINTS dept2_id_pk IMMEDIATE
e
u
constraintid
g
ta t Gu
s
e
n all constraints for a
g Changing
e
@
d
ALTER SESSION
ra Stusession
r
a
SET CONSTRAINTS= IMMEDIATE
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
DeferringoConstraints
ig defer-checking
tra constraints for validity until the end of the transaction. A constraint is
You
Ican
n
o
deferrednif the system checks that it is satisfied only on commit. If a deferred constraint is violated,
then commit causes the transaction to roll back. If a constraint is immediate (not deferred), then it is
checked at the end of each statement. If it is violated, the statement is rolled back immediately. If a
constraint causes an action (for example, DELETE CASCADE), that action is always taken as part of
the statement that caused it, whether the constraint is deferred or immediate. Use the SET
CONSTRAINTS statement to specify, for a particular transaction, whether a deferrable constraint is
checked following each DML statement or when the transaction is committed. To create deferrable
constraints, you must create a nonunique index for that constraint.
You can define constraints as either deferrable or not deferrable, and either initially deferred or
initially immediate. These attributes can be different for each constraint.
Usage scenario: Company policy dictates that department number 40 should be changed to 45.
Changing the DEPARTMENT_ID column affects employees assigned to this department. Therefore,
you make the primary key and foreign keys deferrable and initially deferred. You update both
department and employee information, and at the time of commit, all rows are validated.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 15
Cas Training
INITIALLY IMMEDIATE
a ide
u
g
CONSTRAINT bonus_ck
ta t Gu
s
e
CHECK (bonus > 0 )
@g tude);n
DEFERRABLE INITIALLYraDEFERRED
r sS
a
g
le e thi
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sINITIALLY
era
f
d
Difference
Between
DEFERRED and INITIALLY IMMEDIATE
o tran
g
i
A constraint
- is defined as deferrable can be specified as either INITIALLY DEFERRED or
I onthat
n IMMEDIATE. The INITIALLY IMMEDIATE clause is the default.
INITIALLY
In the slide example:
The sal_ck constraint is created as DEFERRABLE INITIALLY IMMEDIATE
The bonus_ck constraint is created as DEFERRABLE INITIALLY DEFERRED
After creating the emp_new_sal table as shown in the slide, you attempt to insert values into the
table and observe the results. When both the sal_ck and bonus_ck constraints are satisfied, the
rows are inserted without an error.
Example 1: Insert a row that violates sal_ck. In the CREATE TABLE statement, sal_ck is
specified as an initially immediate constraint. This means that the constraint is verified immediately
after the INSERT statement and you observe an error.
INSERT INTO emp_new_sal VALUES(90,5);
Example 2: Insert a row that violates bonus_ck. In the CREATE TABLE statement, bonus_ck is
specified as deferrable and also initially deferred. Therefore, the constraint is not verified until you
COMMIT or set the constraint state back to immediate.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 16
Cas Training
Difference Between INITIALLY DEFERRED and INITIALLY IMMEDIATE (continued)
INSERT INTO emp_new_sal VALUES(110, -1);
The row insertion is successful. But, you observe an error when you commit the transaction.
COMMIT;
The commit failed due to constraint violation. Therefore, at this point, the transaction is rolled back
by the database.
Example 3: Set the DEFERRED status to all constraints that can be deferred. Note that you can also
set the DEFERRED status to a single constraint if required.
SET CONSTRAINTS ALL DEFERRED;
a
s
a
Now, if you attempt to insert a row that violates the sal_ck constraint, the statement
) his executed
s
e
successfully.
a ide
u
g
INSERT INTO emp_new_sal VALUES(90,5);
ta t Gu
s
e
g den
@
tu
ra TheStransaction
But, you observe an error when you commit the transaction.
fails and is rolled back.
r
a
s
g
i
This is because both the constraints are checkedilupon
th
( e sCOMMIT.
e
COMMIT;
z
le to u
z
on nse
G
ce
ra
i
r
l
a
g able
eIMMEDIATE
L
Example 4: Set
the
status to both the constraints that were set as DEFERRED in the
e sfer
d
previous
oexample.
n
g
aCONSTRAINTS
i
r
t
SET
ALL IMMEDIATE;
I
non
You observe an error if you attempt to insert a row that violates either sal_ck or bonus_ck.
INSERT INTO emp_new_sal VALUES(110, -1);
Note: If you create a table without specifying constraint deferability, then the constraint is checked
immediately at the end of each statement. For example, with the CREATE TABLE statement of the
newemp_details table, if you do not specify the newemp_det_pk constraint deferability, then
the constraint is checked immediately.
CREATE TABLE newemp_details(emp_id NUMBER, emp_name
VARCHAR2(20),
CONSTRAINT newemp_det_pk PRIMARY KEY(emp_id));
When you attempt to defer the newemp_det_pk constraint that is not deferrable, you observe the
following error:
SET CONSTRAINT newemp_det_pk DEFERRED;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 17
Cas Training
Dropping a Constraint
s
a
h
s)
ALTER TABLE dept2
e
a ide
u
DROP PRIMARY KEY CASCADE;
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Droppingoa d
Constraint
an you can identify the constraint name from the USER_CONSTRAINTS and
r
t
iga constraint,
To Idrop
non
USER_CONS_COLUMNS data dictionary views. Then use the ALTER TABLE statement with the
DROP clause. The CASCADE option of the DROP clause causes any dependent constraints also to be
dropped.
Syntax
ALTER TABLE table
DROP PRIMARY KEY | UNIQUE (column) |
CONSTRAINT
constraint [CASCADE];
In the syntax:
table
column
constraint
When you drop an integrity constraint, that constraint is no longer enforced by the Oracle server and
is no longer available in the data dictionary.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 18
Cas Training
Disabling Constraints
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Disablingoa d
Constraint
n
aconstraint
ig disable
r
t
You
a
without dropping it or re-creating it by using the ALTER TABLE
Ican
n
nowith
statement
the DISABLE clause.
Syntax
ALTER
TABLE
table
DISABLE CONSTRAINT constraint [CASCADE];
In the syntax:
table
constraint
Guidelines
You can use the DISABLE clause in both the CREATE TABLE statement and the ALTER
TABLE statement.
The CASCADE clause disables dependent integrity constraints.
Disabling a unique or primary key constraint removes the unique index.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 19
Cas Training
Enabling Constraints
ALTER TABLE
emp2
ENABLE CONSTRAINT emp_dt_fk;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
Enablingo
a Constraint
ig enable-traaconstraint without dropping it or re-creating it by using the ALTER TABLE
You
Ican
n
nowith
statement
the ENABLE clause.
Syntax
ALTER
ENABLE
TABLE
table
CONSTRAINT constraint;
In the syntax:
table
constraint
Guidelines
If you enable a constraint, that constraint applies to all the data in the table. All the data in the
table must comply with the constraint.
If you enable a UNIQUE key or a PRIMARY KEY constraint, a UNIQUE or PRIMARY KEY
index is created automatically. If an index already exists, then it can be used by these keys.
You can use the ENABLE clause in both the CREATE TABLE statement and the ALTER TABLE
statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 20
Cas Training
Enabling a Constraint (continued)
Guidelines (continued)
Enabling a primary key constraint that was disabled with the CASCADE option does not enable
any foreign keys that are dependent on the primary key.
To enable a UNIQUE or PRIMARY KEY constraint, you must have the privileges necessary to
create an index on the table.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 21
Cas Training
Cascading Constraints
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Cascading
Constraints
an the usage of the CASCADE CONSTRAINTS clause. Assume that the
igo -tillustrates
r
This
Istatement
onis created as follows:
TEST1 n
table
CREATE TABLE test1 (
col1_pk NUMBER PRIMARY KEY,
col2_fk NUMBER,
col1 NUMBER,
col2 NUMBER,
CONSTRAINT fk_constraint FOREIGN KEY (col2_fk) REFERENCES
test1,
CONSTRAINT ck1 CHECK (col1_pk > 0 and col1 > 0),
CONSTRAINT ck2 CHECK (col2_fk > 0));
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 22
Cas Training
Cascading Constraints
Example:
ALTER TABLE emp2
DROP COLUMN employee_id CASCADE CONSTRAINTS;
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfe(continued)
d
Cascading
Constraints
o tran
Submitting
Iig othe
n- following statement drops the EMPLOYEE_ID column, the primary key constraint,
and any n
foreign key constraints referencing the primary key constraint for the EMP2 table:
ALTER TABLE emp2 DROP COLUMN employee_id CASCADE CONSTRAINTS;
If all columns referenced by the constraints defined on the dropped columns are also dropped, then
CASCADE CONSTRAINTS is not required. For example, assuming that no other referential
constraints from other tables refer to the COL1_PK column, it is valid to submit the following
statement without the CASCADE CONSTRAINTS clause for the TEST1 table created on the previous
page:
ALTER TABLE test1 DROP (col1_pk, col2_fk, col1);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 23
Cas Training
es e
a
ALTER TABLE marketing RENAME CONSTRAINTgumktg_pk
id
u
a
t
G
s
TO new_mktg_pk;
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LColumns
era and Constraints
f
d
Renaming
Table
s
go rename
aantable column, the new name must not conflict with the name of any existing
r
t
When
Iiyou
n
column n
inothe table. You cannot use any other clauses in conjunction with the RENAME COLUMN
clause.
The slide examples use the marketing table with the primary key mktg_pk defined on the id
column.
CREATE TABLE marketing (team_id NUMBER(10),
target VARCHAR2(50),
CONSTRAINT mktg_pk PRIMARY KEY(team_id));
Example a shows that the id column of the marketing table is renamed mktg_id. Example b
shows that mktg_pk is renamed new_mktg_pk.
When you rename any existing constraint for a table, the new name must not conflict with any of
your existing constraint names. You can use the RENAME CONSTRAINT clause to rename systemgenerated constraint names.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 24
Cas Training
Lesson Agenda
Creating indexes
s
a
h
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Using the CREATE TABLE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 25
Cas Training
Overview of Indexes
Indexes are created:
Automatically
PRIMARY KEY creation
UNIQUE KEY creation
Manually
The CREATE INDEX statement
The CREATE TABLE statement
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
OverviewoofdIndexes
an can be created. One type is a unique index. The Oracle server automatically
ig of indexes
r
t
Two
Itypes
on index when you define a column or group of columns in a table to have a PRIMARY
creates anunique
KEY or a UNIQUE key constraint. The name of the index is the name given to the constraint.
The other type of index is a nonunique index, which a user can create. For example, you can create
an index for a FOREIGN KEY column to be used in joins to improve retrieval speed.
You can create an index on one or more columns by issuing the CREATE INDEX statement.
For more information, see Oracle Database 11g SQL Reference.
Note: You can manually create a unique index, but it is recommended that you create a unique
constraint, which implicitly creates a unique index.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 26
Cas Training
a
s
a
)h
s
e
SELECT INDEX_NAME, TABLE_NAME
a ide
u
g
FROM
USER_INDEXES
ta t Gu
s
e
WHERE TABLE_NAME = 'NEW_EMP';
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e with
d
CREATE INDEX
o transthe CREATE TABLE Statement
g
i
In the
I example
n- in the slide, the CREATE INDEX clause is used with the CREATE TABLE statement
o
n
to create a primary key index explicitly. You can name your indexes at the time of primary key
creation to be different from the name of the PRIMARY KEY constraint.
You can query the USER_INDEXES data dictionary view for information about your indexes.
Note: You learn more about USER_INDEXES in the lesson titled Managing Objects with Data
Dictionary Views.
The following example illustrates the database behavior if the index is not explicitly named:
CREATE TABLE EMP_UNNAMED_INDEX
(employee_id NUMBER(6) PRIMARY KEY ,
first_name VARCHAR2(20),
last_name VARCHAR2(25));
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 27
Cas Training
CREATE INDEX with the CREATE TABLE Statement (continued)
Observe that the Oracle server gives a generic name to the index that is created for the PRIMARY
KEY column.
You can also use an existing index for your PRIMARY KEY columnfor example, when you are
expecting a large data load and want to speed up the operation. You may want to disable the
constraints while performing the load and then enable them, in which case having a unique index on
the primary key will still cause the data to be verified during the load. So you can first create a
nonunique index on the column designated as PRIMARY KEY, and then create the PRIMARY KEY
column and specify that it should use the existing index. The following examples illustrate this
process:
Step 1: Create the table:
CREATE TABLE NEW_EMP2
(employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name
VARCHAR2(25)
);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
Step 2: Create the index:
@
ra Stu
CREATE INDEX emp_id_idx2 ON
r
a
new_emp2(employee_id); ileg
his
t
(
e
ez o us
l
z et
Step 3: Create the primary key:on
s
G cenADD
ALTER TABLE
new_emp2
PRIMARY KEY (employee_id) USING INDEX
a
r
i
r
l
a
emp_id_idx2;
eg rable
L
de nsfe
o
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 28
Cas Training
Function-Based Indexes
a
s
a
)h
s
SELECT *
e
a ide
u
FROM
dept2
g
ta t Gu
s
WHERE UPPER(department_name) = 'SALES';
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LIndexes
era
f
d
Function-Based
s
o ran
Function-based
defined with the UPPER(column_name)or LOWER(column_name)
Iig on-tindexes
n
keywords allow non-case-sensitive searches. For example, consider the following index:
CREATE INDEX upper_last_name_idx ON emp2 (UPPER(last_name));
This facilitates processing queries such as:
SELECT * FROM emp2 WHERE UPPER(last_name) = 'KING';
The Oracle server uses the index only when that particular function is used in a query. For example,
the following statement may use the index, but without the WHERE clause, the Oracle server may
perform a full table scan:
SELECT
*
FROM
employees
WHERE
UPPER (last_name) IS NOT NULL
ORDER BY UPPER (last_name);
Note: The QUERY_REWRITE_ENABLED initialization parameter must be set to TRUE for a
function-based index to be used.
The Oracle server treats indexes with columns marked DESC as function-based indexes. The
columns marked DESC are sorted in descending order.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 29
Cas Training
Removing an Index
a
s
a
)h
s
e
a ide
u
g
u or
taof thet G
s
To drop an index, you must be the owner
index
e
g den
@
have the DROP ANY INDEX privilege.
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eIndex
d
Removing
an
o trans
g
i
- indexes. To change an index, you must drop it and then re-create it. Remove an
You
Icannotonmodify
n
index definition
from the data dictionary by issuing the DROP INDEX statement. To drop an index,
DROP INDEX upper_dept_name_idx;
you must be the owner of the index or have the DROP ANY INDEX privilege.
In the syntax:
index
Note: If you drop a table, then indexes, constraints, and triggers are automatically dropped, but views
and sequences remain.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 30
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LPURGE
era
f
d
DROP TABLE
s
o tran
Oracle
IigDatabase
n- provides a feature for dropping tables. When you drop a table, the database does not
o
n
immediately release the space associated with the table. Rather, the database renames the table and
places it in a recycle bin, where it can later be recovered with the FLASHBACK TABLE statement if
you find that you dropped the table in error. If you want to immediately release the space associated
with the table at the time you issue the DROP TABLE statement, then include the PURGE clause as
shown in the statement in the slide.
Specify PURGE only if you want to drop the table and release the space associated with it in a single
step. If you specify PURGE, then the database does not place the table and its dependent objects into
the recycle bin.
Using this clause is equivalent to first dropping the table and then purging it from the recycle bin.
This clause saves you one step in the process. It also provides enhanced security if you want to
prevent sensitive material from appearing in the recycle bin.
Note: You cannot roll back a DROP TABLE statement with the PURGE clause, and you cannot
recover the table if you drop it with the PURGE clause. This feature was not available in earlier
releases.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 31
Cas Training
Lesson Agenda
Creating indexes
s
a
h
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Using the CREATE TABLE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 32
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
SCN
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Statement
era
f
d
FLASHBACK
TABLE
s
o tran
Oracle
IigFlashback
n- Table enables you to recover tables to a specified point in time with a single
o
n
statement. You can restore table data along with associated indexes, and constraints, while the
database is online, undoing changes to only the specified tables.
The Flashback Table feature is similar to a self-service repair tool. For example, if a user accidentally
deleted important rows from a table and then wanted to recover the deleted rows, you can use the
FLASHBACK TABLE statement to restore the table to the time before the deletion and see the
missing rows in the table.
When using the FLASHBACK TABLE statement, you can revert the table and its contents to a certain
time or to an SCN.
Note: The system change number (SCN) is an integer value associated with each change to the
database. It is a unique incremental number in the database. Every time you commit a transaction, a
new SCN is recorded.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 33
Cas Training
Syntax:
FLASHBACK TABLE[schema.]table[,
[ schema.]table ]...
TO { TIMESTAMP | SCN } expr
[ { ENABLE | DISABLE } TRIGGERS ];
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Statement
era (continued)
f
d
FLASHBACK
TABLE
s
o tran
Self-Service
Facility
Iig onRepair
n
Oracle Database provides a SQL data definition language (DDL) command, FLASHBACK TABLE, to
restore the state of a table to an earlier point in time in case it is inadvertently deleted or modified.
The FLASHBACK TABLE command is a self-service repair tool to restore data in a table along with
associated attributes such as indexes or views. This is done while the database is online by rolling
back only the subsequent changes to the given table. Compared to traditional recovery mechanisms,
this feature offers significant benefits such as ease of use, availability, and faster restoration. It also
takes the burden off the DBA to find and restore application-specific properties. The flashback table
feature does not address physical corruption caused because of a bad disk.
Syntax
You can invoke a FLASHBACK TABLE operation on one or more tables, even on tables in different
schemas. You specify the point in time to which you want to revert by providing a valid time stamp.
By default, database triggers are disabled during the flashback operation for all tables involved. You
can override this default behavior by specifying the ENABLE TRIGGERS clause.
Note: For more information about recycle bin and flashback semantics, refer to Oracle Database
Administrators Guide 11g Release 1 (11.1).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 34
Cas Training
s
a
h
s)
a ide
u
g
ta t Gu
FLASHBACK TABLE emp2 TO BEFORE DROP;
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra Statement
de nsfeTABLE
Using theoFLASHBACK
tra
Syntax
Examples
Iigand
n
no restores the EMP2 table to a state before a DROP statement.
The example
The recycle bin is actually a data dictionary table containing information about dropped objects.
Dropped tables and any associated objectssuch as, indexes, constraints, nested tables, and so on
are not removed and still occupy space. They continue to count against user space quotas until
specifically purged from the recycle bin or the situation where they must be purged by the database
because of tablespace space constraints.
Each user can be thought of as an owner of a recycle bin because, unless a user has the SYSDBA
privilege, the only objects that the user has access to in the recycle bin are those that the user owns. A
user can view his or her objects in the recycle bin by using the following statement:
SELECT * FROM RECYCLEBIN;
When you drop a user, any objects belonging to that user are not placed in the recycle bin and any
objects in the recycle bin are purged.
You can purge the recycle bin with the following statement:
PURGE RECYCLEBIN;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 35
Cas Training
Lesson Agenda
Creating indexes
s
a
h
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Using the CREATE TABLE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 36
Cas Training
External Tables
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
External Tables
o tran
ig ntable
- is a read-only table whose metadata is stored in the database but whose data is
AnIexternal
o
n
stored outside the database. This external table definition can be thought of as a view that is used for
running any SQL query against external data without requiring that the external data first be loaded
into the database. The external table data can be queried and joined directly and in parallel without
requiring that the external data first be loaded in the database. You can use SQL, PL/SQL and Java to
query the data in an external table.
The main difference between external tables and regular tables is that externally organized tables are
read-only. No data manipulation language (DML) operations are possible, and no indexes can be
created on them. However, you can create an external table, and thus unload data, by using the
CREATE TABLE AS SELECT command.
The Oracle server provides two major access drivers for external tables. One, the loader access driver
(or ORACLE_LOADER) is used for reading data from external files whose format can be interpreted
by the SQL*Loader utility. Note that not all SQL*Loader functionality is supported with external
tables. The ORACLE_DATAPUMP access driver can be used to both import and export data using a
platform-independent format. The ORACLE_DATAPUMP access driver writes rows from a SELECT
statement to be loaded into an external table as part of a CREATE TABLE ...ORGANIZATION
EXTERNAL...AS SELECT statement. You can then use SELECT to read data out of that data file.
You can also create an external table definition on another system and use that data file. This allows
data to be moved between Oracle databases.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 37
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L san
erExternal
f
Example o
of d
Creating
Table
n
g
a
i
r
UseI
the CREATE
-t DIRECTORY statement to create a directory object. A directory object specifies an
n
o
alias forna directory on the servers file system where an external data source resides. You can use
GRANT READ ON DIRECTORY emp_dir TO hr;
directory names when referring to an external data source, rather than hard code the operating system
path name, for greater file management flexibility.
You must have CREATE ANY DIRECTORY system privileges to create directories. When you create
a directory, you are automatically granted the READ and WRITE object privileges and can grant
READ and WRITE privileges to other users and roles. The DBA can also grant these privileges to
other users and roles.
A user needs READ privileges for all directories used in external tables to be accessed and WRITE
privileges for the log, bad, and discard file locations being used.
In addition, a WRITE privilege is necessary when the external table framework is being used to
unload data.
Oracle also provides the ORACLE_DATAPUMP type, with which you can unload data (that is, read
data from a table in the database and insert it into an external table) and then reload it into an Oracle
database. This is a one-time operation that can be done when the table is created. After the creation
and initial population is done, you cannot update, insert, or delete any rows.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 38
Cas Training
Example of Creating an External Table (continued)
Syntax
CREATE [OR REPLACE] DIRECTORY AS 'path_name';
In the syntax:
OR REPLACE
directory
'path_name'
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 39
Cas Training
ta t G
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sTable
era
f
Creating o
andExternal
antables using the ORGANIZATION EXTERNAL clause of the CREATE TABLE
ig external
r
t
You
Icreate
n
noYou
statement.
are not, in fact, creating a table. Rather, you are creating metadata in the data
dictionary that you can use to access external data. You use the ORGANIZATION clause to specify
the order in which the data rows of the table are stored. By specifying EXTERNAL in the
ORGANIZATION clause, you indicate that the table is a read-only table located outside the database.
Note that the external files must already exist outside the database.
TYPE <access_driver_type> indicates the access driver of the external table. The access
driver is the application programming interface (API) that interprets the external data for the
database. If you do not specify TYPE, Oracle uses the default access driver, ORACLE_LOADER. The
other option is ORACLE_DATAPUMP.
You use the DEFAULT DIRECTORY clause to specify one or more Oracle database directory objects
that correspond to directories on the file system where the external data sources may reside.
The optional ACCESS PARAMETERS clause enables you to assign values to the parameters of the
specific access driver for this external table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 40
Cas Training
Creating an External Table (continued)
Use the LOCATION clause to specify one external locator for each external data source. Usually,
<location_specifier> is a file, but it need not be.
The REJECT LIMIT clause enables you to specify how many conversion errors can occur during a
query of the external data before an Oracle error is returned and the query is aborted. The default
value is 0.
The syntax for using the ORACLE_DATAPUMP access driver is as follows:
CREATE TABLE extract_emps
ORGANIZATION EXTERNAL (TYPE ORACLE_DATAPUMP
DEFAULT DIRECTORY
ACCESS PARAMETERS ( )
LOCATION ()
PARALLEL 4
REJECT LIMIT UNLIMITED
s
a
h
AS
s)
e
a ide
SELECT * FROM ;
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 41
Cas Training
a ide
(fname POSITION ( 1:20) CHAR,
u
g
lname POSITION (22:41) CHAR))
ta t Gu
s
e
g den
LOCATION ('emp.dat'))
@
ra Stu
PARALLEL 5
r
a
REJECT LIMIT 200;
ileg this
( se
z
e
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e san
fe External Table by Using the ORACLE_LOADER Access Driver
Example o
of d
Creating
n
trais a flat file that has records in the following format:
Assume
there
Iigthat
n
no 10,jones,11-Dec-1934
20,smith,12-Jun-1972
Records are delimited by new lines, and the fields are all terminated by a comma ( , ). The name of
the file is /emp_dir/emp.dat.
To convert this file as the data source for an external table, whose metadata will reside in the
database, you must perform the following steps:
1. Create a directory object, emp_dir, as follows:
CREATE DIRECTORY emp_dir AS '/emp_dir' ;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 42
Cas Training
Example of Creating an External Table by Using the ORACLE_LOADER Access Driver
(continued)
In the example, the TYPE specification is given only to illustrate its use. ORACLE_LOADER is the
default access driver if not specified. The ACCESS PARAMETERS option provides values to
parameters of the specific access driver, which are interpreted by the access driver, not by the Oracle
server.
The PARALLEL clause enables five parallel execution servers to simultaneously scan the external
data sources (files) when executing the INSERT INTO TABLE statement. For example, if
PARALLEL=5 were specified, then more than one parallel execution server can be working on a data
source. Because external tables can be very large, for performance reasons, it is advisable to specify
the PARALLEL clause, or a parallel hint for the query.
The REJECT LIMIT clause specifies that if more than 200 conversion errors occur during a query of
the external data, then the query be aborted and an error be returned. These conversion errors can
arise when the access driver tries to transform the data in the data file to match the external table
a
definition.
s
a
) h can be
After the CREATE TABLE command executes successfully, the OLDEMP externalstable
e
described and queried like a relational table.
ua de
ag Gui
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 43
Cas Training
SELECT *
FROM oldemp
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
OLDEMP
a
emp.dat
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nTables
QueryingoExternal
s
g
a
i
r
-t does not describe any data that is stored in the database. It does not describe how
AnIexternal
table
n
o
n in the external source. Instead, it describes how the external table layer must present
data is stored
the data to the server. It is the responsibility of the access driver and the external table layer to do the
necessary transformations required on the data in the data file so that it matches the external table
definition.
When the database server accesses data in an external source, it calls the appropriate access driver to
get the data from an external source in a form that the database server expects.
It is important to remember that the description of the data in the data source is separate from the
definition of the external table. The source file can contain more or fewer fields than there are
columns in the table. Also, the data types for fields in the data source can be different from the
columns in the table. The access driver takes care of ensuring that the data from the data source is
processed so that it matches the definition of the external table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 44
Cas Training
a ide
AS
u
g
SELECT employee_id, first_name, last_name
ta t Gu
s
e
g
FROM
employees;
en
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sTable
era by Using ORACLE_DATAPUMP: Example
f
Creating o
andExternal
athenunload and reload operations with external tables by using the
ig perform
r
t
You
Ican
non
ORACLE_DATAPUMP
access driver.
Note: In the context of external tables, loading data refers to the act of data being read from an
external table and loaded into a table in the database. Unloading data refers to the act of reading data
from a table and inserting it into an external table.
The example in the slide illustrates the table specification to create an external table by using the
ORACLE_DATAPUMP access driver. Data is then populated into the two files: emp1.exp and
emp2.exp.
To populate data read from the EMPLOYEES table into an external table, you must perform the
following steps:
1. Create a directory object, emp_dir, as follows:
CREATE DIRECTORY emp_dir AS '/emp_dir' ;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 45
Cas Training
Quiz
A FOREIGN KEY constraint enforces the following action:
When the data in the parent key is deleted, all the rows in the
child table that depend on the deleted parent key values are
also deleted.
1. True
2. False
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Answer: 2
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 46
Cas Training
Quiz
In all the cases, when you execute a DROP TABLE command,
the database renames the table and places it in a recycle bin,
from where it can later be recovered by using the FLASHBACK
TABLE statement.
1. True
2. False
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Answer: 2
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 47
Cas Training
Summary
In this lesson, you should have learned how to:
Add constraints
Create indexes
Create indexes by using the CREATE TABLE statement
a
s
a
)h
s
Create and use external tables
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Summaryo d
n
alearned
r
t
In this
you
how to perform the following tasks for schema object management:
Iiglesson,
n
o
n
Alter tables to add or modify columns or constraints.
Create indexes and function-based indexes by using the CREATE INDEX statement.
Drop unused columns.
Use FLASHBACK mechanics to restore tables.
Use the ORGANIZATION EXTERNAL clause of the CREATE TABLE statement to create an
external table. An external table is a read-only table whose metadata is stored in the database but
whose data is stored outside the database.
Use external tables to query data without first loading it into the database.
Name your PRIMARY KEY column indexes when you create the table with the CREATE TABLE
statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 48
Cas Training
Practice 2: Overview
This practice covers the following topics:
Altering tables
Adding columns
Dropping columns
Creating indexes
Creating external tables
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Practice 2:
Overview
o tran
In this
- you use the ALTER TABLE command to modify columns and add constraints. You
Iigpractice,
non INDEX command to create indexes when creating a table, along with the CREATE
use the CREATE
TABLE command. You create external tables.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 49
Cas Training
Practice 2
1. Create the DEPT2 table based on the following table instance chart. Enter the syntax in the SQL
Worksheet. Then, execute the statement to create the table. Confirm that the table is created.
Column Name
ID
NAME
Data type
NUMBER
VARCHAR2
Length
25
Key Type
Nulls/Unique
FK Table
FK Column
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
2. Populate the DEPT2 table with data from theeDEPARTMENTS
g this table. Include only the columns
l
i
(
that you need.
e
z
s
e
l
u
3. Create the EMP2 table based on z
the
following
to table instance chart. Enter the syntax in the SQL
n
e
o
Worksheet. Then executeG
the statement
ns to create the table. Confirm that the table is created.
e
a
c
r
r le li
a
g
LAST_NAME
FIRST_NAME
DEPT_ID
Column Name
Le fID
ab
r
e
e
d ns
Key
o Type
g
i
tra
I Nulls/Unique
n
no
FK Table
FK Column
Data type
NUMBER
VARCHAR2
VARCHAR2
NUMBER
Length
25
25
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 50
Cas Training
Practice 2 (continued)
4. Modify the EMP2 table to allow for longer employee last names. Confirm your modification.
5. Create the EMPLOYEES2 table based on the structure of the EMPLOYEES table. Include only
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and DEPARTMENT_ID
columns. Name the columns in your new table ID, FIRST_NAME, LAST_NAME, SALARY,
and DEPT_ID, respectively.
6. Drop the EMP2 table.
7. Query the recycle bin to see whether the table is present.
sa
ha
)
s
e e
a
u
ag Guid
t
s
e ent
g
8. Restore the EMP2 table to a state before the DROP statement.
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
igo -tran
I
9. Dropothe
n FIRST_NAME column from the EMPLOYEES2 table. Confirm your modification by
n
checking the description of the table.
10. In the EMPLOYEES2 table, mark the DEPT_ID column as UNUSED. Confirm your
modification by checking the description of the table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 51
Cas Training
Practice 2 (continued)
11. Drop all the UNUSED columns from the EMPLOYEES2 table. Confirm your modification by
checking the description of the table.
12. Add a table-level PRIMARY KEY constraint to the EMP2 table on the ID column. The
constraint should be named at creation. Name the constraint my_emp_id_pk.
13. Create a PRIMARY KEY constraint to the DEPT2 table using the ID column. The constraint
should be named at creation. Name the constraint my_dept_id_pk.
a to
14. Add a foreign key reference on the EMP2 table that ensures that the employee is notsassigned
a
a nonexistent department. Name the constraint my_emp_dept_id_fk. ) h
estype,eprecision
15. Modify the EMP2 table. Add a COMMISSION column of the NUMBERadata
2,
u
scale 2. Add a constraint to the COMMISSION column that ensures
value is
uid
agthat aGcommission
t
s
greater than zero.
e ent
g
16. Drop the EMP2 and DEPT2 tables so that they cannot
be restored.
a@
ud Verify the recycle bin.
t
r
r
S
a
17. Create the DEPT_NAMED_INDEX table based
table instance chart. Name the
s
gon the following
index for the PRIMARY KEY column as DEPT_PK_IDX.
(ile e thi
ez o us
l
nz se t
Deptno
Column Name
o
a G Yeslicen
Primary Key arr
eg rableNumber
L
Data Type
de nsfe
o
4
Length
Iig on-tra
n
Dname
VARCHAR2
30
18. Create an external table library_items_ext. Use the ORACLE_LOADER access driver.
Note: The emp_dir directory and library_items.dat are already created for this
exercise. library_items.dat has records in the following format:
2354,
2355,
2355,
a. Open the lab_02_18.sql file. Observe the code snippet to create the
library_items_ext external table. Then replace <TODO1>, <TODO2>, <TODO3>,
and <TODO4> as appropriate and save the file as lab_02_18_soln.sql. Run the
script to create the external table.
b. Query the library_items_ext table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 52
Cas Training
Practice 2 (continued)
19. The HR department needs a report of addresses of all departments. Create an external table as
dept_add_ext using the ORACLE_DATAPUMP access driver. The report should show the
location ID, street address, city, state or province, and country in the output. Use a NATURAL
JOIN to produce the results.
Note: The emp_dir directory is already created for this exercise.
a. Open the lab_02_19.sql file. Observe the code snippet to create the dept_add_ext
external table. Then, replace <TODO1>, <TODO2>, and <TODO3> with the appropriate
code. Replace <oraxx_emp4.exp> and <oraxx_emp5.exp> with the appropriate file
names. For example, if you are the ora21 user, your file names are ora21_emp4.exp
and ora21_emp5.exp. Save the script as lab_02_19_soln.sql.
b. Run the lab_02_19_soln.sql script to create the external table.
c. Query the dept_add_ext table.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
g twothfiles
is oraxx_emp4.exp and
Note: When you perform the preceding
lestep,
i
(
e
z theudefault
s directory emp_dir.
oraxx_emp5.exp are created
eunder
l
o
z
t
onand populate
se it with data. Set the primary key as deferred and
G
n
20. Create the emp_books
table
e
rraat the
lic of the transaction.
observe what happens
end
a
e
g
l
e rab
a. Run theLlab_02_20_a.sql
file to create the emp_books table. Observe that the
e
e
f
d
s
primary key is not created as deferrable.
oemp_books_pk
n
g
a
i
r
t
I
non
b. Run the lab_02_20_b.sql file to populate data into the emp_books table. What do
you observe?
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 53
Cas Training
Practice 2 (continued)
c. Set the emp_books_pk constraint as deferred. What do you observe?
s
a
h
s)
e
a ide
u
g
ta t Gu
s
f. Set the emp_books_pk constraint as deferred.
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 2 - 54
Cas Training
Managing Objects
with Data Dictionary Views
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Use the data dictionary views to research data on your
objects
Query various data dictionary views
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
InIthis
n- you are introduced to the data dictionary views. You learn that the dictionary
o
n
views can be used to retrieve metadata and create reports about your schema objects.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 2
Cas Training
Lesson Agenda
View information
Sequence information
Synonym information
Index information
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
Adding a comment to a table and
tu the dictionary
raquerying
r
S
a
views for comment information
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 3
Cas Training
Data Dictionary
Oracle server
Tables containing
business data:
EMPLOYEES
DEPARTMENTS
LOCATIONS
JOB_HISTORY
...
Data dictionary
views:
DICTIONARY
s
USER_OBJECTS) ha
es e
USER_TABLES
a
USER_TAB_COLUMNS
gu uid
a
t
es nt G
g...
a@ Stude
r
r
a
g
e
his
l
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Data Dictionary
go are
an created by the user and contain business data, such as EMPLOYEES. There
r
t
Iitables
User
tables
n
nocollection
is another
of tables and views in the Oracle database known as the data dictionary.
This collection is created and maintained by the Oracle server and contains information about
the database. The data dictionary is structured in tables and views, just like other database data.
Not only is the data dictionary central to every Oracle database, but it is an important tool for all
users, from end users to application designers and database administrators.
You use SQL statements to access the data dictionary. Because the data dictionary is read-only,
you can issue only queries against its tables and views.
You can query the dictionary views that are based on the dictionary tables to find information
such as:
Definitions of all schema objects in the database (tables, views, indexes, synonyms,
sequences, procedures, functions, packages, triggers, and so on)
Default values for columns
Integrity constraint information
Names of Oracle users
Privileges and roles that each user has been granted
Other general database information
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 4
Cas Training
Oracle server
Consists of:
Base tables
User-accessible views
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LStructure
era
f
d
s
Data Dictionary
o tran
- tables store information about the associated database. Only the Oracle server
Iig onbase
Underlying
n
should write to and read from these tables. You rarely access them directly.
There are several views that summarize and display the information stored in the base tables of
the data dictionary. These views decode the base table data into useful information (such as user
or table names) using joins and WHERE clauses to simplify the information. Most users are given
access to the views rather than the base tables.
The Oracle user SYS owns all base tables and user-accessible views of the data dictionary. No
Oracle user should ever alter (UPDATE, DELETE, or INSERT) any rows or schema objects
contained in the SYS schema because such activity can compromise data integrity.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 5
Cas Training
Purpose
ALL
DBA
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LStructure
era (continued)
f
d
s
Data Dictionary
anconsists of sets of views. In many cases, a set consists of three views
igodictionary
r
t
Idata
The
nonsimilar information and distinguished from each other by their prefixes. For example,
containing
V$
Performance-related data
there is a view named USER_OBJECTS, another named ALL_OBJECTS, and a third named
DBA_OBJECTS.
These three views contain similar information about objects in the database, except that the
scope is different. USER_OBJECTS contains information about objects that you own or created.
ALL_OBJECTS contains information about all objects to which you have access.
DBA_OBJECTS contains information about all objects that are owned by all users. For views
that are prefixed with ALL or DBA, there is usually an additional column in the view named
OWNER to identify who owns the object.
There is also a set of views that is prefixed with v$. These views are dynamic in nature and hold
information about performance. Dynamic performance tables are not true tables, and they should
not be accessed by most users. However, database administrators can query and create views on
the tables and grant access to those views to other users. This course does not go into details
about these views.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 6
Cas Training
a
s
a
SELECT *
)h
s
e
FROM
dictionary
a ide
u
g
WHERE table_name = 'USER_OBJECTS';
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LDictionary
era Views
f
d
s
How to Use
the
an with the dictionary views, you can use the dictionary view named
igo -tyourself
r
ToI
familiarize
non It contains the name and short description of each dictionary view to which you
DICTIONARY.
have access.
You can write queries to search for information about a particular view name, or you can search
the COMMENTS column for a word or phrase. In the example shown, the DICTIONARY view is
described. It has two columns. The SELECT statement retrieves information about the dictionary
view named USER_OBJECTS. The USER_OBJECTS view contains information about all the
objects that you own.
You can write queries to search the COMMENTS column for a word or phrase. For example, the
following query returns the names of all views that you are permitted to access in which the
COMMENTS column contains the word columns:
SELECT table_name
FROM dictionary
WHERE LOWER(comments) LIKE '%columns%';
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 7
Cas Training
a
s
a
ALL_OBJECTS:
)h
s
e
a youidhave
Query ALL_OBJECTS to see all objects to which
e
u
g
ta t Gu
s
access
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LandsfALL_OBJECTS
era
d
USER_OBJECTS
Views
o tran
g
i
Ican oquery
You
n- the USER_OBJECTS view to see the names and types of all the objects in your
n
schema. There are several columns in this view:
Note: This is not a complete listing of the columns. For a complete listing, see
USER_OBJECTS in the Oracle Database Reference.
You can also query the ALL_OBJECTS view to see a listing of all objects to which you have
access.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 8
Cas Training
USER_OBJECTS View
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LView
era
f
d
USER_OBJECTS
s
an the names, types, dates of creation, and status of all objects that are owned
igo -shows
r
t
Iexample
The
on
by this n
user.
The OBJECT_TYPE column holds the values of either TABLE, VIEW, SEQUENCE, INDEX,
PROCEDURE, FUNCTION, PACKAGE, or TRIGGER.
The STATUS column holds a value of VALID, INVALID, or N/A. Although tables are always
valid, the views, procedures, functions, packages, and triggers may be invalid.
The CAT View
For a simplified query and output, you can query the CAT view. This view contains only two
columns: TABLE_NAME and TABLE_TYPE. It provides the names of all your INDEX, TABLE,
CLUSTER, VIEW, SYNONYM, SEQUENCE, or UNDEFINED objects.
Note: CAT is a synonym for USER_CATALOGa view that lists tables, views, synonyms and
sequences owned by the user.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 9
Cas Training
Lesson Agenda
View information
Sequence information
Synonym information
Index information
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
Adding a comment to a table and
tu the dictionary
raquerying
r
S
a
views for comment information
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 10
Cas Training
Table Information
USER_TABLES:
DESCRIBE user_tables
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Table Information
n
aUSER_TABLES
igouse -the
r
t
Ican
You
view to obtain the names of all your tables. The
n
o
n
USER_TABLES view contains information about your tables. In addition to providing the table
SELECT table_name
FROM
user_tables;
Note: For a complete listing of the columns in the USER_TABLES view, see USER_TABLES
in the Oracle Database Reference.
You can also query the ALL_TABLES view to see a listing of all tables to which you have
access.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 11
Cas Training
Column Information
USER_TAB_COLUMNS:
DESCRIBE user_tab_columns
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
Column o
Information
a USER_TAB_COLUMNS view to find detailed information about the columns
ig query-trthe
Ican
You
n
o
in yourntables. Although the USER_TABLES view provides information about your table names
and storage, detailed column information is found in the USER_TAB_COLUMNS view.
This view contains information such as:
Column names
Column data types
Length of data types
Precision and scale for NUMBER columns
Whether nulls are allowed (Is there a NOT NULL constraint on the column?)
Default value
Note: For a complete listing and description of the columns in the USER_TAB_COLUMNS view,
see USER_TAB_COLUMNS in the Oracle Database Reference.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 12
Cas Training
Column Information
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L era
de nsf(continued)
Column o
Information
ig -the
traUSER_TAB_COLUMNS table, you can find details about your columns such as
ByI
querying
n
no data types, data type lengths, null constraints, and default value for a column.
the names,
The example shown displays the columns, data types, data lengths, and null constraints for the
EMPLOYEES table. Note that this information is similar to the output from the DESCRIBE
command.
To view information about columns set as unused, you use the USER_UNUSED_COL_TABS
dictionary view.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 13
Cas Training
Constraint Information
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Constraint
Information
n
athe
igofind-out
r
t
Ican
You
names of your constraints, the type of constraint, the table name to which
n
o
n
the constraint applies, the condition for check constraints, foreign key constraint information,
deletion rule for foreign key constraints, the status, and many other types of information about
your constraints.
Note: For a complete listing and description of the columns in the USER_CONSTRAINTS view,
see USER_CONSTRAINTS in the Oracle Database Reference.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 14
Cas Training
USER_CONSTRAINTS: Example
SELECT constraint_name, constraint_type,
search_condition, r_constraint_name,
delete_rule, status
FROM
user_constraints
WHERE table_name = 'EMPLOYEES';
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfeExample
d
USER_CONSTRAINTS:
o tran
igexample
InIthe
n- shown, the USER_CONSTRAINTS view is queried to find the names, types,
o
n
check conditions, name of the unique constraint that the foreign key references, deletion rule for
a foreign key, and status for constraints on the EMPLOYEES table.
The CONSTRAINT_TYPE can be:
C (check constraint on a table , or NOT NULL)
P (primary key)
U (unique key)
R (referential integrity)
V (with check option, on a view)
O (with read-only, on a view)
The DELETE_RULE can be:
CASCADE: If the parent record is deleted, the child records are deleted too.
NO ACTION: A parent record can be deleted only if no child records exist.
The STATUS can be:
ENABLED: Constraint is active.
DISABLED: Constraint is made not active.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 15
Cas Training
Querying USER_CONS_COLUMNS
DESCRIBE user_cons_columns
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Querying
USER_CONS_COLUMNS
igo -tranof the columns to which a constraint applies, query the
ToI
find thennames
no
USER_CONS_COLUMNS
dictionary view. This view tells you the name of the owner of a
SELECT constraint_name, column_name
FROM
user_cons_columns
WHERE table_name = 'EMPLOYEES';
constraint, the name of the constraint, the table that the constraint is on, the names of the
columns with the constraint, and the original position of column or attribute in the definition of
the object.
Note: A constraint may apply to more than one column.
You can also write a join between USER_CONSTRAINTS and USER_CONS_COLUMNS to
create customized output from both tables.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 16
Cas Training
Lesson Agenda
View information
Sequence information
Synonym information
Index information
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
Adding a comment to a table and
tu the dictionary
raquerying
r
S
a
views for comment information
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 17
Cas Training
View Information
1
DESCRIBE user_views
a
s
a
)h
s
e
a ide
3 SELECT text FROM user_views
u
g
WHERE view_name = 'EMP_DETAILS_VIEW'; ta
u
G
s
t
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
View Information
o tran
- is created, you can query the data dictionary view called USER_VIEWS to see
After
Iigyouronview
n
the name of the view and the view definition. The text of the SELECT statement that constitutes
your view is stored in a LONG column. The LENGTH column is the number of characters in the
SELECT statement. By default, when you select from a LONG column, only the first 80
characters of the columns value are displayed. To see more than 80 characters in SQL*Plus, use
the SET LONG command:
SET LONG 1000
Cas Training
Sequence Information
DESCRIBE user_sequences
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Sequence
Information
igo -tran
IUSER_SEQUENCES
The
view describes all sequences that you own. When you create the
n
o
n
sequence, you specify criteria that are stored in the USER_SEQUENCES view. The columns in
this view are:
SEQUENCE_NAME: Name of the sequence
MIN_VALUE: Minimum value of the sequence
MAX_VALUE: Maximum value of the sequence
INCREMENT_BY: Value by which the sequence is incremented
CYCLE_FLAG: Does sequence wrap around on reaching the limit?
ORDER_FLAG: Are sequence numbers generated in order?
CACHE_SIZE: Number of sequence numbers to cache
LAST_NUMBER: Last sequence number written to disk. If a sequence uses caching, the
number written to disk is the last number placed in the sequence cache. This number is
likely to be greater than the last sequence number that was used.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 19
Cas Training
Confirming Sequences
a
s
a
)h
s
e
The LAST_NUMBER column displays the next available
a ide
u
g
sequence number if NOCACHE is specified.
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Confirming
Sequences
o tran
- your sequence, it is documented in the data dictionary. Because a sequence is a
Iigcreating
After
non
database object, you can identify it in the USER_OBJECTS data dictionary table.
You can also confirm the settings of the sequence by selecting from the USER_SEQUENCES
data dictionary view.
Viewing the Next Available Sequence Value Without Incrementing It
If the sequence was created with NOCACHE, it is possible to view the next available sequence
value without incrementing it by querying the USER_SEQUENCES table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 20
Cas Training
Index Information
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Index Information
an
igo the-tUSER_INDEXES
r
Iquery
You
view to find out the names of your indexes, the table name on
n
o
n
which the index is created, and whether the index is unique.
Note: For a complete listing and description of the columns in the USER_INDEXES view, see
USER_INDEXES in the Oracle Database Reference 11g Release 1 (11.1).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 21
Cas Training
USER_INDEXES: Examples
a
a
s
a
)h
s
e
a ide
b SELECT INDEX_NAME, TABLE_NAME
u
g
ta t Gu
FROM
USER_INDEXES
s
e
g den
WHERE TABLE_NAME = 'EMP_LIB';
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Example
era
f
d
USER_INDEXES:
s
o tran
igslidenexample
InIthe
a, the USER_INDEXES view is queried to find the name of the index,
no
name of the table on which the index is created, and whether the index is unique.
In the slide example b, observe that the Oracle server gives a generic name to the index that is
created for the PRIMARY KEY column. The EMP_LIB table is created by using the following
code:
CREATE TABLE EMP_LIB
(book_id NUMBER(6)PRIMARY KEY ,
title VARCHAR2(25),
category VARCHAR2(20));
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 22
Cas Training
Querying USER_IND_COLUMNS
DESCRIBE user_ind_columns
a
s
a
)h
s
e
SELECT INDEX_NAME, COLUMN_NAME,TABLE_NAMEa
e
u
d
i
g
FROM
user_ind_columns
ta t Gu
WHERE INDEX_NAME = 'LNAME_IDX'; ges
n
e
@
d
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Querying
USER_IND_COLUMNS
igo -tran
IUSER_IND_COLUMNS
The
dictionary view provides information such as the name of the
non
index, name of the indexed table, name of a column within the index, and the columns position
within the index.
For the slide example, the emp_test table and LNAME_IDX index are created by using the
following code:
CREATE TABLE emp_test AS SELECT * FROM employees;
CREATE INDEX LNAME_IDX ON emp_test(Last_Name);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 23
Cas Training
Synonym Information
DESCRIBE user_synonyms
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Synonym
Information
igo -tran dictionary view describes private synonyms (synonyms that you own).
IUSER_SYNONYMS
The
on
n
You can query this view to find your synonyms. You can query ALL_SYNONYMS to find out the
SELECT *
FROM
user_synonyms;
name of all the synonyms that are available to you and the objects on which these synonyms
apply.
The columns in this view are:
SYNONYM_NAME: Name of the synonym
TABLE_OWNER: Owner of the object that is referenced by the synonym
TABLE_NAME: Name of the table or view that is referenced by the synonym
DB_LINK: Name of the database link reference (if any)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 24
Cas Training
Lesson Agenda
View information
Sequence information
Synonym information
Index information
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
Adding a comment to a table and
tu the dictionary
raquerying
r
S
a
views for comment information
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 25
Cas Training
a
s
a
)h
Comments can be viewed through the data dictionary
s
e
a ide
views:
u
g
ta t Gu
s
ALL_COL_COMMENTS
e
g den
@
USER_COL_COMMENTS
ra Stu
r
a
his
ALL_TAB_COMMENTS (ileg
t
e
ez o us
l
USER_TAB_COMMENTS
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L stofearaTable
d
Adding Comments
an of up to 4,000 bytes about a column, table, view, or snapshot by using
igoadd -atrcomment
Ican
You
non statement. The comment is stored in the data dictionary and can be viewed in one
the COMMENT
of the following data dictionary views in the COMMENTS column:
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Syntax
COMMENT ON {TABLE table | COLUMN table.column}
IS 'text';
In the syntax:
table Is the name of the table
column Is the name of the column in a table
text
Is the text of the comment
You can drop a comment from the database by setting it to empty string (''):
COMMENT ON TABLE employees IS '';
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 26
Cas Training
Quiz
The dictionary views that are based on the dictionary tables
contain information such as:
1. Definitions of all the schema objects in the database
2. Default values for the columns
3. Integrity constraint information
4. Oracle usernames and passwords
5. Privileges and roles that each user has been granted s
ha
)
s
e e
a
u
ag Guid
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e2, L3, 5 sfera
d
Answers:
1,
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 27
Cas Training
Summary
In this lesson, you should have learned how to find information
about your objects through the following dictionary views:
DICTIONARY
USER_OBJECTS
USER_TABLES
USER_TAB_COLUMNS
USER_CONSTRAINTS
a
s
a
)h
USER_CONS_COLUMNS
s
e
a ide
u
USER_VIEWS
g
ta t Gu
s
e
USER_SEQUENCES
g den
@
ra Stu
r
USER_INDEXES
a
eg this
l
i
(
USER_SYNONYMS
se
ez
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
de nsfe
Summary
o
ra learned about some of the dictionary views that are available to you. You can
tyou
iglesson,
InIthis
n
nodictionary views to find information about your tables, constraints, views, sequences,
use these
and synonyms.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 28
Cas Training
Practice 3: Overview
This practice covers the following topics:
Querying the dictionary views for table and column
information
Querying the dictionary views for constraint information
Querying the dictionary views for view information
Querying the dictionary views for sequence information
Querying the dictionary views for synonym information s
ha
)
Querying the dictionary views for index information
s
e e
a
u
Adding a comment to a table and queryingathe
g dictionary
uid
t
G
s
views for comment information
ge ent
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Practiceo3:dOverview
n
a
r
t
igpractice,
InIthis
you
query the dictionary views to find information about objects in your
n
o
n
schema.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 29
Cas Training
Practice 3
1. Query the USER_TABLES data dictionary view to see information about the tables
that you own.
2. Query the ALL_TABLES data dictionary view to see information about all the tables
a
s
a
that you can access. Exclude tables that you own.
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
goa specified
an table, create a script that reports the column names, data types, and data
r
t
3.
IiFor
nonlengths, as well as whether nulls are allowed. Prompt the user to enter the table
types
Note: Your list may not exactly match the following list:
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 30
Cas Training
Practice 3 (continued)
4. Create a script that reports the column name, constraint name, constraint type, search
condition, and status for a specified table. You must join the USER_CONSTRAINTS
and USER_CONS_COLUMNS tables to obtain all this information. Prompt the user to
enter the table name. Save the script in a file named lab_03_04.sql.
For example, if the user enters DEPARTMENTS, the following output results:
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
tuThen find the names of all
ra it EMP.
r
6. Create a synonym for your EMPLOYEES table.
Call
S
a
synonyms that are in your schema.
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
7. Run lab_03_07.sql
L fera to create the dept50 view for this exercise.
e
d to ndetermine
You
need
the names and definitions of all the views in your schema.
s
o
g
a
i
r
a-treport that retrieves view information: the view name and text from the
I Create
n
o
USER_VIEWS
data dictionary view.
n
Note: The EMP_DETAILS_VIEW was created as part of your schema.
Note: You can see the complete definition of the view if you use Run Script (or press
F5) in SQL Developer. If you use Execute Statement (or press F9) in SQL Developer,
scroll horizontally in the result pane. If you use SQL*Plus, to see more contents of a
LONG column, use the command SET LONG n, where n is the value of the number of
characters of the LONG column that you want to see.
8. Find the names of your sequences. Write a query in a script to display the following
information about your sequences: sequence name, maximum value, increment size,
and last number. Name the script lab_03_08.sql. Run the statement in your script.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 31
Cas Training
Practice 3 (continued)
s
a
h
s)
9. Confirm that both the DEPT2 and EMP2 tables are stored in the data dictionary.
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
z by uquerying
10. Confirm that the constraints werele
added
the USER_CONSTRAINTS view.
s
o
z constraints.
t
Note the types and names ofnthe
e
o
s
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
11. Display the object names and types from the USER_OBJECTS data dictionary view for the
EMP2 and DEPT2 tables.
12. Create the SALES_DEPT table based on the following table instance chart. Name the
index for the PRIMARY KEY column SALES_PK_IDX. Then query the data dictionary
view to find the index name, table name, and whether the index is unique.
Column Name
Team_Id
Location
Primary Key
Yes
Data Type
Number
VARCHAR2
Length
30
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 3 - 32
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Manipulate data using subqueries
Specify explicit default values in the INSERT and UPDATE
statements
Describe the features of multitable INSERTs
Use the following types of multitable INSERTs:
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
Merge rows in a table
ra Stu
r
a
g a tperiod
Track the changes to data
his of time
leover
i
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
-you learn how to manipulate data in the Oracle database by using subqueries. You
In this
Iiglesson,
notonuse the DEFAULT keyword in INSERT and UPDATE statements to identify a default
learn how
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
column value. You also learn about multitable INSERT statements, the MERGE statement, and
tracking changes in the database.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 2
Cas Training
Lesson Agenda
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
s
a
h
Merging rows in a table
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 3
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L tosManipulate
era
f
d
Using Subqueries
Data
o tran
g
i
Subqueries
I ocan
n- be used to retrieve data from a table that you can use as input to an INSERT into a
n
different table. In this way, you can easily copy large volumes of data from one table to another with
one single SELECT statement. Similarly, you can use subqueries to do mass updates and deletes by
using them in the WHERE clause of the UPDATE and DELETE statements. You can also use
subqueries in the FROM clause of a SELECT statement. This is called an inline view.
Note: You learned how to update and delete rows based on another table in the course titled Oracle
Database 11g: SQL Fundamentals I.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 4
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e LUsing
earSubquery
f
d
Retrieving
Data
as Source
s
o tran
g
i
You
Ican use
na-subquery in the FROM clause of a SELECT statement, which is very similar to how
noused.
views are
A subquery in the FROM clause of a SELECT statement is also called an inline view.
A subquery in the FROM clause of a SELECT statement defines a data source for that particular
SELECT statement, and only that SELECT statement. As with a database view, the SELECT
statement in the subquery can be as simple or as complex as you like.
When a database view is created, the associated SELECT statement is stored in the data dictionary.
In situations where you do not have the necessary privileges to create database views, or when you
would like to test the suitability of a SELECT statement to become a view, you can use an inline
view.
With inline views, you can have all the code needed to support the query in one place. This means
that you can avoid the complexity of creating a separate database view. The slide example shows
how to use an inline view to display the department name and the city in Europe. The subquery in the
FROM clause fetches the location ID, city name, and the country by joining three different tables. The
output of the inner query is considered as a table for the outer query. The inner query is similar to
that of a database view but does not have any physical name.
For the example in the slide, the loc table is created by running the following statement:
CREATE TABLE loc AS SELECT * FROM locations;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 5
Cas Training
Retrieving Data Using a Subquery as Source (continued)
You can display the same output as in the slide example by performing the following two steps:
1. Create a database view:
CREATE OR REPLACE VIEW european_cities
AS
SELECT l.location_id, l.city, l.country_id
FROM
loc l
JOIN
countries c
ON(l.country_id = c.country_id)
JOIN regions USING(region_id)
WHERE region_name = Europe;
a
Note: You learned how to create database views in the course titled Oracle Database 11g:
SQL
s
a
Fundamentals I.
)h
es e
a
gu uid
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 6
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de a Subquery
Insertingo
Using
as a Target
s
n
g
a
i
r
t
You
a-subquery
in place of the table name in the INTO clause of the INSERT statement. The
Ican use
n
o
SELECTnlist of this subquery must have the same number of columns as the column list of the
VALUES clause. Any rules on the columns of the base table must be followed in order for the
INSERT statement to work successfully. For example, you cannot put in a duplicate location ID or
leave out a value for a mandatory NOT NULL column.
This application of subqueries helps you avoid having to create a view just for performing an
INSERT.
The slide example uses a subquery in the place of LOC to create a record for a new European city.
Note: You can also perform the INSERT operation on the EUROPEAN_CITIES view by using the
following code:
INSERT INTO european_cities
VALUES (3300,Cardiff,UK);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de a Subquery
Insertingo
Using
as a Target (continued)
s
n
g
a
i
r
-t shows that the insert via the inline view created a new record in the base table
TheI
slide example
n
o
LOC. n
The following example shows the results of the subquery that was used to identify the table for the
INSERT statement.
SELECT l.location_id, l.city, l.country_id
FROM
loc l
JOIN
countries c
ON(l.country_id = c.country_id)
JOIN regions USING(region_id)
WHERE region_name = 'Europe
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 8
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de CHECK
Using theoWITH
s OPTION Keyword on DML Statements
n
g
a
i
r
Specify
WITH
-t CHECK OPTION keyword to indicate that if the subquery is used in place of a
I theon
table in n
an INSERT, UPDATE, or DELETE statement, no changes that produce rows that are not
included in the subquery are permitted to that table.
The slide example shows how to use an inline view with the WITH CHECK OPTION. The INSERT
statement prevents the creation of records in the LOC table for a city that is not in Europe.
The following example executes successfully because of the changes in the VALUES list.
INSERT INTO (SELECT location_id, city, country_id
FROM
loc
WHERE country_id IN
(SELECT country_id
FROM countries
NATURAL JOIN regions
WHERE region_name = 'Europe')
WITH CHECK OPTION)
VALUES (3500, 'Berlin', 'DE');
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 9
Cas Training
Using the WITH CHECK OPTION Keyword on DML Statements (continued)
The application of an inline view with the WITH CHECK OPTION provides an easy method to
prevent changes to the table.
To prevent the creation of a non-European city, you can also use a database view by performing the
following steps:
1. Create a database view:
CREATE OR REPLACE VIEW european_cities
AS
SELECT location_id, city, country_id
FROM
locations
WHERE country_id in
(SELECT country_id
FROM countries
NATURAL JOIN regions
WHERE region_name = 'Europe')
WITH CHECK OPTION;
s
a
h
2. Verify the results by inserting data:
s)
e
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 10
Cas Training
Lesson Agenda
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
s
a
h
Merging rows in a table
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 11
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Explicit Defaults
an can be used in INSERT and UPDATE statements to identify a default
igo -tkeyword
r
TheI
DEFAULT
on
column n
value. If no default value exists, a null value is used.
The DEFAULT option saves you from hard coding the default value in your programs or querying the
dictionary to find it, as was done before this feature was introduced. Hard coding the default is a
problem if the default changes because the code consequently needs changing. Accessing the
dictionary is not usually done in an application program, so this is a very important feature.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 12
Cas Training
UPDATE deptm3
SET manager_id = DEFAULT
WHERE department_id = 10;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eDefault
d
Using Explicit
o trans Values
g
i
Specify
I DEFAULT
n- to set the column to the value previously specified as the default value for the
o
n
column. If no default value for the corresponding column has been specified, the Oracle server sets
the column to null.
In the first example in the slide, the INSERT statement uses a default value for the MANAGER_ID
column. If there is no default value defined for the column, a null value is inserted instead.
The second example uses the UPDATE statement to set the MANAGER_ID column to a default value
for department 10. If no default value is defined for the column, it changes the value to null.
Note: When creating a table, you can specify a default value for a column. This is discussed in SQL
Fundamentals I.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 13
Cas Training
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de from
Copying o
Rows
sAnother Table
n
g
a
i
r
You
the
-t INSERT statement to add rows to a table where the values are derived from existing
Ican use
n
o
tables. Innplace of the VALUES clause, you use a subquery.
Syntax
INSERT INTO table [ column (, column) ] subquery;
In the syntax:
table
Is the table name
column
Is the name of the column in the table to populate
subquery
Is the subquery that returns rows into the table
The number of columns and their data types in the column list of the INSERT clause must match the
number of values and their data types in the subquery. To create a copy of the rows of a table, use
SELECT * in the subquery.
INSERT INTO EMPL3
SELECT *
FROM
employees;
Note: You use the LOG ERRORS clause in your DML statement to enable the DML operation to
complete regardless of errors. Oracle writes the details of the error message to an error-logging table
that you have created. For more information, see Oracle Database 11g SQL Reference.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 14
Cas Training
Lesson Agenda
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
s
a
h
Merging rows in a table
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 15
Cas Training
Target_a
Sourcetab
Subquery
a
INSERT ALL
s
a
INTO target_a VALUES(,,)
Target_b
)h
s
e
INTO target_b VALUES(,,)
a ide
u
g
INTO target_c VALUES(,,) ta
u
G
s
t
e
SELECT
g den
@
FROM sourcetab
ra Stu
r
a
WHERE ;
his
leg
(i se t
z
Target_c
e
l to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e sfeINSERT Statements
OverviewoofdMultitable
an statement, you insert computed rows derived from the rows returned from
ig -tINSERT
r
In aI
multitable
non of a subquery into one or more tables.
the evaluation
Multitable INSERT statements are useful in a data warehouse scenario. You need to load your data
warehouse regularly so that it can serve its purpose of facilitating business analysis. To do this, data
from one or more operational systems must be extracted and copied into the warehouse. The process
of extracting data from the source system and bringing it into the data warehouse is commonly called
ETL, which stands for extraction, transformation, and loading.
During extraction, the desired data must be identified and extracted from many different sources,
such as database systems and applications. After extraction, the data must be physically transported
to the target system or an intermediate system for further processing. Depending on the chosen
means of transportation, some transformations can be done during this process. For example, a SQL
statement that directly accesses a remote target through a gateway can concatenate two columns as
part of the SELECT statement.
After data is loaded into the Oracle database, data transformations can be executed using SQL
operations. A multitable INSERT statement is one of the techniques for implementing SQL data
transformations.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 16
Cas Training
s
a
Single DML versus a procedure to perform multiple inserts
h
)
by using the IF...THEN syntax
es
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra Statements (continued)
e L sfeINSERT
OverviewoofdMultitable
anstatements offer the benefits of the INSERT ... SELECT statement when
r
t
Multitable
Iig oINSERT
n
multiplentables are involved as targets. Without multitable INSERT, you had to deal with n
independent INSERT ... SELECT statements, thus processing the same source data n times and
increasing the transformation workload n times.
As with the existing INSERT ... SELECT statement, the new statement can be parallelized and
used with the direct-load mechanism for faster performance.
Each record from any input stream, such as a nonrelational database table, can now be converted into
multiple records for a more relational database table environment. To alternatively implement this
functionality, you were required to write multiple INSERT statements.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 17
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nsINSERT
Types of o
Multitable
Statements
g
a
i
r
You
-t clauses to indicate the type of INSERT to be executed. The types of multitable
Iuse different
n
o
INSERTnstatements are:
Unconditional INSERT: For each row returned by the subquery, a row is inserted into each of
the target tables.
Conditional INSERT ALL: For each row returned by the subquery, a row is inserted into each
target table if the specified condition is met.
Pivoting INSERT: This is a special case of the unconditional INSERT ALL.
Conditional INSERT FIRST: For each row returned by the subquery, a row is inserted into
the very first target table in which the condition is met.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 18
Cas Training
conditional_insert_clause:
[ALL] [FIRST]
[WHEN condition THEN] [insert_into_clause values_clause]
[ELSE] [insert_into_clause values_clause]
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nStatements
MultitableoINSERT
s
g
a
i
r
TheI
slide displays
-t the generic format for multitable INSERT statements.
n
o
n INSERT: ALL into_clause
Unconditional
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 19
Cas Training
Multitable INSERT Statements (continued)
Conditional INSERT: FIRST
If you specify FIRST, the Oracle server evaluates each WHEN clause in the order in which it appears
in the statement. If the first WHEN clause evaluates to true, the Oracle server executes the
corresponding INTO clause and skips subsequent WHEN clauses for the given row.
Conditional INSERT: ELSE Clause
For a given row, if no WHEN clause evaluates to true:
If you have specified an ELSE clause, the Oracle server executes the INTO clause list associated
with the ELSE clause
If you did not specify an ELSE clause, the Oracle server takes no action for that row
Restrictions on Multitable INSERT Statements
You can perform multitable INSERT statements only on tables, and not on views or
materialized views.
You cannot perform a multitable INSERT on a remote table.
a
s
a
You cannot specify a table collection expression when performing a multitable INSERT.
) h more than
In a multitable INSERT, all insert_into_clauses cannot combinee
tosspecify
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 20
Cas Training
INSERT ALL
INTO sal_history VALUES(EMPID,HIREDATE,SAL)
s
a
h
INTO mgr_history VALUES(EMPID,MGR,SAL)
s)
e
a ide
SELECT employee_id EMPID, hire_date HIREDATE,
u
g
ta t Gu
salary SAL, manager_id MGR
s
e
g den
FROM employees
@
a Stu
WHERE employee_id > 200;
arr
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eINSERT
d
Unconditional
o trans ALL
g
i
TheI
examplenin
- the slide inserts rows into both the SAL_HISTORY and the MGR_HISTORY tables.
o
n
The SELECT statement retrieves the details of employee ID, hire date, salary, and manager ID of
those employees whose employee ID is greater than 200 from the EMPLOYEES table. The details of
the employee ID, hire date, and salary are inserted into the SAL_HISTORY table. The details of
employee ID, manager ID, and salary are inserted into the MGR_HISTORY table.
This INSERT statement is referred to as an unconditional INSERT because no further restriction is
applied to the rows that are retrieved by the SELECT statement. All the rows retrieved by the
SELECT statement are inserted into the two tables: SAL_HISTORY and MGR_HISTORY. The
VALUES clause in the INSERT statements specifies the columns from the SELECT statement that
must be inserted into each of the tables. Each row returned by the SELECT statement results in two
insertions: one for the SAL_HISTORY table and one for the MGR_HISTORY table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 21
Cas Training
Unconditional INSERT ALL (continued)
A total of eight rows were inserted:
SELECT COUNT(*) total_in_sal FROM sal_history;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 22
Cas Training
Hired before
1995
EMP_HISTORY
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
tu
ra EMP_SALES
r
S
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sALL:
eraExample
f
d
Conditional
INSERT
igo -trainnthe employees tables, if the employee was hired before 1995, then insert that
ForI
all employees
n
norecord
employee
into the employee history. If the employee earns a sales commission, then insert the
Employees
With sales
commission
record information into the EMP_SALES table. The SQL statement is shown on the next page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 23
Cas Training
ALL
a
s
a
salary SAL, commission_pct COMM
)h
s
e
a ide
u
FROM employees
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sALL
era
f
d
Conditional
INSERT
igo -trtheanslide is similar to the example in the previous slide because it inserts rows into
TheI
examplenin
no
SELECT employee_id EMPID, hire_date HIREDATE,
both the EMP_HISTORY and the EMP_SALES tables. The SELECT statement retrieves details such
as employee ID, hire date, salary, and commission percentage for all employees from the
EMPLOYEES table. Details such as employee ID, hire date, and salary are inserted into the
EMP_HISTORY table. Details such as employee ID, commission percentage, and salary are inserted
into the EMP_SALES table.
This INSERT statement is referred to as a conditional INSERT ALL because a further restriction is
applied to the rows that are retrieved by the SELECT statement. From the rows that are retrieved by
the SELECT statement, only those rows in which the hire date was prior to 1995 are inserted in the
EMP_HISTORY table. Similarly, only those rows where the value of commission percentage is not
null are inserted in the EMP_SALES table.
SELECT count(*) FROM emp_history;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 24
Cas Training
sa
SAL_MID
) ha
es e
a
gu uid
a
t
es ent G
g
Otherwise
ra@ Stud
r
a
leg e this
i
(
SAL_HIGH
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sFIRST:
era Example
f
d
Conditional
INSERT
go -trainnthe EMPLOYEES table, insert the employee information into the first target
ForI
alli employees
on the condition. In the example, if an employee has a salary of 2,000, the record is
nmeets
table that
EMPLOYEES
inserted into the SAL_LOW table only. The SQL statement is shown on the next page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 25
Cas Training
INSERT FIRST
WHEN salary < 5000 THEN
INTO sal_low VALUES (employee_id, last_name, salary)
WHEN salary between 5000 and 10000 THEN
INTO sal_mid VALUES (employee_id, last_name, salary)
ELSE
sa
s)
e
a ide
SELECT employee_id, last_name, salary
u
g
ta t Gu
s
FROM employees
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sFIRST
era
f
d
Conditional
INSERT
an retrieves details such as employee ID, last name, and salary for every
igo -statement
r
t
TheI
SELECT
non
employee in the EMPLOYEES table. For each employee record, it is inserted into the very first target
table that meets the condition.
This INSERT statement is referred to as a conditional INSERT FIRST. The WHEN salary <
5000 condition is evaluated first. If this first WHEN clause evaluates to true, the Oracle server
executes the corresponding INTO clause and inserts the record into the SAL_LOW table. It skips
subsequent WHEN clauses for this row.
If the row that does not satisfy the first WHEN condition (WHEN salary < 5000), the next
condition (WHEN salary between 5000 and 10000) is evaluated. If this condition
evaluates to true, the record is inserted into the SAL_MID table, and the last condition is skipped.
If neither the first condition (WHEN salary < 5000) nor the second condition (WHEN salary
between 5000 and 10000) is evaluated to true, the Oracle server executes the corresponding
INTO clause for the ELSE clause.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 26
Cas Training
Conditional INSERT FIRST (continued)
A total of 20 rows were inserted:
SELECT count(*) low FROM sal_low;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 27
Cas Training
Pivoting INSERT
Convert the set of sales records from the nonrelational
database table to relational format.
Emp_ID
Week_ID
MON
TUES
WED
THUR
FRI
176
2000
3000
4000
5000
6000
Employee_ID
WEEK
SALES
176
2000
a
s
a
)h
s
e
176
6
3000
a ide
u
g
u
176
6
4000 sta
G
t
e
g den
176
6
5000
@
ra Stu
r
a
176
6
is
leg e th6000
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Pivoting INSERT
o tran
Pivoting
in which you must build a transformation such that each record from any
Iig isoann-operation
n
input stream, such as a nonrelational database table, must be converted into multiple records for a
more relational database table environment.
Suppose you receive a set of sales records from a nonrelational database table:
SALES_SOURCE_DATA, in the following format:
EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE, SALES_WED,
SALES_THUR, SALES_FRI
You want to store these records in the SALES_INFO table in a more typical relational format:
EMPLOYEE_ID, WEEK, SALES
To solve this problem, you must build a transformation such that each record from the original
nonrelational database table, SALES_SOURCE_DATA, is converted into five records for the data
warehouses SALES_INFO table. This operation is commonly referred to as pivoting.
The solution to this problem is shown on the next page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 28
Cas Training
Pivoting INSERT
INSERT ALL
INTO sales_info VALUES (employee_id,week_id,sales_MON)
INTO sales_info VALUES (employee_id,week_id,sales_TUE)
INTO sales_info VALUES (employee_id,week_id,sales_WED)
INTO sales_info VALUES (employee_id,week_id,sales_THUR)
INTO sales_info VALUES (employee_id,week_id, sales_FRI)
SELECT EMPLOYEE_ID, week_id, sales_MON, sales_TUE,
sales_WED, sales_THUR,sales_FRI
FROM sales_source_data;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L(continued)
era
f
d
Pivoting INSERT
s
go -tinrathen slide, the sales data is received from the nonrelational database table
In the
Iiexample
non
SALES_SOURCE_DATA,
which is the details of the sales performed by a sales representative on
each day of a week, for a week with a particular week ID.
DESC SALES_SOURCE_DATA
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 29
Cas Training
Pivoting INSERT (continued)
SELECT * FROM SALES_SOURCE_DATA;
DESC SALES_INFO
a
s
a
)h
s
SELECT * FROM sales_info;
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
L feexample
Observe in theepreceding
ra that by using a pivoting INSERT, one row from the
d
s
SALES_SOURCE_DATA
o tran table is converted into five records for the relational table, SALES_INFO.
g
i
I
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 30
Cas Training
Lesson Agenda
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
s
a
h
Merging rows in a table
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 31
Cas Training
MERGE Statement
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
MERGE Statement
n
asupports
igo server
r
t
TheI
Oracle
the MERGE statement for INSERT, UPDATE, and DELETE operations.
n
o
n
Using this statement, you can update, insert, or delete a row conditionally into a table, thus avoiding
multiple DML statements. The decision whether to update, insert, or delete into the target table is
based on a condition in the ON clause.
You must have the INSERT and UPDATE object privileges on the target table and the SELECT
object privilege on the source table. To specify the DELETE clause of merge_update_clause,
you must also have the DELETE object privilege on the target table.
The MERGE statement is deterministic. You cannot update the same row of the target table multiple
times in the same MERGE statement.
An alternative approach is to use PL/SQL loops and multiple DML statements. The MERGE
statement, however, is easy to use and more simply expressed as a single SQL statement.
The MERGE statement is suitable in a number of data warehousing applications. For example, in a
data warehousing application, you may need to work with data coming from multiple sources, some
of which may be duplicates. With the MERGE statement, you can conditionally add or modify rows.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 32
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Merging Rows
an rows, and insert new rows conditionally by using the MERGE statement.
igoupdate-trexisting
You
Ican
n
noMERGE
Using the
statement, you can delete obsolete rows at the same time as you update rows in a
table. To do this, you include a DELETE clause with its own WHERE clause in the syntax of the
MERGE statement.
In the syntax:
INTO clause
USING clause
ON clause
WHEN MATCHED |
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 33
Cas Training
(ile se th
z
le to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe
de Example
Merging Rows:
s
o
n
-tra INTO copy_emp3 c
Iig onMERGE
n USING (SELECT * FROM EMPLOYEES ) e
ON (c.employee_id = e.employee_id)
WHEN MATCHED THEN
UPDATE SET
c.first_name = e.first_name,
c.last_name = e.last_name,
c.email = e.email,
c.phone_number = e.phone_number,
c.hire_date = e.hire_date,
c.job_id = e.job_id,
c.salary = e.salary*2,
c.commission_pct = e.commission_pct,
c.manager_id = e.manager_id,
c.department_id = e.department_id
DELETE WHERE (E.COMMISSION_PCT IS NOT NULL)
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_id, e.first_name, e.last_name,
e.email, e.phone_number, e.hire_date, e.job_id,
e.salary, e.commission_pct, e.manager_id,
e.department_id);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 34
Cas Training
Merging Rows: Example (continued)
The COPY_EMP3 table is created by using the following code:
CREATE TABLE COPY_EMP3 AS SELECT * FROM EMPLOYEES
WHERE SALARY<10000;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
is and there are two employees
leg e <th10000
Observe that there are thirteen employees with(SALARY
i
with COMMISSION_PCT.
ez o us
l
t
nzEMPLOYEE_ID
e
The example in the slide matchesothe
in the COPY_EMP3 table to the
s
G
n
e
EMPLOYEE_ID in the EMPLOYEES
match is found, the row in the COPY_EMP3 table is
rrinatheleEMPLOYEES
lictable. If atable
a
updated to match the
row
and the salary of the employee is doubled. The
g
e rab
L
records of the
etwo employees
e with values in the COMMISSION_PCT column are deleted. If the
f
d
s
matchig
is o
not found,n
then rows are inserted into the COPY_EMP3 table.
I on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 35
Cas Training
ra Stu
r
a
SELECT * FROM copy_emp3; ileg
his
t
(
e
20 rows selected.
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LExample
era(continued)
f
d
Merging Rows:
s
anshow that the COPY_EMP3 table is empty. The c.employee_id =
igoexamples
r
t
TheI
slide
non
e.employee_id
condition is evaluated. The condition returns falsethere are no matches. The
logic falls into the WHEN NOT MATCHED clause, and the MERGE command inserts the rows of the
EMPLOYEES table into the COPY_EMP3 table. This means that the COPY_EMP3 table now has
exactly the same data as in the EMPLOYEES table.
SELECT employee_id, salary, commission_pct from copy_emp3;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 36
Cas Training
Lesson Agenda
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
s
a
h
Merging rows in a table
s)
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 37
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
z
Versions of retrievedlerows
us
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e
de ninsfData
Tracking o
Changes
ig discover
trathat somehow data in a table has been inappropriately changed. To research this,
You
Imay
n
o
you can n
use multiple flashback queries to view row data at specific points in time. More efficiently,
you can use the Flashback Version Query feature to view all changes to a row over a period of time.
This feature enables you to append a VERSIONS clause to a SELECT statement that specifies a
system change number (SCN) or the time stamp range within which you want to view changes to row
values. The query also can return associated metadata, such as the transaction responsible for the
change.
Further, after you identify an erroneous transaction, you can use the Flashback Transaction Query
feature to identify other changes that were done by the transaction. You then have the option of using
the Flashback Table feature to restore the table to a state before the changes were made.
You can use a query on a table with a VERSI ONS clause to produce all the versions of all the rows
that exist or ever existed between the time the query was issued and the undo_retention seconds
before the current time. undo_retention is an initialization parameter, which is an autotuned
parameter. A query that includes a VERSIONS clause is referred to as a version query. The results of
a version query behaves as though the WHERE clause were applied to the versions of the rows. The
version query returns versions of the rows only across transactions.
System change number (SCN): The Oracle server assigns an System change number to identify the
redo records for each committed transaction.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 38
Cas Training
COMMIT;
SELECT salary FROM employees3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE employee_id = 107;
h3as
s)
e
a ide
u
g
ta t Gu
s
e
g den
3
@
ra Stu
r
1
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera Version Query
Example o
of d
the Flashback
g -tinrathen slide, the salary for employee 107 is retrieved (1). The salary for employee 107
In the
Iiexample
nonby 30 percent and this change is committed (2). The different versions of salary are
is increased
displayed (3).
The VERSIONS clause does not change the plan of the query. For example, if you run a query on a
table that uses the index access method, then the same query on the same table with a VERSIONS
clause continues to use the index access method. The versions of the rows returned by the version
query are versions of the rows across transactions. The VERSIONS clause has no effect on the
transactional behavior of a query. This means that a query on a table with a VERSIONS clause still
inherits the query environment of the ongoing transaction.
The default VERSIONS clause can be specified as VERSIONS BETWEEN {SCN|TIMESTAMP}
MINVALUE AND MAXVALUE.
The VERSIONS clause is a SQL extension only for queries. You can have DML and DDL operations
that use a VERSIONS clause within subqueries. The row version query retrieves all the committed
versions of the selected rows. Changes made by the current active transaction are not returned. The
version query retrieves all incarnations of the rows. This essentially means that versions returned
include deleted and subsequent reinserted versions of the rows.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 39
Cas Training
Example of the Flashback Version Query (continued)
The row access for a version query can be defined in one of the following two categories:
ROWID-based row access: In case of ROWID-based access, all versions of the specified ROWID
are returned irrespective of the row content. This essentially means that all versions of the slot in
the block indicated by the ROWID are returned.
All other row access: For all other row access, all versions of the rows are returned.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 40
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sClause
era
f
d
VERSIONS
BETWEEN
an
igouse the
r
t
You
VERSIONS
BETWEEN clause to retrieve all the versions of the rows that exist or
Ican
n
o
n
have ever existed between the time the query was issued and a point back in time.
If the undo retention time is less than the lower bound time or the SCN of the BETWEEN clause, the
query retrieves versions up to the undo retention time only. The time interval of the BETWEEN clause
can be specified as an SCN interval or a wall-clock interval. This time interval is closed at both the
lower and the upper bounds.
In the example, Lorentzs salary changes are retrieved. The NULL value for END_DATE for the first
version indicates that this was the existing version at the time of the query. The NULL value for
START_DATE for the last version indicates that this version was created at a time before the undo
retention time.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 41
Cas Training
Quiz
When you use the INSERT or UPDATE command, the DEFAULT
keyword saves you from hard-coding the default value in your
programs or querying the dictionary to find it.
1. True
2. False
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Answer: 1
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 42
Cas Training
Summary
In this lesson, you should have learned how to:
Use DML statements and control transactions
Describe the features of multitable INSERTs
Use the following types of multitable INSERTs:
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
a
s
a
)h
s
e
a ide
Merge rows in a table
u
g
u
a
t
G
s
t
e
Manipulate data by using subqueriesg
n
e
@
d
tuof time
raperiod
r
Track the changes to data over
a
S
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Summaryo d
n
ashould
r
t
In this
you
have learned how to manipulate data in the Oracle database by using
Iiglesson,
n
noYou
subqueries.
also should have learned about multitable INSERT statements, the MERGE
statement, and tracking changes in the database.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 43
Cas Training
Practice 4: Overview
This practice covers the following topics:
Performing multitable INSERTs
Performing MERGE operations
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 44
Cas Training
Practice 4
1. Run the lab_04_01.sql script in the lab folder to create the SAL_HISTORY table.
2. Display the structure of the SAL_HISTORY table.
3. Run the lab_04_03.sql script in the lab folder to create the MGR_HISTORY table.
4. Display the structure of the MGR_HISTORY table.
s
a
5. Run the lab_04_05.sql script in the lab folder to create the SPECIAL_SALhtable.
)
6. Display the structure of the SPECIAL_SAL table.
es
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
7. a. Write a query to do the following:ez
l toID,ushire date, salary, and manager ID of those
employee
- Retrieve details such as n
the
z
o ID
siseless than 125 from the EMPLOYEES table.
employees whose employee
G
n
e
a
- If the salaryaisrrmore thanlic
$20,000, insert details such as the employee ID and salary into
e
g
l
the SPECIAL_SAL
Le ferab table.
e
- Insert
d details
s such as the employee ID, hire date, and salary into the SAL_HISTORY
o table.
n
g
a
i
r
-t
I - oInsert
n
details such as the employee ID, manager ID, and salary into the MGR_HISTORY
n
table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 45
Cas Training
Practice 4 (continued)
b. Display the records from the SPECIAL_SAL table.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 46
Cas Training
Practice 4 (continued)
8. a. Run the lab_04_08a.sql script in the lab folder to create the
SALES_WEEK_DATA table.
b. Run the lab_04_08b.sql script in the lab folder to insert records into the
SALES_WEEK_DATA table.
c. Display the structure of the SALES_WEEK_DATA table.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
is
d. Display the records from the SALES_WEEK_DATA
leg e thtable.
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e. Run the lab_04_08c.sql
script in the lab folder to create the EMP_SALES_INFO
L fera
e
table.
s
o d tthe
nstructure
g
a
i
r
f.
Display
of the EMP_SALES_INFO table.
I onn
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 47
Cas Training
Practice 4 (continued)
g. Write a query to do the following:
- Retrieve details such as ID, week ID, sales quantity on Monday, sales quantity on
Tuesday, sales quantity on Wednesday, sales quantity on Thursday, and sales quantity on
Friday from the SALES_WEEK_DATA table.
- Build a transformation such that each record retrieved from the SALES_WEEK_DATA
table is converted into multiple records for the EMP_SALES_INFO table.
Hint: Use a pivoting INSERT statement.
h. Display the records from the EMP_SALES_INFO table.
a
s
a
)h
s
e
a ide
u
g
ta t GuYou want to store
9. You have the data of past employees stored in a flat file called
emp.data.
s
e
n To do this, first create an
g in a dtable.
e
the names and email IDs of all employees, past and present,
@
u in the emp_dir directory.
ra sourceStfile
r
external table called EMP_DATA using the emp.dat
a
leg e this
Use the lab_04_09.sql script to do this.
i
(
ez o us
l
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 48
Cas Training
Practice 4 (continued)
Partial results (48 rows retrieved)
a
s
a
)h
s
e
a table,
echange
u
11. Create the EMP3 table by using the lab_04_11.sql script. In the
EMP3
the
d
i
g
u
a
t
Gdepartment for
department for Kochhar to 60 and commit your change. Next,
the
t
eschange
n
g
Kochhar to 50 and commit your change. Track the changes
@ totKochhar
de by using the Row
a
u
r
r
S
Versions feature.
a
s
g
i
e
h
l
(i se t
z
e
l to u
z
n
o nse
G
ce
ra
i
r
l
a
eg rable
L
de nsfe
o
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 4 - 49
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Use data types similar to DATE that store fractional
seconds and track time zones
Use data types that store the difference between two
datetime values
Use the following datetime functions:
s
TZ_OFFSET
a
CURRENT_DATE
h
s)
e
FROM_TZ
CURRENT_TIMESTAMP
a ide
u
g
TO_TIMESTAMP
LOCALTIMESTAMP
ta t Gu
s
e
g den
TO_YMINTERVAL
DBTIMEZONE
@
tu
raTO_DSINTERVAL
r
S
a
SESSIONTIMEZONE
leg e this
i
(
EXTRACT
lez
us
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
In this
Iiglesson,
n-you learn how to use data types similar to DATE that store fractional seconds and track
o
n
time zones. This lesson addresses some of the datetime functions available in the Oracle database.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 2
Cas Training
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 3
Cas Training
Time Zones
+07:00
-08:00
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
n for
g the
The image represents
time
e
@
d
tu
rawhenSGreenwich
r
each time zone
a
leg e this
i
time is 12:00.
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Time Zones
anare measured by the turning of the earth. The time of day at any particular
igo -trday
TheI
hours ofnthe
o
momentndepends on where you are. When it is noon in Greenwich, England, it is midnight along the
+02:00
+10:00
-05:00
International Date Line. The earth is divided into 24 time zones, one for each hour of the day. The
time along the prime meridian in Greenwich, England, is known as Greenwich Mean Time, or GMT.
GMT is now known as Coordinated Universal Time or UTC. UTC is the time standard against which
all other time zones in the world are referenced. It is the same all year round and is not affected by
summer time or daylight saving time. The meridian line is an imaginary line that runs from the North
Pole to the South Pole. It is known as zero longitude and it is the line from which all other lines of
longitude are measured. All time is measured relative to UTC and all places have a latitude (their
distance north or south of the equator) and a longitude (their distance east or west of the Greenwich
meridian).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 4
Cas Training
An absolute offset
Database time zone
OS local time zone
A named region
ALTER
ALTER
ALTER
ALTER
SESSION
SESSION
SESSION
SESSION
SET
SET
SET
SET
TIME_ZONE
TIME_ZONE
TIME_ZONE
TIME_ZONE
=
=
=
=
'-05:00';
dbtimezone;
local;
s)
e
'America/New_York';
a
has
ide
gu u
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sParameter
era
f
d
TIME_ZONE
Session
igo -transupports storing the time zone in your date and time data, as well as fractional
TheI
Oracle database
onALTER SESSION command can be used to change time zone values in a users
seconds.nThe
session. The time zone values can be set to an absolute offset, a named time zone, a database time
zone, or the local time zone.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 5
Cas Training
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
CURRENT_DATE:
Returns the current date from the user session
Has a data type of DATE
CURRENT_TIMESTAMP:
Returns the current date and time from the user session
Has a data type of TIMESTAMP WITH TIME ZONE
LOCALTIMESTAMP:
a
s
a
Returns the current date and time from the user session
)h
s
e
Has a data type of TIMESTAMP
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LCURRENT_TIMESTAMP,
era
f
d
CURRENT_DATE,
and LOCALTIMESTAMP
s
o tran
g
i
TheI
CURRENT_DATE
and CURRENT_TIMESTAMP functions return the current date and current
nonrespectively. The data type of CURRENT_DATE is DATE. The data type of
time stamp,
CURRENT_TIMESTAMP is TIMESTAMP WITH TIME ZONE. The values returned display the time
zone displacement of the SQL session executing the functions. The time zone displacement is the
difference (in hours and minutes) between local time and Coordinated Universal Time (UTC). The
TIMESTAMP WITH TIME ZONE data type has the format:
TIMESTAMP [ (fractional_seconds_precision) ] WITH TIME ZONE
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 6
Cas Training
es e
a
gu uid
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LandsfTime
era in a Sessions Time Zone
d
Comparing
Date
an command sets the date format of the session to
igo SESSION
r
t
TheI
ALTER
non HH24:MI:SSthat is, day of month (131)-abbreviated name of month-4'DD-MON-YYYY
digit year hour of day (023):minute (059):second (059).
The example in the slide illustrates that the session is altered to set the TIME_ZONE parameter to
5:00. Then the SELECT statement for CURRENT_DATE, CURRENT_TIMESTAMP, and
LOCALTIMESTAMP is executed to observe the differences in format.
Note: The TIME_ZONE parameter specifies the default local time zone displacement for the current
SQL session. TIME_ZONE is a session parameter only, not an initialization parameter. The
TIME_ZONE parameter is set as follows:
TIME_ZONE = '[+ | -] hh:mm'
The format mask ([+ | -] hh:mm) indicates the hours and minutes before or after UTC
(Coordinated Universal Time, formerly known as Greenwich Mean Time).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LandsfTime
era in a Sessions Time Zone (continued)
d
Comparing
Date
o
an
In this
function returns the current date in the sessions time zone, the
Iigcase,onthe-trCURRENT_DATE
n
CURRENT_TIMESTAMP
function returns the current date and time in the sessions time zone as a
value of the data type TIMESTAMP WITH TIME ZONE, and the LOCALTIMESTAMP function
returns the current date and time in the sessions time zone.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 8
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
eandL SESSIONTIMEZONE
era
f
d
DBTIMEZONE
s
n
adatabases
igosets-the
r
t
TheI
DBA
default time zone by specifying the SET TIME_ZONE clause of the
on
CREATEnDATABASE
statement. If omitted, the default database time zone is the operating system
SELECT SESSIONTIMEZONE FROM DUAL;
time zone. The database time zone cannot be changed for a session with an ALTER SESSION
statement.
The DBTIMEZONE function returns the value of the database time zone. The return type is a time
zone offset (a character type in the format: '[+|-]TZH:TZM') or a time zone region name,
depending on how the user specified the database time zone value in the most recent CREATE
DATABASE or ALTER DATABASE statement. The example in the slide shows that the database time
zone is set to 05:00, as the TIME_ZONE parameter is in the format:
TIME_ZONE = '[+ | -] hh:mm'
The SESSIONTIMEZONE function returns the value of the current sessions time zone. The return
type is a time zone offset (a character type in the format '[+|-]TZH:TZM') or a time zone region
name, depending on how the user specified the session time zone value in the most recent ALTER
SESSION statement. The example in the slide shows that the session time zone is offset to UTC by
8 hours. Observe that the database time zone is different from the current sessions time zone.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 9
Cas Training
Data Type
Fields
TIMESTAMP
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
n type; also
g dedata
TIMESTAMP WITH LOCAL
Same as the
TIMESTAMP
@
u in its value
toffset
ra zone
r
S
TIME ZONE
includes
a time s
a
leg e thi
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LTypes
era
f
d
TIMESTAMP
Data
s
n
igo -tradata
TheI
TIMESTAMP
type is an extension of the DATE data type.
nonTIMESTAMP (fractional_seconds_ precision)
This data type contains the year, month, and day values of date, as well as hour, minute, and second
values of time, where significant fractional seconds precision is the number of digits in the fractional
part of the SECOND datetime field. The accepted values of significant
fractional_seconds_precision are 0 through 9. The default is 6.
TIMESTAMP (fractional_seconds_precision) WITH TIME ZONE
This data type contains all values of TIMESTAMP as well as time zone displacement value.
TIMESTAMP (fractional_seconds_precision) WITH LOCAL TIME ZONE
This data type contains all values of TIMESTAMP, with the following exceptions:
Data is normalized to the database time zone when it is stored in the database.
When the data is retrieved, users see the data in the session time zone.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 10
Cas Training
TIMESTAMP Fields
Datetime Field
Valid Values
YEAR
MONTH
01 to 12
DAY
01 to 31
HOUR
00 to 23
a
s
a
SECOND
00 to 59.9(N) where 9(N) is precision
)h
s
e
a ide
TIMEZONE_HOUR
12 to 14
u
g
ta t Gu
TIMEZONE_MINUTE
s
00 to 59
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
TIMESTAMP
Fields
antype is composed of several of these fields. Datetimes are mutually comparable
igo -data
r
t
Each
Idatetime
non only if they have the same datetime fields.
and assignable
MINUTE
00 to 59
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 11
Cas Training
-- when hire_date is
of type DATE
SELECT hire_date
FROM employees;
SELECT hire_date
FROM employees;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e LType:
eExample
f
d
TIMESTAMP
Data
s
go example
an A shows the data from the hire_date column of the EMPLOYEES table
r
t
In the
Iislide,
on type of the column is DATE. In example B, the table is altered and the data type of the
when thendata
hire_date column is made into TIMESTAMP. The output shows the differences in display. You
can convert from DATE to TIMESTAMP when the column has data, but you cannot convert from
DATE or TIMESTAMP to TIMESTAMP WITH TIME ZONE unless the column is empty.
You can specify the fractional seconds precision for time stamp. If none is specified, as in this
example, it defaults to 6.
For example, the following statement sets the fractional seconds precision as 7:
ALTER TABLE employees
MODIFY hire_date TIMESTAMP(7);
Note: The Oracle date data type by default appears as shown in this example. However, the date data
type also contains additional information such as hours, minutes, seconds, AM, and PM. To obtain
the date in this format, you can apply a format mask or a function to the date value.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 12
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L sferData
d
Comparing
TIMESTAMP
Types
o tran
g
i
In the
- in the slide, a new table web_orders is created with a column of data type
I example
non WITH TIME ZONE and a column of data type TIMESTAMP WITH LOCAL TIME
TIMESTAMP
ZONE. This table is populated whenever a web_order is placed. The time stamp and time zone for
the user placing the order is inserted based on the CURRENT_DATE value. The local time stamp
and time zone is populated by inserting two days from the CURRENT_TIMESTAMP value into it
every time an order is placed. When a Web-based company guarantees shipping, they can estimate
their delivery time based on the time zone of the person placing the order.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 13
Cas Training
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 14
Cas Training
a
s
a
)h
s
e
a ide
u
Data Type
Fields
g
ta t Gu
s
e
INTERVAL YEAR TO MONTH Year, Month
g den
@
a S
tu with
rMinute,
Second
r
INTERVAL DAY TO SECOND Days, Hour,
a
fractional
his
leg seconds
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LTypes
era
f
d
INTERVAL
Data
s
o tran
INTERVAL
- types are used to store the difference between two datetime values. There are two
Iig ondata
n
classes of intervals: year-month intervals and day-time intervals. A year-month interval is made up of
a contiguous subset of fields of YEAR and MONTH, whereas a day-time interval is made up of a
contiguous subset of fields consisting of DAY, HOUR, MINUTE, and SECOND. The actual subset of
fields that constitute an interval is called the precision of the interval and is specified in the interval
qualifier. Because the number of days in a year is calendar dependent, the year-month interval is
NLS dependent, whereas day-time interval is NLS independent.
The interval qualifier may also specify the leading field precision, which is the number of digits in
the leading or only field, and in case the trailing field is SECOND, it may also specify the fractional
seconds precision, which is the number of digits in the fractional part of the SECOND value. If not
specified, the default value for leading field precision is 2 digits, and the default value for fractional
seconds precision is 6 digits.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 15
Cas Training
INTERVAL Data Types (continued)
INTERVAL YEAR (year_precision) TO MONTH
This data type stores a period of time in years and months, where year_precision is the number
of digits in the YEAR datetime field. The accepted values are 0 through 9. The default is 6.
INTERVAL DAY (day_precision) TO SECOND
(fractional_seconds_precision)
This data type stores a period of time in days, hours, minutes, and seconds, where
day_precision is the maximum number of digits in the DAY datetime field (accepted values are
0 through 9; the default is 2), and fractional_seconds_precision is the number of digits
in the fractional part of the SECOND field. The accepted values are 0 through 9. The default is 6.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 16
Cas Training
INTERVAL Fields
INTERVAL Field
YEAR
MONTH
00 to 11
DAY
s
a
h
)
s
e
00
to
59
MINUTE
a ide
u
g
ta t Gu
s
00 to 59.9(N) where 9(N) is precision
SECOND
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
INTERVAL
Fields
o tran
INTERVAL
- TO MONTH can have fields of YEAR and MONTH.
Iig onYEAR
n
INTERVAL DAY TO SECOND can have fields of DAY, HOUR, MINUTE, and SECOND.
HOUR
00 to 23
The actual subset of fields that constitute an item of either type of interval is defined by an interval
qualifier, and this subset is known as the precision of the item.
Year-month intervals are mutually comparable and assignable only with other year-month intervals,
and day-time intervals are mutually comparable and assignable only with other day-time intervals.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 17
Cas Training
a
s
a
SELECT * FROM warranty;
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LTO sMONTH
era Data Type
f
d
INTERVAL
YEAR
o tran
INTERVAL
- TO MONTH stores a period of time using the YEAR and MONTH datetime fields.
Iig onYEAR
n
INSERT INTO warranty VALUES (678, '200-11');
where year_precision is the number of digits in the YEAR datetime field. The default value of
year_precision is 2.
Restriction: The leading field must be more significant than the trailing field. For example,
INTERVAL '0-1' MONTH TO YEAR is not valid.
Examples
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 18
Cas Training
INTERVAL YEAR TO MONTH Data Type (continued)
The Oracle database supports two interval data types: INTERVAL YEAR TO MONTH and INTERVAL
DAY TO SECOND; the column type, PL/SQL argument, variable, and return type must be one of the
two. However, for interval literals, the system recognizes other American National Standards
Institute (ANSI) interval types such as INTERVAL '2' YEAR or INTERVAL '10' HOUR. In these
cases, each interval is converted to one of the two supported types.
In the example in the slide, a WARRANTY table is created, which contains a warranty_time
column that takes the INTERVAL YEAR(3) TO MONTH data type. Different values are inserted into
it to indicate years and months for various products. When these rows are retrieved from the table,
you see a year value separated from the month value by a (-).
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 19
Cas Training
TO SECOND);
a
s
a
)h
s
e
SELECT * FROM lab;
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e TO
d
INTERVAL
DAY
Data Type: Example
s
o tranSECOND
g
i
In the
- in the slide, you are creating the lab table with a test_time column of the
I example
non
INTERVAL DAY TO SECOND data type. You then insert into it the value 90 00:00:00 to indicate
90 days and 0 hours, 0 minutes, and 0 seconds, and INTERVAL '6 03:30:16' DAY TO
SECOND to indicate 6 days, 3 hours, 30 minutes, and 16 seconds. The SELECT statement shows how
this data is displayed in the database.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 20
Cas Training
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 21
Cas Training
EXTRACT
a ide
u
WHERE manager_id = 100;
g
u
a
t
G
s
t
e
n
g
a@ Stude
r
r
a
g
e
his
l
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
EXTRACTo de nsfe
ig -texpression
ra
TheI
EXTRACT
extracts and returns the value of a specified datetime field from a datetime
n
o
n
or interval value expression. You can extract any of the components mentioned in the following
syntax using the EXTRACT function. The syntax of the EXTRACT function is:
SELECT
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 22
Cas Training
TZ_OFFSET
Display the time zone offset for the 'US/Eastern',
'Canada/Yukon' and 'Europe/London' time zones:
SELECT TZ_OFFSET('US/Eastern'),
TZ_OFFSET('Canada/Yukon'),
TZ_OFFSET('Europe/London')
FROM DUAL;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
TZ_OFFSET
n
igo -trafunction
TheI
TZ_OFFSET
returns the time zone offset corresponding to the value entered. The
n
o
n
return value is dependent on the date when the statement is executed. For example, if the
TZ_OFFSET function returns a value 08:00, this value indicates that the time zone where the
command was executed is eight hours behind UTC. You can enter a valid time zone name, a time
zone offset from UTC (which simply returns itself), or the keyword SESSIONTIMEZONE or
DBTIMEZONE. The syntax of the TZ_OFFSET function is:
TZ_OFFSET ( ['time_zone_name'] '[+ | -] hh:mm' ]
[ SESSIONTIMEZONE] [DBTIMEZONE]
The Fold Motor Company has its headquarters in Michigan, USA, which is in the US/Eastern time
zone. The company president, Mr. Fold, wants to conduct a conference call with the vice president of
the Canadian operations and the vice president of European operations, who are in the Canada/Yukon
and Europe/London time zones, respectively. Mr. Fold wants to find out the time in each of these
places to make sure that his senior management will be available to attend the meeting. His secretary,
Mr. Scott, helps by issuing the queries shown in the example and gets the following results:
The 'US/Eastern' time zone is four hours behind UTC.
The 'Canada/Yukon' time zone is seven hours behind UTC.
The 'Europe/London' time zone is one hour ahead of UTC.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 23
Cas Training
TZ_OFFSET (continued)
For a listing of valid time zone name values, you can query the V$TIMEZONE_NAMES dynamic
performance view.
SELECT * FROM V$TIMEZONE_NAMES;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 24
Cas Training
FROM_TZ
Display the TIMESTAMP value '2000-03-28 08:00:00' as a
TIMESTAMP WITH TIME ZONE value for the
'Australia/North' time zone region.
SELECT FROM_TZ(TIMESTAMP
'2000-07-12 08:00:00', 'Australia/North')
FROM DUAL;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
FROM_TZo de nsfe
ig -tfunction
ra converts a TIMESTAMP value to a TIMESTAMP WITH TIME ZONE value.
TheI
FROM_TZ
n
noof the FROM_TZ function is as follows:
The syntax
FROM_TZ(TIMESTAMP timestamp_value, time_zone_value)
where time_zone_value is a character string in the format 'TZH:TZM' or a character
expression that returns a string in TZR (time zone region) with an optional TZD format. TZD is an
abbreviated time zone string with daylight saving information. TZR represents the time zone region
in datetime input strings. Examples are 'Australia/North', 'PST' for US/Pacific standard
time, 'PDT' for US/Pacific daylight time, and so on.
The example in the slide converts a TIMESTAMP value to TIMESTAMP WITH TIME ZONE.
Note: To see a listing of valid values for the TZR and TZD format elements, query the
V$TIMEZONE_NAMES dynamic performance view.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 25
Cas Training
TO_TIMESTAMP
Display the character string '2007-03-06 11:00:00'
as a TIMESTAMP value:
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
TO_TIMESTAMP
igo -tran function converts a string of CHAR, VARCHAR2, NCHAR, or NVARCHAR2
TheI
TO_TIMESTAMP
ona value of the TIMESTAMP data type. The syntax of the TO_TIMESTAMP function is:
data typento
TO_TIMESTAMP (char,[fmt],['nlsparam'])
The optional fmt specifies the format of char. If you omit fmt, then the string must be in the
default format of the TIMESTAMP data type. The optional nlsparam specifies the language in
which month and day names, and abbreviations are returned. This argument can have this form:
'NLS_DATE_LANGUAGE = language'
If you omit nlsparams, this function uses the default date language for your session.
The example in the slide converts a character string to a value of TIMESTAMP.
Note: You use the TO_TIMESTAMP_TZ function to convert a string of CHAR, VARCHAR2, NCHAR,
or NVARCHAR2 data type to a value of the TIMESTAMP WITH TIME ZONE data type. For more
information about this function, see Oracle Database SQL Language Reference 11g Release 1 (11.1).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 26
Cas Training
TO_YMINTERVAL
Display a date that is one year and two months after the hire
date for the employees working in the department with the
DEPARTMENT_ID 20.
SELECT hire_date,
hire_date + TO_YMINTERVAL('01-02') AS
HIRE_DATE_YMININTERVAL
FROM
employees
WHERE department_id = 20;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
TO_YMINTERVAL
igo -tran function converts a character string of CHAR, VARCHAR2, NCHAR, or
TheI
TO_YMINTERVAL
non data type to an INTERVAL YEAR TO MONTH data type. The INTERVAL YEAR TO
NVARCHAR2
MONTH data type stores a period of time using the YEAR and MONTH datetime fields. The format of
INTERVAL YEAR TO MONTH is as follows:
INTERVAL YEAR [(year_precision)] TO MONTH
where year_precision is the number of digits in the YEAR datetime field. The default value of
year_precision is 2.
The syntax of the TO_YMINTERVAL function is:
TO_YMINTERVAL (char)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 27
Cas Training
TO_DSINTERVAL
Display a date that is 100 days and 10 hours after the hire date
for all the employees.
SELECT last_name,
TO_CHAR(hire_date, 'mm-dd-yy:hh:mi:ss') hire_date,
TO_CHAR(hire_date +
TO_DSINTERVAL('100 10:00:00'),
'mm-dd-yy:hh:mi:ss') hiredate2
FROM employees;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
TO_DSINTERVAL
o
n
TO_DSINTERVAL
Iig on-tra converts a character string of the CHAR, VARCHAR2, NCHAR, or NVARCHAR2
data typento an INTERVAL DAY TO SECOND data type.
In the example in the slide, the date 100 days and 10 hours after the hire date is obtained.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 28
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LTime
era
f
d
Daylight Saving
(DST)
s
an advance the clock ahead one hour during the summer months. This period is
igo -nations
r
t
Most
Iwestern
non saving time. Daylight saving time lasts from the first Sunday in April to the last
called daylight
Sunday in October in the most of the United States, Mexico, and Canada. The nations of the
European Union observe daylight saving time, but they call it the summer time period. Europes
summer time period begins a week earlier than its North American counterpart, but ends at the same
time.
The Oracle database automatically determines, for any given time zone region, whether daylight
saving time is in effect and returns local time values accordingly. The datetime value is sufficient for
the Oracle database to determine whether daylight saving time is in effect for a given region in all
cases except boundary cases. A boundary case occurs during the period when daylight saving time
goes into or out of effect. For example, in the US/Eastern region, when daylight saving time goes
into effect, the time changes from 01:59:59 AM to 03:00:00 AM. The one-hour interval between
02:00:00 AM and 02:59:59 AM. does not exist. When daylight saving time goes out of effect, the
time changes from 02:00:00 AM back to 01:00:01 AM, and the one-hour interval between 01:00:01
AM and 02:00:00 AM is repeated.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 29
Cas Training
Daylight Saving Time (DST) (continued)
ERROR_ON_OVERLAP_TIME
The ERROR_ON_OVERLAP_TIME is a session parameter to notify the system to issue an error when
it encounters a datetime that occurs in the overlapped period and no time zone abbreviation was
specified to distinguish the period.
For example, daylight saving time ends on October 31, at 02:00:01 AM. The overlapped periods are:
10/31/2004 01:00:01 AM to 10/31/2004 02:00:00 AM (EDT)
10/31/2004 01:00:01 AM to 10/31/2004 02:00:00 AM (EST)
If you input a datetime string that occurs in one of these two periods, you need to specify the time
zone abbreviation (for example, EDT or EST) in the input string for the system to determine the
period. Without this time zone abbreviation, the system does the following:
If the ERROR_ON_OVERLAP_TIME parameter is FALSE, it assumes that the input time is standard
time (for example, EST). Otherwise, an error is raised.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 30
Cas Training
Quiz
The TIME_ZONE session parameter may be set to:
1.
2.
3.
4.
A relative offset
Database time zone
OS local time zone
A named region
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
eL
Answers:o2,d3, 4 nsfe
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 31
Cas Training
Summary
In this lesson, you should have learned how to use the
following functions:
CURRENT_DATE
CURRENT_TIMESTAMP
LOCALTIMESTAMP
DBTIMEZONE
SESSIONTIMEZONE
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
ez
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
s
g
(ile se thi
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e sfe
Summaryo d
an some of the datetime functions available in the Oracle database.
ig addressed
r
t
This
Ilesson
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 32
Cas Training
Practice 5: Overview
This practice covers using the datetime functions.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Practice 5:
Overview
o tran
In this
- you display time zone offsets, CURRENT_DATE, CURRENT_TIMESTAMP, and
Iigpractice,
non
LOCALTIMESTAMP.
You also set time zones and use the EXTRACT function.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 33
Cas Training
Practice 5
1. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.
2. a. Write queries to display the time zone offsets (TZ_OFFSET) for the following
time zones.
- US/Pacific-New
- Singapore
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
s to the time zone offset of
g thivalue
b. Alter the session to set the TIME_ZONE
leparameter
i
(
e
US/Pacific-New.
ez o us
l
t
c. Display CURRENT_DATE,
and LOCALTIMESTAMP
nzCURRENT_TIMESTAMP,
e
o
s
n
for this session. a G
ce
r
i
r
l
a
eg rable
L
de nsfe
o
trasession to set the TIME_ZONE parameter value to the time zone offset of
Iid.g Alter
the
n
o
nSingapore.
- Egypt
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 34
Cas Training
Practice 5 (continued)
4. Write a query to extract the YEAR from the HIRE_DATE column of the EMPLOYEES table for
those employees who work in department 80.
a
s
a
)h
s
e
a ide
u
g
u
b. Modify the data type of the DATE_COL column and change
Select
tait to TIMESTAMP.
G
s
t
e
n
g de
from the table to view the data.
@
a
tu
r
r
S
a
leg e this
i
(
ez o us
l
nz se t
o
c. Try to modify the data
type of
enthe DATE_COL column and change it to TIMESTAMP
chappens?
ra G
i
r
l
WITH TIMEaZONE.
What
eg rable
L
e last names from the EMPLOYEES table and calculate the review
daequeryntosfretrieve
7. Create
o
ig If-the
trayear hired was 1998, display Needs Review for the review status; otherwise,
Istatus.
n
no not this year! Name the review status column Review. Sort the results by the
display
HIRE_DATE column.
Hint: Use a CASE expression with the EXTRACT function to calculate the review status.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 35
Cas Training
Practice 5 (continued)
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 36
Cas Training
Practice 5 (continued)
8. Create a query to print the last names and the number of years of service for each employee. If
the employee has been employed for five or more years, print 5 years of service. If the
employee has been employed for 10 or more years, print 10 years of service. If the
employee has been employed for 15 or more years, print 15 years of service. If none of
these conditions match, print maybe next year! Sort the results by the HIRE_DATE
column. Use the EMPLOYEES table.
Hint: Use CASE expressions and TO_YMINTERVAL.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 5 - 37
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Write a multiple-column subquery
Use scalar subqueries in SQL
Solve problems with correlated subqueries
Update and delete rows using correlated subqueries
Use the EXISTS and NOT EXISTS operators
s
a
h
Use the WITH clause
s)
e e
a
u
ag Guid
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
InIthis
n- you learn how to write multiple-column subqueries and subqueries in the FROM
o
n
clause of a SELECT statement. You also learn how to solve problems by using scalar, correlated
subqueries and the WITH clause.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 2
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 3
Cas Training
Multiple-Column Subqueries
Main query
WHERE (MANAGER_ID, DEPARTMENT_ID)
IN
Subquery
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g dtoenvalues
@
Each row of the main query is compared
ra Stu
r
a
from a multiple-row and multiple-column
subquery.
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Subqueries
era
f
d
s
Multiple-Column
n
igo -trawritten
SoI
far, younhave
single-row subqueries and multiple-row subqueries where only one
o
n
column is returned by the inner SELECT statement and this is used to evaluate the expression in
100
102
124
90
60
50
the parent SELECT statement. If you want to compare two or more columns, you must write a
compound WHERE clause using logical operators. Using multiple-column subqueries, you can
combine duplicate WHERE conditions into a single WHERE clause.
Syntax
SELECT
column, column, ...
FROM table
WHERE(column, column, ...) IN
(SELECT column, column, ...
FROM
table
WHERE condition);
The graphic in the slide illustrates that the values of MANAGER_ID and DEPARTMENT_ID
from the main query are being compared with the MANAGER_ID and DEPARTMENT_ID values
retrieved by the subquery. Because the number of columns that are being compared is more than
one, the example qualifies as a multiple-column subquery.
Note: Before you run the examples in the next few slides, you need to create the empl_demo
table and populate data into it by using the lab_06_insert_empdata.sql file.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 4
Cas Training
Column Comparisons
Multiple-column comparisons involving subqueries can be:
Nonpairwise comparisons
Pairwise comparisons
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Nonpairwise
s
PairwiseoVersus
Comparisons
n
g
a
i
r
I on-t comparisons involving subqueries can be nonpairwise comparisons or pairwise
Multiple-column
n If you consider the example Display the details of the employees who work in the
comparisons.
same department, and have the same manager, as Daniel? , you get the correct result with the
following statement:
SELECT first_name, last_name, manager_id, department_id
FROM empl_demo
WHERE manager_id IN (SELECT manager_id
FROM empl_demo
WHERE first_name = Daniel)
AND department_id IN (SELECT department_id
FROM empl_demo
WHERE first_name = Daniel);
There is only one Daniel in the EMPL_DEMO table (Daniel Faviet, who is managed by
employee 108 and works in department 100). However, if the subqueries return more than one
row, the result might not be correct. For example, if you run the same query but substitute
John for Daniel, you get an incorrect result. This is because the combination of
department_id and manager_id is important. To get the correct result for this query, you
need a pairwise comparison.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 5
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
de nsfeSubquery
PairwiseoComparison
ig -intrathe slide compares the combination of values in the MANAGER_ID column and
Iexample
The
non
the DEPARTMENT_ID
column of each row in the EMPL_DEMO table with the values in the
MANAGER_ID column and the DEPARTMENT_ID column for the employees with the
FIRST_NAME of John. First, the subquery to retrieve the MANAGER_ID and
DEPARTMENT_ID values for the employees with the FIRST_NAME of John is executed.
This subquery returns the following:
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 6
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eComparison
d
Nonpairwise
Subquery
o trans
g
i
Iexample
The
n-shows a nonpairwise comparison of the columns. First, the subquery to retrieve the
o
n
MANAGER_ID values for the employees with the FIRST_NAME of John is executed.
Similarly, the second subquery to retrieve the DEPARTMENT_ID values for the employees with
the FIRST_NAME of John is executed. The retrieved values of the MANAGER_ID and
DEPARTMENT_ID columns are compared with the MANAGER_ID and DEPARTMENT_ID
columns for each row in the EMPL_DEMO table. If the MANAGER_ID column of the row in the
EMPL_DEMO table matches with any of the values of MANAGER_ID retrieved by the inner
subquery and if the DEPARTMENT_ID column of the row in the EMPL_DEMO table matches
with any of the values of DEPARTMENT_ID retrieved by the second subquery, the record is
displayed.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 8
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
This query retrieves additional rows than the pairwise comparison (those with the combination
of manager_id=100 and department_id=50 or 80, although no employee named John has such
a combination).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 9
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 10
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sinfeSQL
d
Scalar Subqueries
o tran
ig nthat
- returns exactly one column value from one row is also referred to as a scalar
A Isubquery
o
n
subquery. Multiple-column subqueries that are written to compare two or more columns, using a
compound WHERE clause and logical operators, do not qualify as scalar subqueries.
The value of the scalar subquery expression is the value of the select list item of the subquery. If
the subquery returns 0 rows, the value of the scalar subquery expression is NULL. If the
subquery returns more than one row, the Oracle server returns an error. The Oracle server has
always supported the usage of a scalar subquery in a SELECT statement. You can use scalar
subqueries in:
The condition and expression part of DECODE and CASE
All clauses of SELECT except GROUP BY
The SET clause and WHERE clause of an UPDATE statement
However, scalar subqueries are not valid expressions in the following places:
As default values for columns and hash expressions for clusters
In the RETURNING clause of data manipulation language (DML) statements
As the basis of a function-based index
In GROUP BY clauses, CHECK constraints, and WHEN conditions
In CONNECT BY clauses
In statements that are unrelated to queries, such as CREATE PROFILE
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 11
Cas Training
a
s
a
)h
Scalar subqueries in the ORDER BY clause:
s
e
a ide
u
SELECT
employee_id, last_name
g
ta t Gu
s
FROM
employees e
e
g den
ORDER BY (SELECT department_name
@
ra Stu
r
FROM departments d
a
his
leg = ed.department_id);
i
t
WHERE e.department_id
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sExamples
era
f
d
Scalar Subqueries:
anin the slide demonstrates that scalar subqueries can be used in CASE
igoexample
r
t
Ifirst
The
nonThe inner query returns the value 20, which is the department ID of the department
expressions.
whose location ID is 1800. The CASE expression in the outer query uses the result of the inner
query to display the employee ID, last names, and a value of Canada or USA, depending on
whether the department ID of the record retrieved by the outer query is 20 or not.
The following is the result of the first example in the slide:
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 12
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
The second example uses a correlated subquery. In a correlated subquery, the subquery
references a column from a table referred to in the parent statement. Correlated subqueries are
explained later in this lesson.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 13
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 14
Cas Training
Correlated Subqueries
Correlated subqueries are used for row-by-row processing.
Each subquery is executed once for every row of the outer
query.
GET
candidate row from outer query
a
s
a
EXECUTE
)h
s
e
inner query using candidate row value
a ide
u
g
ta t Gu
s
e
g den
@
USE
tuor
rato qualify
r
S
a
values from inner query
is
leg e throw
i
(
disqualify
candidate
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Correlated
Subqueries
anperforms a correlated subquery when the subquery references a column from
igo server
r
t
IOracle
The
on
a table n
referred to in the parent statement. A correlated subquery is evaluated once for each row
processed by the parent statement. The parent statement can be a SELECT, UPDATE, or
DELETE statement.
Nested Subqueries Versus Correlated Subqueries
With a normal nested subquery, the inner SELECT query runs first and executes once, returning
values to be used by the main query. A correlated subquery, however, executes once for each
candidate row considered by the outer query. That is, the inner query is driven by the outer
query.
Nested Subquery Execution
The inner query executes first and finds a value.
The outer query executes once, using the value from the inner query.
Correlated Subquery Execution
Get a candidate row (fetched by the outer query).
Execute the inner query using the value of the candidate row.
Use the values resulting from the inner query to qualify or disqualify the candidate.
Repeat until no candidate row remains.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 15
Cas Training
Correlated Subqueries
The subquery references a column from a table in the parent
query.
SELECT column1, column2, ...
outer
FROM
table1
WHERE column1 operator
(SELECT
FROM
WHERE
column1, column2
table2
expr1 =
outer.expr2);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L sfer(continued)
d
Correlated
Subqueries
o tran
ig n-subquery
A Icorrelated
is one way of reading every row in a table and comparing values in each
o
n
row against related data. It is used whenever a subquery must return a different result or set of
results for each candidate row considered by the main query. That is, you use a correlated
subquery to answer a multipart question whose answer depends on the value in each row
processed by the parent statement.
The Oracle server performs a correlated subquery when the subquery references a column from
a table in the parent query.
Note: You can use the ANY and ALL operators in a correlated subquery.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 16
Cas Training
a
s
a
)h
s
e
a ide
u
g
u
tatime taG
Each
row from
s
e
nquery
gthe outer
e
@
d
tu
ra isSprocessed,
r
the
a
s
g
i
e
h
l
(i se t inner query is
z
e
evaluated.
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe
de nSubqueries
s
Using Correlated
o
ig -intrathe slide determines which employees earn more than the average salary of their
Iexample
The
nonIn this case, the correlated subquery specifically computes the average salary for
department.
each department.
Because both the outer query and inner query use the EMPLOYEES table in the FROM clause, an
alias is given to EMPLOYEES in the outer SELECT statement for clarity. The alias makes the
entire SELECT statement more readable. Without the alias, the query would not work properly
because the inner statement would not be able to distinguish the inner table column from the
outer table column.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 17
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Subqueries
era (continued)
f
d
s
Using Correlated
igo -intrathenslide displays the details of those employees who have changed jobs at least
Iexample
The
nonOracle server evaluates a correlated subquery as follows:
twice. The
1. Select a row from the table specified in the outer query. This will be the current candidate
row.
2. Store the value of the column referenced in the subquery from this candidate row. (In the
example in the slide, the column referenced in the subquery is E.EMPLOYEE_ID.)
3. Perform the subquery with its condition referencing the value from the outer querys
candidate row. (In the example in the slide, the COUNT(*) group function is evaluated
based on the value of the E.EMPLOYEE_ID column obtained in step 2.)
4. Evaluate the WHERE clause of the outer query on the basis of results of the subquery
performed in step 3. This determines whether the candidate row is selected for output. (In
the example, the number of times an employee has changed jobs, evaluated by the
subquery, is compared with 2 in the WHERE clause of the outer query. If the condition is
satisfied, that employee record is displayed.)
5. Repeat the procedure for the next candidate row of the table, and so on, until all the rows in
the table have been processed.
The correlation is established by using an element from the outer query in the subquery. In this
example, you compare EMPLOYEE_ID from the table in the subquery with EMPLOYEE_ID
from the table in the outer query.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 18
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 19
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
EXISTS o
Operator
g -SELECT
tra statements, all logical operators are valid. In addition, you can use the
Iinesting
With
n
nooperator. This operator is frequently used with correlated subqueries to test whether a
EXISTS
The search continues in the inner query
value retrieved by the outer query exists in the results set of the values retrieved by the inner
query. If the subquery returns at least one row, the operator returns TRUE. If the value does not
exist, it returns FALSE. Accordingly, NOT EXISTS tests whether a value retrieved by the outer
query is not a part of the results set of the values retrieved by the inner query.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 20
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Operator
era
f
d
Using the
EXISTS
s
an ensures that the search in the inner query does not continue when at least
igo -toperator
r
IEXISTS
The
nonis found for the manager and employee number by the condition:
one match
WHERE manager_id = outer.employee_id.
Note that the inner SELECT query does not need to return a specific value, so a constant can be
selected.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 21
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e EXISTS
d
Using the
NOT
o trans Operator
g
i
I onSolution
Alternative
n
A NOT IN construct can be used as an alternative for a NOT EXISTS operator, as shown in the
following example:
SELECT department_id, department_name
FROM
departments
WHERE department_id NOT IN (SELECT department_id
FROM
employees);
No rows selected.
However, NOT IN evaluates to FALSE if any member of the set is a NULL value. Therefore,
your query will not return any rows even if there are rows in the departments table that
satisfy the WHERE condition.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 22
Cas Training
Correlated UPDATE
Use a correlated subquery to update rows in one table based
on rows from another table.
UPDATE table1 alias1
SET
column = (SELECT expression
FROM
table2 alias2
WHERE alias1.column =
alias2.column);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Correlated
UPDATE
o ran
igcase nof-tthe
InIthe
UPDATE statement, you can use a correlated subquery to update rows in one
o
n
table based on rows from another table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 23
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L s(continued)
era
f
d
Correlated
UPDATE
igo -intrathenslide denormalizes the EMPL6 table by adding a column to store the
Iexample
The
nonname and then populates the table by using a correlated update.
department
Following is another example for a correlated update.
Problem Statement
The REWARDS table has a list of employees who have exceeded expectations in their
performance. Use a correlated subquery to update rows in the EMPL6 table based on rows from
the REWARDS table:
UPDATE empl6
SET
salary = (SELECT empl6.salary + rewards.pay_raise
FROM
rewards
WHERE employee_id =
empl6.employee_id
AND payraise_date =
(SELECT MAX(payraise_date)
FROM
rewards
WHERE employee_id = empl6.employee_id))
WHERE empl6.employee_id
IN
(SELECT employee_id FROM rewards);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 24
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 25
Cas Training
Correlated DELETE
Use a correlated subquery to delete rows in one table based on
rows from another table.
DELETE FROM table1 alias1
WHERE column operator
(SELECT expression
FROM
table2 alias2
WHERE alias1.column = alias2.column);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Correlated
DELETE
o
an statement, you can use a correlated subquery to delete only those rows
igcase nof-tarDELETE
InIthe
noexist in another table. If you decide that you will maintain only the last four job history
that also
records in the JOB_HISTORY table, then when an employee transfers to a fifth job, you delete
the oldest JOB_HISTORY row by looking up the JOB_HISTORY table for the
MIN(START_DATE)for the employee. The following code illustrates how the preceding
operation can be performed using a correlated DELETE:
DELETE FROM emp_history JH
WHERE employee_id =
(SELECT employee_id
FROM employees E
WHERE JH.employee_id = E.employee_id
AND START_DATE =
(SELECT MIN(start_date)
FROM job_history JH
WHERE JH.employee_id = E.employee_id)
AND 5 > (SELECT COUNT(*)
FROM job_history JH
WHERE JH.employee_id = E.employee_id
GROUP BY EMPLOYEE_ID
HAVING COUNT(*) >= 4));
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 26
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L s(continued)
era
f
d
Correlated
DELETE
o
n
Iig on-tra
Example
n
Two tables are used in this example. They are:
The EMPL6 table, which provides details of all the current employees
The EMP_HISTORY table, which provides details of previous employees
EMP_HISTORY contains data regarding previous employees, so it would be erroneous if the
same employees record existed in both the EMPL6 and EMP_HISTORY tables. You can delete
such erroneous records by using the correlated subquery shown in the slide.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 27
Cas Training
Lesson Agenda
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 28
Cas Training
WITH Clause
Using the WITH clause, you can use the same query block
in a SELECT statement when it occurs more than once
within a complex query.
The WITH clause retrieves the results of a query block and
stores it in the users temporary tablespace.
The WITH clause may improve performance.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
WITH Clause
o tran
IigtheoWITH
Using
n- clause, you can define a query block before using it in a query. The WITH
n
clause (formally known as subquery_factoring_clause) enables you to reuse the same
query block in a SELECT statement when it occurs more than once within a complex query.
This is particularly useful when a query has many references to the same query block and there
are joins and aggregations.
Using the WITH clause, you can reuse the same query when it is costly to evaluate the query
block and it occurs more than once within a complex query. Using the WITH clause, the Oracle
server retrieves the results of a query block and stores it in the users temporary tablespace. This
can improve performance.
WITH Clause Benefits
Makes the query easy to read
Evaluates a clause only once, even if it appears multiple times in the query
In most cases, may improve performance for large queries
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 29
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eExample
d
WITH Clause:
o trans
g
i
Iproblem
The
n-in the slide would require the following intermediate calculations:
o
n
1. Calculate the total salary for every department, and store the result using a WITH clause.
2. Calculate the average salary across departments, and store the result using a WITH clause.
3. Compare the total salary calculated in the first step with the average salary calculated in the
second step. If the total salary for a particular department is greater than the average salary
across departments, then display the department name and the total salary for that
department.
The solution for this problem is provided on the next page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 30
Cas Training
WITH
dept_costs AS (
SELECT d.department_name, SUM(e.salary) AS dept_total
FROM
employees e JOIN departments d
ON
e.department_id = d.department_id
GROUP BY d.department_name),
avg_cost
AS (
SELECT SUM(dept_total)/COUNT(*) AS dept_avg
FROM
dept_costs)
SELECT *
FROM
dept_costs
WHERE dept_total >
(SELECT dept_avg
FROM avg_cost)
ORDER BY department_name;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eExample
d
WITH Clause:
o trans (continued)
g
i
ISQLocode
The
n- in the slide is an example of a situation in which you can improve performance
n
and write SQL more simply by using the WITH clause. The query creates the query names
DEPT_COSTS and AVG_COST and then uses them in the body of the main query. Internally,
the WITH clause is resolved either as an in-line view or a temporary table. The optimizer
chooses the appropriate resolution depending on the cost or benefit of temporarily storing the
results of the WITH clause.
The output generated by the SQL code in the slide is as follows:
Cas Training
Quiz
With a correlated subquery, the inner SELECT statement drives
the outer SELECT statement.
1. True
2. False
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Answer:o2 d
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 32
Cas Training
Summary
In this lesson, you should have learned that:
A multiple-column subquery returns more than one column
Multiple-column comparisons can be pairwise or
nonpairwise
A multiple-column subquery can also be used in the FROM
clause of a SELECT statement
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
an
igouse -multiple-column
r
t
Ican
You
subqueries to combine multiple WHERE conditions in a single
n
o
n
WHERE clause. Column comparisons in a multiple-column subquery can be pairwise
comparisons or nonpairwise comparisons.
You can use a subquery to define a table to be operated on by a containing query.
Scalar subqueries can be used in:
The condition and expression part of DECODE and CASE
All clauses of SELECT except GROUP BY
A SET clause and WHERE clause of the UPDATE statement
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 33
Cas Training
Summary
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
(continued)
anperforms a correlated subquery when the subquery references a column from
igo server
r
t
IOracle
The
on
a table n
referred to in the parent statement. A correlated subquery is evaluated once for each row
processed by the parent statement. The parent statement can be a SELECT, UPDATE, or
DELETE statement. Using the WITH clause, you can reuse the same query when it is costly to
reevaluate the query block and it occurs more than once within a complex query.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 34
Cas Training
Practice 6: Overview
This practice covers the following topics:
Creating multiple-column subqueries
Writing correlated subqueries
Using the EXISTS operator
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Practiceo6:dOverview
ayoun write multiple-column subqueries, and correlated and scalar subqueries.
r
t
igpractice,
InIthis
n
nosolve
You also
problems by writing the WITH clause.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 35
Cas Training
Practice 6
1. Write a query to display the last name, department number, and salary of any employee
whose department number and salary both match the department number and salary of any
employee who earns a commission.
2. Display the last name, department name, and salary of any employee whose salary and
commission match the salary and commission of any employee located in location ID 1700.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
z name,
t date, and salary for all employees who have the
nlast
3. Create a query to display the
hire
e
o
s
n
same salary and commission
eKochhar.
a G las
c
r
i
r
a Kochhar
Note: Do notedisplay
g
le in the result set.
b
L
a
e sfer
d
o
n
Iig on-tra
n
4. Create a query to display the employees who earn a salary that is higher than the salary of
all the sales managers (JOB_ID = 'SA_MAN'). Sort the results on salary from the highest
to the lowest.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 36
Cas Training
Practice 6 (continued)
5. Display details such as the employee ID, last name, and department ID of those employees
who live in cities the names of which begin with T.
6. Write a query to find all employees who earn more than the average salary in their
departments. Display last name, salary, department ID, and the average salary for the
department. Sort by average salary and round to two decimals. Use aliases for the columns
retrieved by the query as shown in the sample output.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
n
7. Find all employees who
esupervisors.
a Gare not
c
r
i
r
l
ausingbthe
a. First, do this
g
leNOT EXISTS operator.
e
L
a
e sfer
d
o
n
Iig on-tra
n
b. Can this be done by using the NOT IN operator? How, or why not?
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 37
Cas Training
Practice 6 (continued)
8. Write a query to display the last names of the employees who earn less than the average
salary in their departments.
a
s
a
)h
s
e
a ide
u
g
u
tahave tone
G
s
9. Write a query to display the last names of the employees
who
or
more coworkers
e
n
g
e
in their departments with later hire dates but higher
salaries.
tud
ra@
r
S
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
10. Write a query to display the employee ID, last names, and department names of all
employees.
Note: Use a scalar subquery to retrieve the department name in the SELECT statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 38
Cas Training
Practice 6 (continued)
11. Write a query to display the department names of those departments whose total salary
cost is above one-eighth (1/8) of the total salary cost of the whole company. Use the WITH
clause to write this query. Name the query SUMMARY.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 6 - 39
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
List the benefits of using regular expressions
Use regular expressions to search for, match, and replace
strings
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
InIthis
n- you learn to use the regular expression support feature. Regular expression
o
n
support is available in both SQL and PL/SQL.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 2
Cas Training
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
s
a
h
Accessing subexpressions
s)
e
a ide
Using the REGEXP_COUNT function
u
g
u
a
t
G
s
t
e
Regular expressions and check constraints
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 3
Cas Training
t
G
s
t
e
n
g
a@ Stude
r
r
a
g
e
his
l
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Expressions?
era
f
d
s
What Are
Regular
o tran
IigDatabase
Oracle
n- provides support for regular expressions. The implementation complies with
o
n
the Portable Operating System for UNIX (POSIX) standard, controlled by the Institute of
Electrical and Electronics Engineers (IEEE), for ASCII data-matching semantics and syntax.
Oracles multilingual capabilities extend the matching capabilities of the operators beyond the
POSIX standard. Regular expressions are a method of describing both simple and complex
patterns for searching and manipulating.
String manipulation and searching contribute to a large percentage of the logic within a
Web-based application. Usage ranges from the simple, such as finding the word San Francisco
in a specified text, to the complex task of extracting all URLs from the text and the more
complex task of finding all words whose every second character is a vowel.
When coupled with native SQL, the use of regular expressions allows for very powerful search
and manipulation operations on any data stored in an Oracle database. You can use this feature
to easily solve problems that would otherwise involve complex programming.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 4
Cas Training
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera Expressions
BenefitsoofdUsingnRegular
tra are a powerful text-processing component of programming languages such
Iig expressions
Regular
n
noand Java. For example, a PERL script can process each HTML file in a directory, read
as PERL
its contents into a scalar variable as a single string, and then use regular expressions to search for
URLs in the string. One reason for many developers writing in PERL is that it has a robust
pattern-matching functionality. Oracles support of regular expressions enables developers to
implement complex match logic in the database. This technique is useful for the following
reasons:
By centralizing match logic in Oracle Database, you avoid intensive string processing of
SQL results sets by middle-tier applications. The SQL regular expression functions move
the processing logic closer to the data, thereby providing a more efficient solution.
Before Oracle Database 10g, developers often coded data validation logic on the client,
requiring the same validation logic to be duplicated for multiple clients. Using server-side
regular expressions to enforce constraints solves this problem.
The built-in SQL and PL/SQL regular expression functions and conditions make string
manipulations more powerful and less cumbersome than in previous releases of Oracle
Database 10g.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 5
Cas Training
Description
REGEXP_LIKE
REGEXP_REPLACE
a
s
a
)h
s
e
a ide
u
g
u a
Searches for a regular expression
within
REGEXP_SUBSTR
tapattern
G
s
t
e
given string and extracts the
nsubstring
g matched
e
@
d
ra Stu
r
a
g ofthtimes
is a pattern match is found
lenumber
Returns the
REGEXP_COUNT
i
(
e
z stingus
in an
einput
l
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sExpressions
era
f
d
Using the
Regular
Functions and Conditions in SQL and PL/SQL
o tran
g
i
I Database
Oracle
n- provides a set of SQL functions that you use to search and manipulate strings
o
n
using regular expressions. You use these functions on a text literal, bind variable, or any column
REGEXP_INSTR
that holds character data such as CHAR, NCHAR, CLOB, NCLOB, NVARCHAR2, and VARCHAR2
(but not LONG). A regular expression must be enclosed or wrapped between single quotation
marks. This ensures that the entire expression is interpreted by the SQL function and can
improve the readability of your code.
REGEXP_LIKE: This condition searches a character column for a pattern. Use this condition in
the WHERE clause of a query to return rows matching the regular expression you specify.
REGEXP_REPLACE: This function searches for a pattern in a character column and replaces
each occurrence of that pattern with the pattern you specify.
REGEXP_INSTR: This function searches a string for a given occurrence of a regular expression
pattern. You specify which occurrence you want to find and the start position to search from.
This function returns an integer indicating the position in the string where the match is found.
REGEXP_SUBSTR: This function returns the actual substring matching the regular expression
pattern you specify.
REGEXP_COUNT: This function returns the number of times a pattern match is found in the
input string.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 6
Cas Training
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
s
a
h
Accessing subexpressions
s)
e
a ide
Using the REGEXP_COUNT function
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 7
Cas Training
s
The literals f or ht
a
h
s)
The t literal
e
a ide
u
g
The p literal, optionally followed by the s literal
ta t Gu
s
e
The colon : literal at the end of the
@gstringden
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
What Are
Metacharacters?
an in the slide matches the http:, https:, ftp:, and ftps: strings.
igo expression
r
t
Iregular
The
on
n
Note: For a complete list of the regular expressions metacharacters, see the Oracle Database
Advanced Application Developers Guide 11g Release 1 (11.1)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 8
Cas Training
Description
{m}
s
a
h
Matches at least m, but not more than n, occurrences of the preceding
{m,n}
s)
e
subexpression
a ide
u
g
Matches any single character in the list within the brackets
[]
ta t Gu
s
e
g den
Matches one of the alternatives
|
@
ra Stu
r
a
the iparentheses
as a unit. The
( ... ) Treats the enclosed expression
hor sa complex expression
legofwithin
i
t
subexpression can be a string
literals
containing
(
e
z
operators.
s
e
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
de nsfein Regular Expressions Functions
Using Metacharacters
o
ig -tra . : a.b matches the strings abb, acb, and adb, but not acc.
Icharacter,
Any
non
{m, }
One or more, + : a+ matches the strings a, aa, and aaa, but does not match bbb.
Zero or one, ? : ab?c matches the strings abc and ac, but does not match abbc.
Zero or more, * : ab*c matches the strings ac, abc, and abbc, but does not match abb.
Exact count, {m} : a{3} matches the strings aaa, but does not match aa.
At least count, {m,} : a{3,} matches the strings aaa and aaaa, but not aa.
Between count, {m,n} : a{3,5} matches the strings aaa, aaaa, and aaaaa, but not aa.
Matching character list, [] : [abc] matches the first character in the strings all, bill,
and cold, but does not match any characters in doll.
Or, | : a|b matches character a or character b.
Subexpression, () :(abc)?def matches the optional string abc, followed by def. The
expression matches abcdefghi and def, but does not match ghi. The subexpression can be a
string of literals or a complex expression containing operators.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 9
Cas Training
Description
\n
a
s
a
)h
s
e
acharacter
class
e
[:class:] Matches any character belonging to the specified POSIX
u
d
i
g
ta t Gu
s
e
n
g debrackets
list within the
[^:class:] Matches any single character not in the
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sferinaRegular Expressions Functions (continued)
d
Using Metacharacters
o
anline anchor, ^ and $: ^def matches def in the string defghi but
Iig on-trof
Beginning/end
nmatch def in abcdef. def$ matches def in the string abcdef but does not match
does not
\d
A digit character
Cas Training
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
s
a
h
Accessing subexpressions
s)
e
a ide
Using the REGEXP_COUNT function
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 11
Cas Training
REGEXP_INSTR
s
a
h
s)
REGEXP_REPLACE(source_char, pattern [,replacestr
e
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 12
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eBasic
d
Performing
a
o transSearch Using the REGEXP_LIKE Condition
g
i
I on- is similar to the LIKE condition, except that REGEXP_LIKE performs regularREGEXP_LIKE
n matching instead of the simple pattern matching performed by LIKE. This condition
expression
evaluates strings using characters as defined by the input character set.
Example of REGEXP_LIKE
In this query, against the EMPLOYEES table, all employees with first names containing either
Steven or Stephen are displayed. In the expression used,
'^Ste(v|ph)en$'
^ indicates the beginning of the expression
$ indicates the end of the expression
| indicates either/or
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 13
Cas Training
Replacing Patterns
Using the REGEXP_REPLACE Function
REGEXP_REPLACE(source_char, pattern [,replacestr
[, position [, occurrence [, match_option]]]])
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sUsing
era the REGEXP_REPLACE Function
f
d
Replacing
Patterns
o tran
IigtheoREGEXP_REPLACE
Using
function, you reformat the phone number to replace the period
nn
(.) delimiter with a dash (-) delimiter. Here is an explanation of each of the elements used in the
Original
Partial results
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 14
Cas Training
Finding Patterns
Using the REGEXP_INSTR Function
REGEXP_INSTR (source_char, pattern [, position [,
occurrence [, return_option [, match_option]]]])
SELECT street_address,
REGEXP_INSTR(street_address,'[[:alpha:]]') AS
First_Alpha_Position
FROM locations;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nUsing
Finding o
Patterns
s the REGEXP_INSTR Function
g
a
i
r
example,
-t the REGEXP_INSTR function is used to search the street address to find the
InIthis
n
o
locationnof the first alphabetic character, regardless of whether it is in uppercase or lowercase.
Note that [:<class>:] implies a character class and matches any character from within that
class; [:alpha:] matches with any alphabetic character. The partial results are displayed.
In the expression used in the query '[[:alpha:]]':
[ starts the expression.
[:alpha:] indicates alphabetic character class.
] ends the expression.
Note: The POSIX character class operator enables you to search for an expression within a
character list that is a member of a specific POSIX character class. You can use this operator to
search for specific formatting, such as uppercase characters, or you can search for special
characters such as digits or punctuation characters. The full set of POSIX character classes is
supported. Use the syntax [:class:] where class is the name of the POSIX character class
to search for. The following regular expression searches for one or more consecutive uppercase
characters : [[:upper:]]+ .
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 15
Cas Training
Extracting Substrings
Using the REGEXP_SUBSTR Function
REGEXP_SUBSTR (source_char, pattern [, position
[, occurrence [, match_option]]])
SELECT REGEXP_SUBSTR(street_address , ' [^ ]+ ') AS Road
FROM locations;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L sferUsing
d
Extracting
Substrings
the REGEXP_SUBSTR Function
o tran
g
i
example,
InIthis
n- the road names are extracted from the LOCATIONS table. To do this, the
o
n
contents in the STREET_ADDRESS column that are after the first space are returned using the
REGEXP_SUBSTR function. In the expression used in the query [^ ]+ :
[ starts the expression.
^ indicates NOT.
indicates space.
] ends the expression.
+ indicates 1 or more.
indicates space.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 16
Cas Training
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
s
a
h
Accessing subexpressions
s)
e
a ide
Using the REGEXP_COUNT function
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 17
Cas Training
Subexpressions
Examine this expression:
a
s
a
3
4
)h
s
1
e
a ide
u
g
2
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Subexpressions
o tran
IigDatabase
Oracle
n- 11g provides regular expression support parameter to access a subexpression.
o
n
In the slide example, a string of digits is shown. The parentheses identify the subexpressions
within the string of digits. Reading from left to right, and from outer parentheses to the inner
parentheses, the subexpressions in the string of digits are:
1. 123
2. 45678
3. 56
4. 78
You can search for any of those subexpressions with the REGEXP_INSTR and
REGEXP_SUBSTR functions.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 18
Cas Training
a ide
u
FROM dual;
g
u
a
t
G
s
t
e
n
g
a@ Stude
r
r
a
g
e
his
l
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L sferwith
d
Using Subexpressions
Regular Expression Support
o tran
g
i
I on- and REGEXP_SUBSTR have an optional SUBEXPR parameter that lets you
REGEXP_INSTR
target anparticular substring of the regular expression being evaluated.
In the example shown in the slide, you may want to search for the first subexpression pattern in
your list of subexpressions. The example shown identifies several parameters for the
REGEXP_INSTR function.
1. The string you are searching is identified.
2. The subexpressions are identified. The first subexpression is 123. The second
subexpression is 45678, the third is 56, and the fourth is 78.
3. The third parameter identifies from which position to start searching.
4. The fourth parameter identifies the occurrence of the pattern you want to find. 1 means find
the first occurrence.
5. The fifth parameter is the return option. This is the position of the first character of the
occurrence. (If you specify 1, then the position of the character following the occurrence is
returned.)
6. The sixth parameter identifies whether your search should be case-sensitive or not.
7. The last parameter is the parameter added in Oracle Database 11g. This parameter specifies
which subexpression you want to find. In the example shown, you are searching for the first
subexpression, which is 123.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 19
Cas Training
a
s
a
)h
s
e
a ide
u
'(gtc(tcac)(aaag))',
g
ta t Gu
s
1, 1, 0, 'i',
e
g den
1) "Position" @
ra Stu
r
FROM dual;
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
etheL nthsfSubexpression?
era
d
Why Access
o tran
igsciences,
InIlife
n- you may need to extract the offsets of subexpression matches from a DNA
o
n
sequence for further processing. For example, you may need to find a specific protein sequence,
such as the begin offset for the DNA sequence preceded by gtc and followed by tcac
followed by aaag. To accomplish this goal, you can use the REGEXP_INSTR function, which
returns the position where a match is found.
In the slide example, the position of the first subexpression (gtc)is returned. gtc appears
starting in position 195 of the DNA string.
If you modify the slide example to search for the second subexpression (tcac), the query
results in the following output. tcac appears starting in position 198 of the DNA string.
If you modify the slide example to search for the third subexpression (aaag), the query results
in the following output. aaag appears starting in position 202 of the DNA string.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 20
Cas Training
REGEXP_SUBSTR: Example
SELECT
REGEXP_SUBSTR
1
('acgctgcactgca',
2 'acg(.*)gca',
3 1,
4 1,
5 'i',
6 1)
"Value"
FROM dual;
-------
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Example
era
f
d
REGEXP_SUBSTR
s
o tran
igexample
InIthe
n- shown in the slide:
o
n
1. acgctgcactgca is the source to be searched.
2. acg(.*)gca is the pattern to be searched. Find acg followed by gca with potential
characters between the acg and the gca.
3. Start searching at the first character of the source.
4. Search for the first occurrence of the pattern.
5. Use non-case-sensitive matching on the source.
6. Use a nonnegative integer value that identifies the nth subexpression to be targeted. This is
the subexpression parameter. In this example, 1 indicates the first subexpression. You can
use a value from 09. A zero means that no subexpression is targeted. The default value for
this parameter is 0.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 21
Cas Training
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
s
a
h
Accessing subexpressions
s)
e
a ide
Using the REGEXP_COUNT function
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 22
Cas Training
a
s
a
)h
s
e
a ide
FROM dual;
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera Function
d
Using the
REGEXP_COUNT
igo -tran function evaluates strings using characters as defined by the input
IREGEXP_COUNT
The
n
noset.
character
It returns an integer indicating the number of occurrences of pattern. If no match is
ctctgctctcctctcctgaacccctgaaccctctggctaccccagagcacttagagccag,
gtc) AS Count
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 23
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
de nsfeand
Regular o
Expressions
Check Constraints: Examples
g
a
i
r
-t
I expressions
Regular
can also be used in CHECK constraints. In this example, a CHECK constraint
n
o
n
is added on the EMAIL column of the EMPLOYEES table. This ensures that only strings
containing an @ symbol are accepted. The constraint is tested. The CHECK constraint is
violated because the email address does not contain the required symbol. The NOVALIDATE
clause ensures that existing data is not checked.
For the slide example, the emp8 table is created by using the following code:
CREATE TABLE emp8 AS SELECT * FROM employees;
Note: The example in the slide is executed by using the Execute Statement option in SQL
Developer. The output format differs if you use the Run Script option.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 24
Cas Training
Quiz
With the use of regular expressions in SQL and PL/SQL, you
can:
1. Avoid intensive string processing of SQL result sets by
middle-tier applications
2. Avoid data validation logic on the client
3. Enforce constraints on the server
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e2, L3 sfera
d
Answers:
1,
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 25
Cas Training
Summary
In this lesson, you should have learned how to use regular
expressions to search for, match, and replace strings.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
o tran
iglesson,
InIthis
n- you have learned to use the regular expression support features. Regular
o
n
expression support is available in both SQL and PL/SQL.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 26
Cas Training
Practice 7: Overview
This practice covers using regular expressions functions to do
the following:
Searching for, replacing, and manipulating data
Creating a new CONTACTS table and adding a CHECK
constraint to the p_number column to ensure that phone
numbers are entered into the database in a specific
standard format
a
Testing the adding of some phone numbers into the has
)
p_number column by using various formats aes
gu uide
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Practiceo7:dOverview
n
a
r
t
igpractice,
InIthis
you
use regular expressions functions to search for, replace, and manipulate
n
o
n
data. You also create a new CONTACTS table and add a CHECK constraint to the p_number
column to ensure that phone numbers are entered into the database in a specific standard format.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 27
Cas Training
Practice 7
In this practice, you use regular expressions functions to search for, replace, and manipulate data.
You also create a new contacts table and add a check constraint to the p_number column to
enforce that phone numbers are entered into the database in a specific standard format.
1. Write a query to search the EMPLOYEES table for all employees whose first names start
with Ki or Ko.
2. Create a query that removes the spaces in the STREET_ADDRESS column of the
LOCATIONS table in the display. Use Street Address as the column heading.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
3. Create a query that displays St replaced
ez obyusStreet in the STREET_ADDRESS column
l
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 28
Cas Training
Practice 7 (continued)
5. Run the SQL script lab_07_05.sql to insert the following seven phone numbers into
the contacts table. Which numbers are added?
l_name Column Value
NULL
(650) 555-5555
NULL
(215) 555-3427
NULL
650 555-5555
NULL
NULL
650-555-5555
NULL
(650)555-5555
NULL
(650) 555-5555
sstring
a
6. Write a query to find the number of occurrences of the DNA pattern ctc inhthe
)
gtctcgtctcgttctgtctgtcgttctg. Ignore case-sensitivity. es
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II 7 - 29
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
_____________________
Appendix A:
Practice Solutions
_____________________
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Note the following points before you begin with the practices:
Enter your SQL statements in a SQL Worksheet. To save a script in SQL Developer,
from the File menu, select Save As or right-click in the SQL Worksheet and select Save
file to save your SQL statement. To modify an existing script, use File > Open to open
the script file, make changes, and then make sure you use Save As to save it with a
different file name.
To run the query, click the Execute Statement icon (or press F9) in the SQL Worksheet.
For DML and DDL statements, use the Run Script icon (or press F5).
After you have executed a saved script, make sure that you do not enter your next query
in the same worksheet. Open a new worksheet.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions
In this practice, you review the available SQL Developer resources. You also learn about your
user account that you use in this course. You then start SQL Developer, create a new database
connection, and browse your HR tables. You also set some SQL Developer preferences, execute
SQL statements, and execute an anonymous PL/SQL block using SQL Worksheet. Finally, you
access and bookmark the Oracle Database 11g documentation and other useful Web sites that
you can use in this course.
Accessing SQL Developer Resources
1) Access the SQL Developer home page.
a) Access the online SQL Developer home page available online at:
http://www.oracle.com/technology/products/database/sql_developer/index.html
The SQL Developer home page is displayed as follows:
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
2) Access the SQL Developer tutorial available online at:
http://st-curriculum.oracle.com/tutorial/SQLDeveloper/index.htm
Then, review the following sections and associated demos:
a) What to Do First
b) Working with Database Objects
c) Accessing Data
Starting SQL Developer, Creating and Testing a New SQL Developer Database
Connection, and Connecting to Your oraxx Account
3) Start up SQL Developer using the Desktop icon.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
4) Create a database connection using the following information:
g den
@
ra Stu
a. Connection Name: myconnection.
r
a
eg this
l
i
(
e you one ora account out of the
b. Username: oraxx (Ask your instructor
z to uassign
s
e
l
ora21ora40 range of accounts.)
nz se to
o
a G licen
c. Password: oraxx
r
r
a ble
g
e
a host name for your PC.
d. Hostname:
e L sEnter
erthe
f
d
o tran
- 1521
Iige. oPort:
n
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
n
gothe -new
aconnection.
If the status is Success, connect to the database using this new
r
t
I5)iTest
n
connection.
no
a) Click the Test button in the New/Select Database Connection window.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
b) Expand the Tables icon by clicking the plus sign next to it.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
a
s
a
)h
s
e
a ide
u
g
ta t Gutable in the
8) Execute some basic SELECT statements to query the data in the
EMPLOYEES
s
e
nthe Run Script icons
g F9)dand
e
SQL Worksheet area. Use both the Execute Statement (or
press
@
tu of both methods of
ra the S
(or press F5) to execute the SELECT statements. a
Review
results
r
executing the SELECT statements on the appropriate
his pages.
leg e tabbed
i
t
(
a) Write a query to select the last name
ez andosalary
l
us for any employee whose salary is less
z
t
than or equal to $3,000. n
o nse
G
SELECT last_name,
ce
ra salary
i
r
l
a
FROM employees
g able
e
L
WHERE
e salary
er<= 3000;
f
d
s
oWritetraaquery
n to display last name, job ID, and commission for all employees who are
Iigb) onot
n nentitled to receive a commission.
SELECT last_name, job_id, commission_pct
FROM
employees
WHERE commission_pct IS NULL;
9) Set your script pathing preference to D:\labs\SQL2.
a) Select Tools > Preferences > Database > Worksheet Parameters.
b) Enter the value in the Select default path to look for scripts field. Then, click OK.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
s
a
h
10) Enter the following in the Enter SQL Statement box.
s)
e
a ide
SELECT employee_id, first_name, last_name agu
u
t
G
s
FROM employees;
t
e
g den
@
ra Stu
r
a
g File t>hSave
is As menu item.
11) Save the SQL statement to a script file using
lethe
i
(
e
a) Select File > Save As.
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
c) Place the file under the D:\labs\SQL2\labs folder.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
oclick Save.
Then,
an
r
t
igOpen
I12)
nonand run confidence.sql from your D:\Labs\labs folder and observe the output.
Right-click in the Enter SQL Statement box to open the file. Then, press F5.
The following is the expected result.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
Quiz:
1. What condition do you use to display rows based on a range of values?
BETWEEN
2. The character pattern-matching operation is also referred to as:
Wildcard search
3. Group functions return one result per row. True/False.
False. Group functions give one result per group of rows. Single-row functions
operate on single rows only and return one result per row.
s
a
h
s)
e
UPPER
a ide
u
g
ta t Gu
s
5. Which among the following are group functions?
e
g den
@
a. MAX
ra Stu
r
a
leg e this
i
(
b. TRUNC
ez o us
l
nz se t
c. STDDEV
o
G cen
a
r
r
li
d. MOD
a
e
g
l
Le ferab
e
e.
CONCAT
o d trans
g
i
I of.n-SUM
n
4.
7.
You can sort by a column that is not in the SELECT list. True/False.
True
8.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice I: Solutions (continued)
9.
10. What happens if you do not specify the WHERE clause in a DELETE statement?
If you omit the WHERE clause, all rows in the table are deleted.
11. Consider a SELECT statement that consists of three query blocks: the outer query and
two inner queries. If both the inner queries return single values, what do you call such a
SQL statement?
Single-row subquery
a
s
a
)h
s
e
a in the
e
ualso
d
False. You can use subqueries not only in the WHERE clausea
but
HAVING
i
g
u
t
G
s
clause.
t
e
g den
@
tu there is no employee
rahappensSwhen
r
13. Observe the following SELECT statement. What
a
named Kiran?
leg e this
i
(
ez o us
l
I
n-subquery returns no rows. The outer query takes the results of the subquery
noThe
12. You can use subqueries only in the WHERE clause but not in the HAVING clause.
True/False.
(null) and uses these results in its WHERE clause. The outer query finds no employee
with a job ID equal to null, and so returns no rows. If a job existed with a value of
null, the row is not returned because comparison of two null values yields a null;
therefore, the WHERE condition is not true.
14. The subqueries are processed first by the Oracle server, after which the WHERE or
HAVING clause uses the results. True/False.
True
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 1: Solutions
To complete question 8 and the subsequent ones, you need to connect to the database using
SQL Developer.
1. What privilege should a user be given to log on to the Oracle server? Is this a system or
an object privilege?
The CREATE SESSION system privilege
2. What privilege should a user be given to create tables?
The CREATE TABLE privilege
3. If you create a table, who can pass along privileges to other users on your table?
You can, or anyone you have given those privileges to, by using WITH GRANT
OPTION
a
s
a
)h
s
e
asystem
e
4. You are the DBA. You are creating many users who require the same
privileges.
u
d
i
g
What should you use to make your job easier?
ta t Gu
s
e
n to the users.
g thedrole
Create a role containing the system privileges and grant
e
@
ra Stu
r
a
5. What command do you use to change your
his
legpassword?
i
t
(
e
The ALTER USER statement lez
us
o
z
t
on nse
G
6. User1 is the owner
a of the lEMP
cetable and grants DELETE privileges to User2 by using the
r
i
r
a
WITH GRANT
e clause. User2 then grants DELETE privileges on EMP to User3.
egfindsrOPTION
blUser3
L
a
User1
now
that
has the privilege and revokes it from User2. Which user can
e
e
f
d
s
o nowtdelete
n data from the EMP table?
g
a
i
r
- only
I
User1
non
7. You want to grant SCOTT the privilege to update data in the DEPARTMENTS table. You
also want to enable SCOTT to grant this privilege to other users. What command do you
use?
GRANT UPDATE ON departments TO scott WITH GRANT OPTION;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
REVOKE select
ON regions
FROM <team2_oraxx>;
9. Grant another user query and data manipulation privileges on your COUNTRIES table.
Make sure the user cannot pass on these privileges to other users.
Team 1 executes this statement
GRANT select, update, insert
ON COUNTRIES
TO <team2_oraxx>;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
a
s
a
)h
s
e
a ide
u
Team 1 executes the GRANT statement.
g
ta t Gu
s
e
g den
GRANT select
@
ON departments
ra Stu
r
a
TO <team2_oraxx>;
leg e this
i
(
ez o us
l
FROM
departments;
13. Add a new row to your DEPARTMENTS table. Team 1 should add Education as
department number 500. Team 2 should add Human Resources as department number
510. Query the other teams table.
Team 1 executes this INSERT statement.
INSERT INTO departments(department_id, department_name)
VALUES (500, 'Education');
COMMIT;
Team 2 executes this INSERT statement.
INSERT INTO departments(department_id, department_name)
VALUES (510, 'Human Resources');
COMMIT;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 1: Solutions (continued)
14. Create a synonym for the other teams DEPARTMENTS table.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
aSELECT
16. Revoke the
g
leprivilege from the other team.
e
b
L
a
e sfer
d
o
n
Iig on-traTeam 1 revokes the privilege.
n
REVOKE select
ON
departments
FROM
<team2_oraxx>;
Team 2 revokes the privilege.
REVOKE select
ON
departments
FROM
<team1_oraxx>;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 1: Solutions (continued)
17. Remove the row you inserted into the DEPARTMENTS table in step 8 and save the
changes.
Team 1 executes this DELETE statement.
DELETE FROM departments
WHERE department_id = 500;
COMMIT;
Team 2 executes this DELETE statement.
DELETE FROM departments
WHERE department_id = 510;
COMMIT;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 2: Solutions
1. Create the DEPT2 table based on the following table instance chart. Enter the syntax in
the SQL Worksheet. Then, execute the statement to create the table. Confirm that the
table is created.
Column Name
ID
NAME
NUMBER
VARCHAR2
Key Type
Nulls/Unique
FK Table
FK Column
Data type
a
s
a
)h
s
e
a ide
u
CREATE TABLE dept2
g
ta t Gu
s
(id NUMBER(7),
e
g den
@
name VARCHAR2(25));
ra Stu
r
a
leg e this
i
(
DESCRIBE dept2
ez o us
l
nz se t
o
Gtable with
2. Populate the DEPT2
endata from the DEPARTMENTS table. Include only the
a
c
r
i
r
l
columns thatayou need.e
eg rabl
L
feINTO dept2
de INSERT
s
o
n
SELECT
department_id, department_name
ra
Iig on-tFROM
departments;
n
7
Length
25
3. Create the EMP2 table based on the following table instance chart. Enter the syntax in the
SQL Worksheet. Then execute the statement to create the table. Confirm that the table is
created.
Column Name ID
LAST_NAME
FIRST_NAME
DEPT_ID
Key Type
Nulls/Unique
FK Table
FK Column
Data type
NUMBER
VARCHAR2
VARCHAR2
NUMBER
Length
25
25
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 2: Solutions (continued)
CREATE TABLE
(id
last_name
first_name
dept_id
emp2
NUMBER(7),
VARCHAR2(25),
VARCHAR2(25),
NUMBER(7));
DESCRIBE emp2
4. Modify the EMP2 table to allow for longer employee last names. Confirm your
modification.
a
s
a
)h
VARCHAR2(50));
s
e
a ide
u
g
DESCRIBE emp2
ta t Gu
s
e
g den
@
5. Create the EMPLOYEES2 table based on the structure
of
a SthetuEMPLOYEES table. Include
r
r
a
only the EMPLOYEE_ID, FIRST_NAME,g
LAST_NAME,
is SALARY, and
e
h
l
i
t
(
DEPARTMENT_ID columns. Name
the columns
se in your new table ID, FIRST_NAME,
ez orespectively.
l
u
LAST_NAME, SALARY, and
DEPT_ID,
nz se t
o
a G licen
r
r
a TABLE
CREATE
g
le employees2 AS
e
b
L
a
SELECT
employee_id
id, first_name, last_name, salary,
e sfer
d
department_id dept_id
o tran
g
i
- FROM employees;
I
non
ALTER TABLE emp2
MODIFY (last_name
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
ALTER TABLE employees2
g
ta t Gu
s
e
DROP COLUMN first_name;
g den
@
ra Stu
r
a
DESCRIBE employees2
leg e this
i
(
ez o us
l
t
10. In the EMPLOYEES2 table,
column as UNUSED. Confirm your
nzmarksthee DEPT_ID
o
modification by checking
of the table.
n
edescription
a G lthe
c
r
i
r
aTABLEblemployees2
e
g
ALTER
e
L
a
eSET sfUNUSED
er
(dept_id);
d
o
n
Iig on-tra
n DESCRIBE employees2
9. Drop the FIRST_NAME column from the EMPLOYEES2 table. Confirm your
modification by checking the description of the table.
11. Drop all the UNUSED columns from the EMPLOYEES2 table. Confirm your modification
by checking the description of the table.
ALTER TABLE employees2
DROP UNUSED COLUMNS;
DESCRIBE employees2
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
15. Modify the EMP2 table. Add a COMMISSION column
tuNUMBER data type,
rra sofSthe
a
precision 2, scale 2. Add a constraint to thegCOMMISSION
i column that ensures that a
e
h
l
i
t
(
commission value is greater than zero.
e
z
s
e
l
u
z e to
n
o
ALTER TABLE
G emp2
ns
e
a
c
r
ADD commission
r le li NUMBER(2,2)
a
g
CONSTRAINT
Le ferab my_emp_comm_ck CHECK (commission > 0);
e
d ns
o
g
a EMP2 and DEPT2 tables so that they cannot be restored. Verify the recycle bin.
i
-trthe
I 16.oDrop
n
n
ALTER TABLE emp2
ADD CONSTRAINT my_emp_dept_id_fk
FOREIGN KEY (dept_id) REFERENCES dept2(id);
17. Create the DEPT_NAMED_INDEX table based on the following table instance chart.
Name the index for the PRIMARY KEY column as DEPT_PK_IDX.
Column Name
Deptno
Dname
Primary Key
Yes
Data Type
Number
VARCHAR2
Length
30
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 2: Solutions (continued)
s
a
h
s)
e
a ide
2354, 2264, 13.21, 150,
u
g
ta t Gu
s
e
2355, 2289, 46.23, 200,
g den
@
ra Stu
r
a
2355, 2264, 50.00, 100,
leg e this
i
(
a) Open the lab_02_18.sql file.
ezObserve
l
usthe code snippet to create the
o
z
t
library_items_ext
etable. Then, replace <TODO1>, <TODO2>,
onexternal
s
G
n
<TODO3>, anda
<TODO4>
as
appropriate
and save the file as
e
c
r
i
r
l
lab_02_18_soln.sql.
a ble
g
e
Run the
e L script
etoracreate the external table.
f
d
s
o tran
- TABLE library_items_ext ( category_id number(12)
IigCREATE
non
, book_id number(6)
, book_price number(8,2)
, quantity
number(8)
)
ORGANIZATION EXTERNAL
(TYPE ORACLE_LOADER
DEFAULT DIRECTORY emp_dir
ACCESS PARAMETERS (RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY ',')
LOCATION ('library_items.dat')
)
REJECT LIMIT UNLIMITED;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 2: Solutions (continued)
b) Query the library_items_ext table.
SELECT * FROM library_items_ext;
19. The HR department needs a report of addresses of all departments. Create an external
table as dept_add_ext using the ORACLE_DATAPUMP access driver. The report
should show the location ID, street address, city, state or province, and country in the
output. Use a NATURAL JOIN to produce the results.
Note: The emp_dir directory is already created for this exercise.
a) Open the lab_02_19.sql file. Observe the code snippet to create the
dept_add_ext external table. Then, replace <TODO1>, <TODO2>, and <TODO3>
with appropriate code. Replace <oraxx_emp4.exp> and <oraxx<emp5.exp>
with appropriate file names. For example, if you are user ora21, your file names are
ora21_emp4.exp
and
ora21_emp5.exp.
Save
the
script
as
lab_02_19_soln.sql.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
CREATE TABLE dept_add_ext (location_id,
g den
@
street_address,
a Stu city,
r
r
a
his
legstate_province,
i
t
country_name)
(
e
ez o us
l
ORGANIZATION EXTERNAL(
nz se t
o
TYPE ORACLE_DATAPUMP
n
ra G liceemp_dir
DEFAULTarDIRECTORY
eg r('oraxx_emp4.exp','oraxx_emp5.exp'))
ble
LOCATION
L
a
e sfe
dPARALLEL
o
tran location_id, street_address, city,
-SELECT
Iig onAS
n state_province, country_name
FROM locations
NATURAL JOIN countries;
Note: When you perform the preceding step, two files oraxx_emp4.exp and
oraxx_emp5.exp are created under the default directory emp_dir.
Run the lab_02_19_soln.sql script to create the external table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 2: Solutions (continued)
20. Create the emp_books table and populate it with data. Set the primary key as deferred
and observe what happens at the end of the transaction.
a) Run the lab_02_20a.sql script to create the emp_books table. Observe that the
emp_books_pk primary key is not created as deferrable.
CREATE TABLE emp_books (book_id number,
title varchar2(20),
CONSTRAINT emp_books_pk PRIMARY KEY (book_id));
b) Run the lab_02_20b.sql script to populate data into the emp_books table.
What do you observe?
a
s
a
)h
s
INSERT INTO emp_books VALUES(300,'Change
e
a ide
u
Management');
g
ta t Gu
s
e
g den
@
The first row is inserted. But, you see the ora-00001
a Stuerror with the second row
r
r
a
insertion.
s
hiWhat
leasgdeferred.
i
t
c) Set the emp_books_pk constraint
do you observe?
(
e
z
s
e
l to u DEFERRED;
SET CONSTRAINT emp_books_pk
z
n
o nse
G
ce: ORA-02447: Cannot defer a constraint that is not
ra error
i
r
l
You see the
following
a
eg rable
deferrable.
L
de nsfe
o
tra the emp_books_pk constraint.
Iig ond)-Drop
n ALTER TABLE emp_books DROP CONSTRAINT emp_books_pk;
INSERT INTO emp_books VALUES(300,'Organizations');
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
You see that the transaction is rolled back
g
ta t Gu
s
e
g den
.
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
COMMIT;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 3: Solutions
1. Query the data dictionary to see information about the tables you
own.
SELECT table_name
FROM
user_tables;
2. Query the dictionary view to see information about all the tables that you can access.
Exclude tables that you own.
a
s
a
) hand data
3. For a specified table, create a script that reports the column names, data types,
s
e
atoenteridtheetable
types lengths, as well as whether nulls are allowed. Prompt the user
u
g
u columns.
name. Give appropriate aliases to the DATA_PRECISION and
taDATA_SCALE
G
s
t
e
Save this script in a file named lab_03_01.sql. g
n
e
@
d
ra Stu
r
a
SELECT column_name, data_type, idata_length,
leg e this
(
data_precision PRECISION,
SCALE, nullable
lez to data_scale
us
FROM
user_tab_columns z
on nse
WHERE table_name =GUPPER('&tab_name');
ce
ra
i
r
l
a
To test, run the script
eg andraenter
bleDEPARTMENTS as the table name.
L
de nsfe
o
Create
that reports the column name, constraint name, constraint type, search
-traascript
Iig4. ocondition,
n
and status for a specified table. You must join the USER_CONSTRAINTS and
n
USER_CONS_COLUMNS tables to obtain all this information. Prompt the user to enter the
table name. Save the script in a file named lab_03_04.sql.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 3: Solutions (continued)
5. Add a comment to the DEPARTMENTS table. Then query the USER_TAB_COMMENTS
view to verify that the comment is present.
COMMENT ON TABLE departments IS
'Company department information including name, code, and
location.';
SELECT COMMENTS
FROM
user_tab_comments
WHERE table_name = 'DEPARTMENTS';
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
CREATE SYNONYM emp FOR EMPLOYEES;
e
g den
SELECT *
@
ra Stu
FROM
user_synonyms;
r
a
leg e this
i
(
ez o us
l
nz se t
o
en the dept50 view for this exercise. You need to
a G toliccreate
7. Run lab_03_07.sql
r
r
anamesband
g
le definitions of all the views in your schema. Create a report that
determine
the
e
L
a
r
retrieves
the view name and text from the USER_VIEWS data
e view
einformation:
f
d
s
odictionarynview.
Iig on-tra
Note:
n The EMP_DETAILS_VIEW was created as part of your schema.
6. Create a synonym for your EMPLOYEES table. Call it EMP. Then, find the names of all
synonyms that are in your schema.
Note: You can see the complete definition of the view if you use Run Script (or press F5) in
SQL Developer. If you use Execute Statement (or press F9) in SQL Developer, scroll
horizontally in the result pane. If you use SQL*Plus to see more contents of a LONG column,
use the SET LONG n command, where n is the value of the number of characters of the
LONG column that you want to see.
SELECT
FROM
view_name, text
user_views;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 3: Solutions (continued)
8. Find the names of your sequences. Write a query in a script to display the following
information about your sequences: sequence name, maximum value, increment size, and
last number. Name the script lab_03_08.sql. Run the statement in your script.
SELECT
sequence_name, max_value, increment_by, last_number
FROM user_sequences;
Run the lab_03_09_tab.sql script as a prerequisite for exercises 9 through 11.
Alternatively, open the script file to copy the code and paste it into your SQL Worksheet. Then
execute the script. This script:
a
s
a
)sohthat they
s
Note: In Practice 2, you should have already dropped the DEPT2 and EMP2 tables
e
a ide
cannot be restored.
u
g
u
tadata tdictionary.
G
s
9. Confirm that both the DEPT2 and EMP2 tables are stored
in
the
e
g den
@
ra Stu
r
a
SELECT
table_name
leg e this
i
(
FROM
user_tables
ez o us'EMP2');
l
WHERE
table_name IN
('DEPT2',
nz se t
o
en out the constraint names and types for both the tables.
10. Query the datardictionary
a G litocfind
r
a ble
g
e
e L constraint_name,
era
SELECT
constraint_type
f
d
s
o
n
tra user_constraints
IigFROM
n
WHERE
table_name IN ('EMP2', 'DEPT2');
no
11. Query the data dictionary to display the object names and types for both the tables.
SELECT
FROM
WHERE
OR
object_name, object_type
user_objects
object_name LIKE 'EMP%'
object_name LIKE 'DEPT%';
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 3: Solutions (continued)
12. Create the SALES_DEPT table based on the following table instance chart. Name the
index for the PRIMARY KEY column as SALES_PK_IDX. Then query the data
dictionary view to find the index name, table name, and whether the index is unique.
Column Name
Team_Id
Location
Primary Key
Yes
Data Type
Number
VARCHAR2
Length
30
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 4: Solutions
1. Run the lab_04_01.sql script in the lab folder to create the SAL_HISTORY table.
2. Display the structure of the SAL_HISTORY table.
DESC sal_history
3. Run the lab_04_03.sql script in the lab folder to create the MGR_HISTORY table.
4. Display the structure of the MGR_HISTORY table.
DESC mgr_history
a
s
a
) h table.
5. Run the lab_04_05.sql script in the lab folder to create the SPECIAL_SAL
s
e
a ide
u
g
ta t Gu
s
6. Display the structure of the SPECIAL_SAL table.
e
g den
@
ra Stu
r
a
DESC special_sal
leg e this
i
(
ez o us
l
z et
nfollowing:
o
7. a) Write a query to do
the
G cens
a
r
rdetails lsuch
lias the employee ID, hire date, salary, and manager ID of those
- Retrieve
a
e
g
employees
Le ferwhose
ab employee ID is less than 125 from the EMPLOYEES table.
e
o d- tIfrathenssalary is more than $20,000, insert details such as the employee ID and salary
g
i
I on- into the SPECIAL_SAL table.
n - Insert details such as the employee ID, hire date, and salary into the
-
SAL_HISTORY table.
Insert details such as the employee ID, manager ID, and salary into the
MGR_HISTORY table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 4: Solutions (continued)
INSERT ALL
WHEN SAL > 20000 THEN
INTO special_sal VALUES (EMPID, SAL)
ELSE
INTO sal_history VALUES(EMPID,HIREDATE,SAL)
INTO mgr_history VALUES(EMPID,MGR,SAL)
SELECT employee_id EMPID, hire_date HIREDATE,
salary SAL, manager_id MGR
FROM employees
WHERE employee_id < 125;
s
a
h
s)
e
a ide
u
g
b) Display the records from the SPECIAL_SAL table.
ta t Gu
s
e
g den
@
SELECT * FROM special_sal;
ra Stu
r
a
leg e this
i
(
c) Display the records from thelSAL_HISTORY
ez o us table.
nz se t
o
en sal_history;
SELECT
a G * liFROM
c
r
r
a ble
g
e
ra from the MGR_HISTORY table.
e L stheferecords
d)dDisplay
o
n
Iig on-tra SELECT * FROM mgr_history;
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 4: Solutions (continued)
d) Display the records from the SALES_WEEK_DATA table.
SELECT * FROM SALES_WEEK_DATA;
a
s
a
)h
g) Write a query to do the following:
s
e
a onidMonday,
e
- Retrieve details such as the employee ID, week ID, salesgquantity
u
u on
ta salest G
sales quantity on Tuesday, sales quantity on Wednesday,
quantity
s
e
n
Thursday, and sales quantity on Friday from thegSALES_WEEK_DATA
table.
e
@
d
a
u
t
- Build a transformation such that eacharecord
rr retrieved
S from the
s
g
i
SALES_WEEK_DATA table is iconverted
le e into
th multiple records for the
(
z
EMP_SALES_INFO table.
le to us
z
on INSERT
se statement.
Hint: Use a G
pivoting
n
e
rra le lic
a
g
Le ALL
ab
INSERT
r
e
e
f
o d traINTO
ns emp_sales_info VALUES (id, week_id, QTY_MON)
g
i
I on- INTO emp_sales_info VALUES (id, week_id, QTY_TUE)
n
INTO emp_sales_info VALUES (id, week_id, QTY_WED)
INTO emp_sales_info VALUES (id, week_id, QTY_THUR)
INTO emp_sales_info VALUES (id, week_id, QTY_FRI)
SELECT ID, week_id, QTY_MON, QTY_TUE, QTY_WED,
QTY_THUR,QTY_FRI FROM sales_week_data;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 4: Solutions (continued)
9. You have the data of past employees stored in a flat file called emp.data. You want to
store the names and email IDs of all employees past and present in a table. To do this,
first create an external table called EMP_DATA using the emp.dat source file in the
emp_dir directory. You can use the script in lab_04_09.sql to do this.
CREATE TABLE emp_data
(first_name VARCHAR2(20)
,last_name
VARCHAR2(20)
, email
VARCHAR2(30)
)
ORGANIZATION EXTERNAL
(
TYPE oracle_loader
DEFAULT DIRECTORY emp_dir
ACCESS PARAMETERS
(
RECORDS DELIMITED BY NEWLINE CHARACTERSET US7ASCII
NOBADFILE
NOLOGFILE
FIELDS
( first_name POSITION ( 1:20) CHAR
, last_name POSITION (22:41) CHAR
, email
POSITION (43:72) CHAR )
)
LOCATION ('emp.dat') ) ;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
L the flab_04_10.sql
10. Next,
run
script to create the EMP_HIST table.
ra
e
e
d
s
oa) Increase
n the size of the email column to 45.
g
a
i
r
t
I
non
b) Merge the data in the EMP_DATA table created in the last lab into the data in the
EMP_HIST table. Assume that the data in the external EMP_DATA table is the most
up-to-date. If a row in the EMP_DATA table matches the EMP_HIST table, update the
email column of the EMP_HIST table to match the EMP_DATA table row. If a row in
the EMP_DATA table does not match, insert it into the EMP_HIST table. Rows are
considered matching when the employees first and last names are identical.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 4: Solutions (continued)
a
s
a
)h
s
e
c) Retrieve the rows from EMP_HIST after the merge.
a ide
u
g
ta t Gu
s
SELECT * FROM emp_hist;
e
g den
@
ra script.SIntuthe EMP3 table, change the
r
11. Create the EMP3 table using the lab_04_11.sql
a
g change.
hisNext, change the department for
leyour
department for Kochhar to 60 and commit
i
t
(
e
Kochhar to 50 and commit your lchange.
ez oTrack
us the changes to Kochhar using the Row
z
t
Versions feature.
on nse
G
ce
ra
i
r
l
a
le department_id = 60
UPDATE
egemp3rabSET
L
e last_name
= Kochhar;
fe
dWHERE
s
o
n
COMMIT;
-tra emp3 SET department_id = 50
Iig onUPDATE
n
WHERE last_name = Kochhar;
COMMIT;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 5: Solutions
1. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.
ALTER SESSION SET NLS_DATE_FORMAT =
'DD-MON-YYYY HH24:MI:SS';
2. a. Write queries to display the time zone offsets (TZ_OFFSET) for the following
time zones: US/Pacific-New, Singapore, and Egypt.
US/Pacific-New
SELECT TZ_OFFSET ('US/Pacific-New') from dual;
Singapore
SELECT TZ_OFFSET ('Singapore') from dual;
Egypt
SELECT TZ_OFFSET ('Egypt') from dual;
a
s
a
)h
s
e
a ide
u
g
u
ttoathe time
G
s
b. Alter the session to set the TIME_ZONE parameter value
zone offset of
t
e
g den
US/Pacific-New.
@
ra Stu
r
a
is
leg e =th'-7:00';
i
ALTER SESSION SET TIME_ZONE
(
ez o us
l
t
nz sCURRENT_TIMESTAMP,
e
o
c. Display the CURRENT_DATE,
and LOCALTIMESTAMP
G cen
a
r
for this session.
r le li
a
g
Note:
The
e output
b may be different based on the date when the command is executed.
L
a
r
fe CURRENT_DATE, CURRENT_TIMESTAMP,
de nSELECT
s
o
Iig on-tra LOCALTIMESTAMP FROM DUAL;
n
d. Alter the session to set the TIME_ZONE parameter value to the time zone offset of
Singapore.
ALTER SESSION SET TIME_ZONE = '+8:00';
e. Display the CURRENT_DATE, CURRENT_TIMESTAMP, LOCALTIMESTAMP for
this session.
Note: The output might be different, based on the date when the command is
executed.
SELECT CURRENT_DATE, CURRENT_TIMESTAMP,
LOCALTIMESTAMP FROM DUAL;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 5: Solutions (continued)
Note: Observe in the preceding practice that CURRENT_DATE,
CURRENT_TIMESTAMP, and LOCALTIMESTAMP are all sensitive to the session time
zone.
3. Write a query to display DBTIMEZONE and SESSIONTIMEZONE.
SELECT DBTIMEZONE,SESSIONTIMEZONE
FROM DUAL;
4. Write a query to extract YEAR from the HIRE_DATE column of the EMPLOYEES table
for those employees who work in department 80.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
5. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.
g den
@
ra Stu
r
a
ALTER SESSION SET NLS_DATE_FORMAT
leg e this = 'DD-MON-YYYY';
i
(
ez o us
l
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 5: Solutions (continued)
7. Create a query to retrieve last names from the EMPLOYEES table and calculate the review
status. If the year hired was 1998, display Needs Review for the review status;
otherwise, display not this year! Name the review status column Review. Sort the
results by the HIRE_DATE column.
Hint: Use a CASE expression with the EXTRACT function to calculate the review status.
SELECT e.last_name
(CASE extract(year from e.hire_date)
WHEN 1998 THEN 'Needs Review'
ELSE 'not this year!'
END )
AS "Review "
FROM
employees e
ORDER BY e.hire_date;
a
s
a
h
)each
s
8. Create a query to print the last names and the number of years of service
for
e
a 5 years
e of
u
employee. If the employee has been employed five or more years,
print
d
i
g
u
ta printt G
s
service. If the employee has been employed 10 or more
years,
10 years of
e
n 15 years of
g deprint
service. If the employee has been employed 15 or
more years,
@
u year! Sort the
tnext
ra maybe
r
service. If none of these conditions match,aprint
S
his table.
letheg EMPLOYEES
results by the HIRE_DATE column. Use
i
t
(
e
z
Hint: Use CASE expressions and
eTO_YMINTERVAL.
l
us
o
z
t
on nse
G
ce hire_date, sysdate,
rae.last_name,
i
r
l
SELECT
a
eg ra(CASE
ble
L
de nsfe WHEN (sysdate -TO_YMINTERVAL('15-0'))>=
o
hire_date THEN
'15 years of service'
Iig on-tra
n
WHEN (sysdate -TO_YMINTERVAL('10-0'))>=
hire_date
THEN '10 years of service'
WHEN (sysdate - TO_YMINTERVAL('5-0'))>=
hire_date
THEN '5 years of service'
ELSE 'maybe next year!'
END) AS "Awards"
FROM
employees e;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 6: Solutions
1. Write a query to display the last name, department number, and salary of any employee
whose department number and salary match the department number and salary of any
employee who earns a commission.
SELECT last_name, department_id, salary
FROM
employees
WHERE (salary, department_id) IN
(SELECT salary, department_id
FROM
employees
WHERE
commission_pct IS NOT NULL);
2. Display the last name, department name, and salary of any employee whose salary and
commission match the salary and commission of any employee located in location
ID1700.
a
s
a
)h
s
e
SELECT e.last_name, d.department_name, e.salary
a ide
u
FROM
employees e, departments d
g
ta t Gu
s
WHERE e.department_id = d.department_id
e
g deINn
AND
(salary, NVL(commission_pct,0))
@
tu
raNVL(commission_pct,0)
r
(SELECT salary,
S
a
is departments d
FROM
employees
leg e the,
i
(
z e.department_id
WHERE
= d.department_id
s
e
l
u
o
= 1700);
z ed.location_id
t
nAND
o
s
G cen
a
r
r
li last name, hire date, and salary for all employees who have
3. Create a query
to display
the
a
e
g
l
the same
and
Lesalary
abcommission as Kochhar.
r
e
e
f
d Donnot
s display Kochhar in the result set.
oNote:
g
a
i
r
I on-t
SELECT last_name, hire_date, salary
n
FROM
WHERE
employees
(salary, NVL(commission_pct,0)) IN
(SELECT salary, NVL(commission_pct,0)
FROM
employees
WHERE last_name = 'Kochhar')
AND last_name != 'Kochhar';
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 6: Solutions (continued)
4. Create a query to display the employees who earn a salary that is higher than the salary of
all the sales managers (JOB_ID = 'SA_MAN'). Sort the results on salary from the
highest to the lowest.
SELECT last_name, job_id, salary
FROM
employees
WHERE salary > ALL
(SELECT salary
FROM
employees
WHERE job_id = 'SA_MAN')
ORDER BY salary DESC;
5. Display details such as the employee ID, last name, and department ID of those
employees who live in cities the names of which begin with T.
a
s
a
SELECT employee_id, last_name, department_id s) h
e e
a
FROM
employees
u
ag Guid
t
WHERE department_id IN (SELECT department_id
s
ge dent
FROM @
departments
tu
ra location_id
r
WHERE
IN
S
a
s
g
i
(ile se th(SELECT location_id
z
le to u
FROM locations
z
n
WHERE city LIKE 'T%'));
o nse
G
e
rra le lic
a
g
6. Write aLquery
employees who earn more than the average salary in their
e torfind
aball
e
e
departments.
Display
last
name, salary, department ID, and the average salary for the
f
d ns
o
department.
Sort
by
average
salary. Use aliases for the columns retrieved by the query as
a
r
t
Iig oshown
n n in the sample output.
SELECT e.last_name ename, e.salary salary,
e.department_id deptno, AVG(a.salary) dept_avg
FROM
employees e, employees a
WHERE e.department_id = a.department_id
AND
e.salary > (SELECT AVG(salary)
FROM
employees
WHERE department_id = e.department_id )
GROUP BY e.last_name, e.salary, e.department_id
ORDER BY AVG(a.salary);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 6: Solutions (continued)
7. Find all employees who are not supervisors.
a. First, do this by using the NOT EXISTS operator.
SELECT outer.last_name
FROM
employees outer
WHERE NOT EXISTS (SELECT 'X'
FROM employees inner
WHERE inner.manager_id =
outer.employee_id);
b. Can this be done by using the NOT IN operator? How, or why not?
a
s
a
)h
s
SELECT outer.last_name
e
a ide
u
FROM
employees outer
g
ta t Gu
s
WHERE outer.employee_id
e
g den
@
NOT IN (SELECT inner.manager_id
ra Stu
r
a
FROM
employees inner);
leg e this
i
(
z
eone.
l
us picks up a NULL value, so the entire
This alternative solution is not a good
The
subquery
o
z
t
on is nthatseall conditions that compare a NULL value result in
query returns no rows. TheG
reason
NULL. Whenever NULL
celikely to be part of the value set, do not use NOT IN as a
ravalueslare
i
r
a
le
substitute for NOT
eg EXISTS.
b
L
a
e sfer
d
o traaquery
n to display the last names of the employees who earn less than the average
Iig8. oWrite
n in their departments.
n salary
SELECT last_name
FROM
employees outer
WHERE outer.salary < (SELECT AVG(inner.salary)
FROM employees inner
WHERE inner.department_id
= outer.department_id);
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 6: Solutions (continued)
9. Write a query to display the last names of employees who have one or more coworkers in
their departments with later hire dates but higher salaries.
SELECT last_name
FROM
employees outer
WHERE EXISTS (SELECT 'X'
FROM employees inner
WHERE inner.department_id =
outer.department_id
AND inner.hire_date > outer.hire_date
AND inner.salary > outer.salary);
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
SELECT employee_id, last_name,
g den
@
(SELECT department_name
ra Stu
r
a
FROM departments le
dg
his
i
t
(
e
WHERE
e.department_id
ez o us =
l
d.department_id
nz se t ) department
o
G e cen
FROM employees
a
r
r
li
ORDERgBY
department;
a
e
l
Le ferab
e
d a query
11.
Write
s to display the department names of those departments whose total salary
ocost
n
g
a
i
r
-ist above one-eighth (1/8) of the total salary cost of the whole company. Use the
I oWITH
n
clause to write this query. Name the query SUMMARY.
n
10. Write a query to display the employee ID, last names, and department names of all
employees.
Note: Use a scalar subquery to retrieve the department name in the SELECT statement.
WITH
summary AS (
SELECT d.department_name, SUM(e.salary) AS dept_total
FROM employees e, departments d
WHERE e.department_id = d.department_id
GROUP BY d.department_name)
SELECT department_name, dept_total
FROM summary
WHERE dept_total > ( SELECT SUM(dept_total) * 1/8
FROM summary )
ORDER BY dept_total DESC;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 7: Solutions
1. Write a query to search the EMPLOYEES table for all employees whose first names start
with Ki or Ko.
SELECT first_name, last_name
FROM employees
WHERE REGEXP_LIKE (last_name, '^K(i|o).');
2. Create a query that removes the spaces in the STREET_ADDRESS column of the
LOCATIONS table in the display. Use Street Address as the column heading.
SELECT regexp_replace (street_address, ' ', '') AS "Street
Address"
FROM locations;
a
s
a
)h
s
e
a ide
u
g
3. Create a query that displays St replaced by Street in the STREET_ADDRESS
ta t Gu column of
s
e
the LOCATIONS table. Be careful that you do not affectgany rows that
n already have
e
@
d
Street in them. Display only those rows, whichra
are affected.
tu
r
S
a
leg e this 'St$', 'Street')
i
SELECT regexp_replace (street_address,
(
ez o us
FROM locations
l
t
WHERE regexp_like
'St');
nz(street_address,
e
o
s
G
n
ce
ra
i
r
l
a
eg rable
L
fe table and add a check constraint to the p_number column to enforce
de a contacts
4. oCreate
s
n
tra format mask to ensure that phone numbers are entered into the database in
-following
Iig othe
n
following standard format: (XXX) XXX-XXXX. The table should have the following
n the
columns:
l_name varchar2(30)
p_number varchar2 (30)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Practice 7: Solutions (continued)
5. Run the lab_07_05.sql SQL script to insert the following seven phone numbers into
the contacts table. Which numbers are added?
Only the first two INSERT statements use a format that conforms to the
c_contacts_pnf constraint; the remaining statements generate CHECK
constraint errors.
6. Write a query to find the number of occurrences of the DNA pattern ctc in the string
gtctcgtctcgttctgtctgtcgttctg. Use the alias Count_DNA. Ignore casesensitivity.
SELECT REGEXP_COUNT('gtctcgtctcgttctgtctgtcgttctg','ctc')
AS Count_DNA
FROM dual;
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Table Descriptions
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Schema Description
Overall Description
The Oracle database sample schemas portray a sample company that operates worldwide to fill orders
for several different products. The company has three divisions:
Human Resources: Tracks information about the employees and facilities
Order Entry: Tracks product inventories and sales through various channels
Sales History: Tracks business statistics to facilitate business decisions
Each of these divisions is represented by a schema. In this course, you have access to the objects in
all the schemas. However, the emphasis of the examples, demonstrations, and practices is on the
Human Resources (HR) schema.
All scripts necessary to create the sample schemas reside in the
$ORACLE_HOME/demo/schema/ folder.
Human Resources (HR)
This is the schema that is used in this course. In the Human Resource (HR) records, each employee
a
s
a
has an identification number, email address, job identification code, salary, and manager.
) h Some
s
e
employees earn commissions in addition to their salary.
a ide
u
g
The company also tracks information about jobs within the organization.
jobuhas an
ta Each
G
s
t
e
identification code, job title, and a minimum and maximum salary
for
n the job. Some employees
g range
e
@
d
have been with the company for a long time and have held
tupositions within the company.
radifferent
r
S
a
When an employee resigns, the duration the employee
was
working
g this for, the job identification
e
l
i
(
number, and the department are recorded. z
se
le
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 2
Cas Training
The HR Entity Relationship Diagram
HR
DEPARTMENTS
department_id
department_name
manager_id
location_id
JOB_HISTORY
employee_id
start_date
end_date
job_id
department_id
LOCATIONS
location_id
street_address
postal_code
city
state_province
country_id
EMPLOYEES
employee_id
first_name
last_name
email
phone_number
hire_date
job_id
salary
commission_pct
manager_id
department_id
COUNTRIES
country_id
country_name
region_id
s
a
h
s)
e
JOBS
a ide
u
job_id
g
ta t Gu
s
job_title
e
g den REGIONS
min_salary
@
region_id
max_salary
ra Stu
r
a
region_name
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 3
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE countries
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 4
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE departments
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 5
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE employees
s
a
h
s)
e
a ide
u
g
ta t Gu
SELECT * FROM employees;
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 6
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE job_history
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 7
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE jobs
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 8
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE locations
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 9
Cas Training
The Human Resources (HR) Table Descriptions
DESCRIBE regions
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II B - 10
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this appendix, you should be able to do the
following:
List the key features of Oracle SQL Developer
Install Oracle SQL Developer 1.2.1
Identify menu items of Oracle SQL Developer
Create a database connection
Manage database objects
s
a
h
Use SQL Worksheet
s)
e
a ide
u
Save and run SQL scripts
g
ta t Gu
s
e
g den
Create and save reports
@
tu
ra S1.5.3
r
Install and use Oracle SQL Developer
a
g
is
(ile se th
z
le to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
de nsfe
Objectives
o
trayou are introduced to the graphical tool called SQL Developer. You learn how
igappendix,
InIthis
n
no Developer for your database development tasks. You learn how to use SQL
to use SQL
Worksheet to execute SQL statements and SQL scripts.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 2
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
SQL
ez Developer
l
us
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e
fDeveloper?
de SQL
s
What Is Oracle
o
n
tra is a free graphical tool designed to improve your productivity and
IigSQL
Oracle
Developer
n
no
simplify
the development of everyday database tasks. With just a few clicks, you can easily
create and debug stored procedures, test SQL statements, and view optimizer plans.
SQL Developer, the visual tool for database development, simplifies the following tasks:
Browsing and managing database objects
Executing SQL statements and scripts
Editing and debugging PL/SQL statements
Creating reports
You can connect to any target Oracle database schema by using standard Oracle database
authentication. When connected, you can perform operations on objects in the database.
Note: The SQL Developer 1.2 release is called the Migration release because it tightly
integrates with Developer Migration Workbench that provides users with a single point to
browse database objects and data in third-party databases, and to migrate from these databases to
Oracle. You can also connect to schemas for selected third-party (non-Oracle) databases such as
MySQL, Microsoft SQL Server, and Microsoft Access, and you can view metadata and data in
these databases.
Additionally, SQL Developer includes support for Oracle Application Express 3.0.1 (Oracle
APEX).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 3
Cas Training
Developed in Java
Supports Windows, Linux, and Mac OS X platforms
Default connectivity by using the JDBC Thin driver
Does not require an installer
Unzip the downloaded SQL Developer kit and double-click
sqldeveloper.exe to start SQL Developer.
a ide
http://www.oracle.com/technology/products/database/sql_de
u
g
u
a
veloper/index.html
tG
est
g den
@
Needs JDK 1.5 installed on your
tuthat can be
rasystem
r
S
a
downloaded from the following
his
leg elink:
i
t
(
ez o us
http://java.sun.com/javase/downloads/index_jdk5.jsp
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e Lof SQL
erDeveloper
f
d
s
Specifications
o tran
IigSQL
Oracle
Developer
is developed in Java leveraging the Oracle JDeveloper integrated
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 4
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LDeveloper
era
f
d
s
Installing
SQL
o tran
IigSQL
Oracle
does not require an installer. To install SQL Developer, you need an
nDeveloper
o
n
unzip tool.
To install SQL Developer, perform the following steps:
1. Create a folder as <local drive>:\SQL Developer.
2. Download the SQL Developer kit from
http://www.oracle.com/technology/products/database/sql_developer/index.html.
3. Unzip the downloaded SQL Developer kit into the folder created in step 1.
To start SQL Developer, go to <local drive>:\SQL Developer, and double-click
sqldeveloper.exe.
Notes: SQL Developer 1.2 is already installed on the classroom machine. The installation kit for
SQL Developer 1.5.3 is also on the classroom machine. You may use either version of SQL
Developer in this course. Instructions for installing SQL Developer version 1.5.3 are available at
the end of this appendix.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 5
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L1.2sInterface
era
f
d
SQL Developer
go -tra1.2n has two main navigation tabs:
SQL
IiDeveloper
non
Connections
Navigator: By using this, you can browse database objects and users to
Cas Training
sa
rr s S
a
g
le e thi
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfeConnection
Creatingoa d
Database
n
ig n-tisraa SQL Developer object that specifies the necessary information for connecting
A Iconnection
no database as a specific user of that database. To use SQL Developer, you must have
to a specific
at least one database connection, which may be existing, created, or imported.
You can create and test connections for multiple databases and for multiple schemas.
By default, the tnsnames.ora file is located in the $ORACLE_HOME/network/admin
directory, but it can also be in the directory specified by the TNS_ADMIN environment variable
or registry value. When you start SQL Developer and display the Database Connections dialog
box, SQL Developer automatically imports any connections defined in the tnsnames.ora file
on your system.
Note: On Windows, if the tnsnames.ora file exists but its connections are not being used by
SQL Developer, define TNS_ADMIN as a system environment variable.
You can export connections to an XML file so that you can reuse it later.
You can create additional connections as different users to the same database or to connect to the
different databases.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfeConnection
Creatingoa d
Database
(continued)
n
g
a
i
r
-t
ToI
create andatabase
connection, perform the following steps:
o
n
1. On the Connections tabbed page, right-click Connections and select New Connection.
2. In the New/Select Database Connection window, enter the connection name. Enter the
username and password of the schema that you want to connect to.
1. From the Role drop-down box, you can select either default or SYSDBA (you choose
SYSDBA for the sys user or any user with database administrator privileges).
2. You can select the connection type as:
Basic: In this type, enter hostname and SID for the database you want to
connect to. Port is already set to 1521. Or you can also choose to enter the Service
name directly if you use a remote database connection.
TNS: You can select any one of the database aliases imported from the
tnsnames.ora file.
Advanced: You can define a custom Java Database Connectivity (JDBC)
URL to connect to the database.
3. Click Test to ensure that the connection has been set correctly.
4. Click Connect.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 8
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 9
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfObjects
era
d
Browsing
Database
o tran
Iigyouocreate
After
n- a database connection, you can use the Connections Navigator to browse
n
through many objects in a database schema including Tables, Views, Indexes, Packages,
Procedures, Triggers, and Types.
SQL Developer uses the left side for navigation to find and select objects, and the right side to
display information about the selected objects. You can customize many aspects of the
appearance of SQL Developer by setting preferences.
You can see the definition of the objects broken into tabs of information that is pulled out of the
data dictionary. For example, if you select a table in the Navigator, the details about columns,
constraints, grants, statistics, triggers, and so on are displayed on an easy-to-read tabbed page.
If you want to see the definition of the EMPLOYEES table as shown in the slide, perform the
following steps:
1. Expand the Connections node in the Connections Navigator.
2. Expand Tables.
3. Click EMPLOYEES. By default, the Columns tab is selected. It shows the column
description of the table. Using the Data tab, you can view the table data and also enter new
rows, update data, and commit these changes to the database.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 10
Cas Training
gu uide
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sObject
era
f
Creatingoa d
Schema
n
g -trasupports
IiDeveloper
SQL
the creation of any schema object by executing a SQL statement in
n
o
n
SQL Worksheet. Alternatively, you can create objects using the context menus. When created,
you can edit the objects using an edit dialog box or one of the many context-sensitive menus.
As new objects are created or existing objects are edited, the DDL for those adjustments is
available for review. An Export DDL option is available if you want to create the full DDL for
one or more objects in the schema.
The slide shows how to create a table using the context menu. To open a dialog box for creating
a new table, right-click Tables and select New Table. The dialog boxes to create and edit
database objects have multiple tabs, each reflecting a logical grouping of properties for that type
of object.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 11
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
a
e L sferExample
Creatingoa d
New Table:
andialog box, if you do not select the Advanced check box, you can create a
r
t
igCreate
InIthe
Table
non by specifying columns and some frequently used features.
table quickly
If you select the Advanced check box, the Create Table dialog box changes to one with multiple
options, in which you can specify an extended set of features while you create the table.
The example in the slide shows how to create the DEPENDENTS table by selecting the
Advanced check box.
To create a new table, perform the following steps:
1. In the Connections Navigator, right-click Tables.
2. Select Create TABLE.
3. In the Create Table dialog box, select Advanced.
4. Specify column information.
5. Click OK.
Although it is not required, you should also specify a primary key by using the Primary Key tab
in the dialog box. Sometimes, you may want to edit the table that you have created; to do so,
right-click the table in the Connections Navigator and select Edit.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 12
Cas Training
a
s
a
)h
s
Click the Open
SQL
e
aicon. ide
Worksheet
u
g
ta t Gu
s
e
g den
@
ra Stu
r
Select SQL
a
Worksheet from the
leg e this
i
(
Tools menu, or
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LWorksheet
era
f
d
s
Using the
SQL
o tran
- to a database, a SQL Worksheet window for that connection automatically
Iigyouonconnect
When
n
opens. You can use the SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus
statements. The SQL Worksheet supports SQL*Plus statements to a certain extent. SQL*Plus
statements that are not supported by the SQL Worksheet are ignored and not passed to the
database.
You can specify actions that can be processed by the database connection associated with the
worksheet, such as:
Creating a table
Inserting data
Creating and editing a trigger
Selecting data from a table
Saving the selected data to a file
You can display a SQL Worksheet by using one of the following:
Select Tools > SQL Worksheet.
Click the Open SQL Worksheet icon.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 13
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LWorksheet
era (continued)
f
d
s
Using the
SQL
n
igo want-trtoause
Imay
You
the shortcut keys or icons to perform certain tasks such as executing a SQL
n
o
n
statement, running a script, and viewing the history of SQL statements that you have executed.
You can use the SQL Worksheet toolbar that contains icons to perform the following tasks:
1. Execute Statement: Executes the statement where the cursor is located in the Enter SQL
Statement box. You can use bind variables in the SQL statements, but not substitution
variables.
2. Run Script: Executes all statements in the Enter SQL Statement box by using the Script
Runner. You can use substitution variables in the SQL statements, but not bind variables.
3. Commit: Writes any changes to the database and ends the transaction
4. Rollback: Discards any changes to the database, without writing them to the database, and
ends the transaction
5. Cancel: Stops the execution of any statements currently being executed
6. SQL History: Displays a dialog box with information about SQL statements that you have
executed
7. Execute Explain Plan: Generates the execution plan, which you can see by clicking the
Explain tab
8. Autotrace: Generates trace information for the statement
9. Clear: Erases the statement or statements in the Enter SQL Statement box
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 14
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
tu are
ra Results
r
S
a
is here.
leg e thshown
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LWorksheet
era (continued)
f
d
s
Using the
SQL
o tran
- to a database, a SQL Worksheet window for that connection automatically
Iigyouonconnect
When
n
opens. You can use the SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus
Enter SQL
statements.
statements. All SQL and PL/SQL commands are supported as they are passed directly from the
SQL Worksheet to the Oracle database. SQL*Plus commands used in the SQL Developer have
to be interpreted by the SQL Worksheet before being passed to the database.
The SQL Worksheet currently supports a number of SQL*Plus commands. Commands not
supported by the SQL Worksheet are ignored and are not sent to the Oracle database. Through
the SQL Worksheet, you can execute SQL statements and some of the SQL*Plus commands.
You can display a SQL Worksheet by using any of the following two options:
Select Tools > SQL Worksheet.
Click the Open SQL Worksheet icon.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 15
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
View the results on
g den
@
the Script Output
ra Stu
r
tabbed page.
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LStatements
era
f
d
s
Executing
SQL
o tran
igSQLnWorksheet,
InIthe
you can use the Enter SQL Statement box to enter single or multiple
o
n
SQL statements. For a single statement, the semicolon at the end is optional.
When you enter the statement, the SQL keywords are automatically highlighted. To execute a
SQL statement, ensure that your cursor is within the statement and click the Execute Statement
icon. Alternatively, you can press the F9 key.
To execute multiple SQL statements and see the results, click the Run Script icon. Alternatively,
you can press the F5 key.
In the example in the slide, because there are multiple SQL statements, the first statement is
terminated with a semicolon. The cursor is in the first statement, and therefore, when the
statement is executed, results corresponding to the first statement are displayed in the Results
box.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 16
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eScripts
d
Saving SQL
o trans
g
i
Ican osave
You
n-your SQL statements from the SQL Worksheet into a text file. To save the
n
contents of the Enter SQL Statement box, follow these steps:
The contents of the
saved file are visible
and editable in your
SQL Worksheet
window.
1. Click the Save icon or use the File > Save menu item.
2. In the Windows Save dialog box, enter a file name and the location where you want the
file saved.
3. Click Save.
After you save the contents to a file, the Enter SQL Statement window displays a tabbed page of
your file contents. You can have multiple files open at the same time. Each file displays as a
tabbed page.
Script Pathing
You can select a default path to look for scripts and to save scripts. Under Tools > Preferences >
Database > Worksheet Parameters, enter a value in the Select default path to look for scripts
field.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 17
Cas Training
a
s
a
)h
s
e
a ide
u
g
Click Open.
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Script
eraFiles: Method 1
f
d
s
Executing
Saved
n
igo -trafile
ToI
open a script
and display the code in the SQL Worksheet area, perform the following:
n
o
n
1. Right-click in the SQL Worksheet area, and select Open File from the menu. The Open
Select (or navigate
to) the script file that
you want to open.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 18
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Script
eraFiles: Method 2
f
d
s
Executing
Saved
an script, perform the following:
igo -trSQL
ToI
run a saved
n
nothe
1. Use
@ command, followed by the location, and name of the file you want to run, in the
The output from the
script is displayed on
the Script Output
tabbed page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 19
Cas Training
F9
F5
F5
a
s
a
F9
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LStatements
era
f
d
s
Executing
SQL
igo -intrathenslide shows the difference in output for the same query when the [F9] key or
Iexample
The
on
ExecutenStatement is used versus the output when [F5] or Run Script is used.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 20
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
After
ra Stu
r
a
formatting
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LSQLsfCode
era
d
Formatting
the
n
igo want-trtoabeautify
Imay
You
the indentation, spacing, capitalization, and line separation of the
n
o
n
SQL code. SQL Developer has a feature for formatting SQL code.
To format the SQL code, right-click in the statement area, and select Format SQL.
In the example in the slide, before formatting, the SQL code has the keywords not capitalized
and the statement not properly indented. After formatting, the SQL code is beautified with the
keywords capitalized and the statement properly indented.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 21
Cas Training
Using Snippets
Snippets are code fragments that may be just syntax or
examples.
When you place your cursor here,
it shows the Snippets window.
From the drop-down list, you can
select the functions category that
you want.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Using Snippets
n
igo want-trtoause
Imay
You
certain code fragments when you use the SQL Worksheet or create or edit
n
o
n
a PL/SQL function or procedure. SQL Developer has the feature called Snippets. Snippets are
code fragments such as SQL functions, Optimizer hints, and miscellaneous PL/SQL
programming techniques. You can drag snippets into the Editor window.
To display Snippets, select View > Snippets.
The Snippets window is displayed at the right side. You can use the drop-down list to select a
group. A Snippets button is placed in the right window margin, so that you can display the
Snippets window if it becomes hidden.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 22
Cas Training
Inserting a
snippet
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Example
era
f
d
s
Using Snippets:
igo Snippet
traninto your code in a SQL Worksheet or in a PL/SQL function or procedure,
ToI
insert a n
o
drag thensnippet from the Snippets window into the desired place in your code. Then you can
Editing the
snippet
edit the syntax so that the SQL function is valid in the current context. To see a brief description
of a SQL function in a tool tip, place the cursor over the function name.
The example in the slide shows that CONCAT(char1, char2)is dragged from the Character
Functions group in the Snippets window. Then the CONCAT function syntax is edited and the
rest of the statement is added as in the following:
SELECT CONCAT(first_name, last_name)
FROM employees;
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 23
Cas Training
Using SQL*Plus
a
s
a
) hthe
s
e
Provide
a idof
ethe
u
location
g
u
ta sqlplus.exe
G
s
t
e
g den file only the
@
ra Stu first time you
r
a
leg e this
i
(
invoke
z
s
e
l
u
SQL*Plus.
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Using SQL*Plus
an supports most of the SQL*Plus statements. SQL*Plus statements must be
igo Worksheet
r
t
ISQL
The
nonby the SQL Worksheet before being passed to the database; any SQL*Plus
interpreted
statements that are not supported by the SQL Worksheet are ignored and not passed to the
database. To display the SQL*Plus command window, from the Tools menu, select SQL*Plus.
To use this feature, the system on which you use SQL Developer must have an Oracle home
directory or folder, with a SQL*Plus executable under that location. If the location of the
SQL*Plus executable is not already stored in your SQL Developer preferences, you are asked to
specify its location.
For example, some of the SQL*Plus statements that are not supported by SQL Worksheet are:
append
archive
attribute
break
For the complete list of SQL*Plus statements that are either supported or not supported by SQL
Worksheet, refer to the SQL*Plus Statements Supported and Not Supported in SQL Worksheet
topic in the SQL Developer online Help.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 24
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sferaand Functions
d
Debugging
Procedures
o tran
ig Developer,
InISQL
n- you can debug PL/SQL procedures and functions. Using the Debug menu
o
n
options, you can perform the following debugging tasks:
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 25
Cas Training
Database Reporting
SQL Developer provides a number of predefined reports about
the database and its objects.
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Database
Reporting
n
go -traprovides
IiDeveloper
SQL
many reports about the database and its objects. These reports can be
n
o
n
grouped into the following categories:
About Your Database reports
Database Administration reports
Table reports
PL/SQL reports
Security reports
XML reports
Jobs reports
Streams reports
All Objects reports
Data Dictionary reports
User-Defined reports
To display reports, click the Reports tab at the left side of the window. Individual reports are
displayed in tabbed panes at the right side of the window; and for each report, you can select
(using a drop-down list) the database connection for which to display the report. For reports
about objects, the objects shown are only those visible to the database user associated with the
selected database connection, and the rows are usually ordered by Owner. You can also create
your own user-defined reports.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 26
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
g thinisfolders.
lereports
Organize
i
(
e
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sferaReport
Creatingoa d
User-Defined
tran are reports created by SQL Developer users. To create a user-defined
Iig on-reports
User-defined
report, n
perform the following steps:
1. Right-click the User Defined Reports node under Reports, and select Add Report.
2. In the Create Report Dialog box, specify the report name and the SQL query to retrieve
information for the report. Then, click Apply.
In the example in the slide, the report name is specified as emp_sal. An optional description is
provided indicating that the report contains details of employees with salary >= 10000.
The complete SQL statement for retrieving the information to be displayed in the user-defined
report is specified in the SQL box. You can also include an optional tool tip to be displayed
when the cursor stays briefly over the report name in the Reports navigator display.
You can organize user-defined reports in folders, and you can create a hierarchy of folders and
subfolders. To create a folder for user-defined reports, right-click the User Defined Reports node
or any folder name under that node and select Add Folder. Information about user-defined
reports, including any folders for these reports, is stored in a file named UserReports.xml
under the directory for user-specific information.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 27
Cas Training
Shortcuts to
frequently used tools
1
2
a
s
a
)h
s
e
a ide
u
g
Links to popular
ta t Gu
s
e
search engines and
g den
@
discussion forums
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e Land
era Tools
f
d
s
Search Engines
External
igo -tran of the SQL developers, SQL Developer has added quick links to
ToI
enhancenproductivity
o
popularnsearch engines and discussion forums such as AskTom, Google, and so on. Also, you
have shortcut icons to some of the frequently used tools such as Notepad, Microsoft Word, and
Dreamweaver, available to you.
You can add external tools to the existing list or even delete shortcuts to tools that you do not
use frequently. To do so, perform the following:
1. From the Tools menu, select External Tools.
2. In the External Tools dialog box, select New to add new tools. Select Delete to remove any
tool from the list.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 28
Cas Training
Setting Preferences
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Setting Preferences
anmany aspects of the SQL Developer interface and environment by modifying
igocustomize
r
t
Ican
You
non preferences according to your preferences and needs. To modify SQL Developer
SQL Developer
preferences, select Tools, then Preferences.
The preferences are grouped into the following categories:
Environment
Accelerators (Keyboard shortcuts)
Code Editors
Database
Debugger
Documentation
Extensions
File Types
Migration
PL/SQL Compilers
PL/SQL Debugger, and so on.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 29
Cas Training
gu uid
a
t
It connects to Oracle Database versione9.2.0.1
G later.
s nt and
g
e
@ tudlink:
It is freely downloadable from the
afollowing
r
r
S
a
s
g
i
e
http://www.oracle.com/technology/products/database/sql_de
h
l
(i se t
veloper/index.html lez
u
o
z
t
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
feDeveloper 1.5.3
de ofnSQL
s
Specifications
o
g -tra1.5.3 is also available, as it is the latest version of the product that was available
IiDeveloper
SQL
nonof the release of this of course
at the time
Like version 1.2, SQL Developer 1.5.3 is developed in Java leveraging the Oracle JDeveloper
integrated development environment (IDE). Therefore, it is a cross-platform tool. The tool runs
on Windows, Linux, and Mac operating system (OS) X platforms. You can install SQL
Developer on the Database Server and connect remotely from your desktop, thus avoiding
client/server network traffic.
Default connectivity to the database is through the Java Database Connectivity (JDBC) Thin
driver, and therefore, no Oracle Home is required. The JDBC drivers that are shipped with
version 1.5.3 support 11g R1. Therefore, users will no longer be able to connect to an Oracle
8.1.7 database.
SQL Developer does not require an installer and you need to simply unzip the downloaded file.
With SQL Developer, users can connect to Oracle Databases 9.2.0.1 and later, and all Oracle
database editions including Express Edition.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 30
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LDeveloper
era 1.5.3
f
d
s
Installing
SQL
o tran
IigSQL
Oracle
does not require an installer. To install SQL Developer, you need an
nDeveloper
o
n
unzip tool.
To install SQL Developer, perform the following steps:
1. Create a folder. For example: <local drive>:\software
2. Download the SQL Developer kit from
http://www.oracle.com/technology/products/database/sql_developer/index.html.
3. Unzip the downloaded SQL Developer kit into the folder created in step 1.
Starting SQL Developer
To start SQL Developer, go to <local drive>:\software\sqldeveloper, and
double-click sqldeveloper.exe.
Notes:
The SQL Developer 1.5.3 kit, named sqldeveloper-5783.zip, is located in is
d:\labs\software on your classroom machine.
When you open SQL Developer 1.5.3 for the first time, select No when prompted to
migrate settings from a previous release.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 31
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L1.5.3
eInterface
f
d
s
SQL Developer
an 1.5.3 interface contains all of the features found in version 1.2, and also
igo Developer
r
t
The
ISQL
non features.
some additional
Version 1.5.3 contains three main navigation tabs, from left to right:
Connections tab: By using this tab, you can browse database objects and users to which
you have access.
Files tab: Identified by the Files folder icon, this tab enables you to access files from your
local machine without having to use the File > Open menu.
Reports tab: Identified by the Reports icon, this tab enables you to run predefined reports
or create and add your own reports.
General Navigation and Use
SQL Developer uses the left side for navigation to find and select objects, and the right side to
display information about selected objects. You can customize many aspects of the appearance
and behavior of SQL Developer by setting preferences.
The features and functions that have been covered previously in this lesson for version 1.2, such
as Creating a Connection, Browsing Database Objects, Creating Schema Objects, Using the SQL
Worksheet, Using Snippets, Creating Reports, and Setting Preferences, are equivalent in the
1.5.3 interface.
Note: As with version 1.2, you need to define at least one connection to be able to connect to a
database schema and issue SQL queries or run procedures/functions.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 32
Cas Training
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 33
Cas Training
Summary
In this appendix, you should have learned how to use SQL
Developer to do the following:
Browse, create, and edit database objects
Execute SQL statements and scripts in SQL Worksheet
Create and save custom reports
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
go -traisna free graphical tool to simplify database development tasks. Using SQL
IiDeveloper
SQL
nonyou can browse, create, and edit database objects. You can use SQL Worksheet to
Developer,
run SQL statements and scripts. SQL Developer enables you to create and save your own special
set of reports for repeated use.
Version 1.2 is the default version set up for this class. Version 1.5.3 is also available on the
classroom machine for use with all examples, demos, and practices.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II C - 34
Cas Training
Using SQL*Plus
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this appendix, you should be able to do the
following:
Log in to SQL*Plus
Edit SQL commands
Format the output using SQL*Plus commands
Interact with script files
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
ancreate SELECT statements that can be used again and again. This appendix also
igo want
r
t
You
to
Imight
n
nouse
covers the
of SQL*Plus commands to execute SQL statements. You learn how to format output
using SQL*Plus commands, edit SQL commands, and save scripts in SQL*Plus.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 2
Cas Training
SQL statements
Server
SQL*Plus
Query results
a
s
a
)h
Buffer
s
e
a ide
u
g
ta t Gu
s
e
g den
@
a Stu
SQL arr
leg e this
scripts
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
SQL and o
SQL*Plus
tra language used for communication with the Oracle server from any tool or
SQL
Iisiga command
n
no Oracle SQL contains many extensions. When you enter a SQL statement, it is stored in a
application.
part of memory called the SQL buffer and remains there until you enter a new SQL statement.
SQL*Plus is an Oracle tool that recognizes and submits SQL statements to the Oracle9i Server for
execution. It contains its own command language.
Features of SQL
Can be used by a range of users, including those with little or no programming
experience
Is a nonprocedural language
Reduces the amount of time required for creating and maintaining systems
Is an English-like language
Features of SQL*Plus
Accepts ad hoc entry of statements
Accepts SQL input from files
Provides a line editor for modifying SQL statements
Controls environmental settings
Formats query results into basic reports
Accesses local and remote databases
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 3
Cas Training
SQL*Plus
An environment
Oracle-proprietary
Keywords can be
abbreviated.
Commands do not
allow manipulation of a
s
a
values in the database.
h
)
es e
a
gu uid
a
t
es ent G
g
SQL
SQL
SQL*Plus
ra@ Stud SQL*Plus
r
a
statements
buffer legcommands
buffer
his
i
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de n(continued)
SQL and o
SQL*Plus
s
g
a
i
r
t compares SQL and SQL*Plus:
-table
TheI
following
n
o
n
SQL
Is a language for communicating with the
Oracle server to access data
Is based on American National Standards
Institute (ANSI)standard SQL
Manipulates data and table definitions in the
database
Is entered into the SQL buffer on one or
more lines
Does not have a continuation character
Cannot be abbreviated
Uses a termination character to execute
commands immediately
Uses functions to perform some formatting
SQL*Plus
Recognizes SQL statements and sends them
to the server
Is the Oracle-proprietary interface for
executing SQL statements
Does not allow manipulation of values in the
database
Is entered one line at a time, not stored in the
SQL buffer
Uses a dash () as a continuation character if
the command is longer than one line
Can be abbreviated
Does not require termination characters;
executes commands immediately
Uses commands to format data
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 4
Cas Training
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.
a
Execute saved files.
s
a
Load commands from the file to buffer to edit. es) h
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
SQL*Pluso d
an
SQL*Plus
in which you can:
Iig oisnan-trenvironment
n
Execute SQL statements to retrieve, modify, add, and remove data from the database
Format, perform calculations on, store, and print query results in the form of reports
Create script files to store SQL statements for repeated use in the future
SQL*Plus commands can be divided into the following main categories:
Category
Purpose
Environment
Format
File manipulation
Execution
Edit
Interaction
Miscellaneous
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 5
Cas Training
Logging In to SQL*Plus
sqlplus [username[/password[@database]]]
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
2
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eSQL*Plus
d
Logging In
to
o trans
g
i
How
Iyou invoke
n- SQL*Plus depends on which type of operating system or Windows environment
o
n
you are running.
To log in from a Windows environment:
1. Select Start > Programs > Oracle > Application Development > SQL*Plus.
2. Enter the username, password, and database name.
To log in from a command-line environment:
1. Log on to your machine.
2. Enter the sqlplus command shown in the slide.
In the syntax:
username Your database username
password Your database password (Your password is visible if you enter it here.)
@database The database connect string
Note: To ensure the integrity of your password, do not enter it at the operating system prompt.
Instead, enter only your username. Enter your password at the password prompt.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 6
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
deSettings
Changingothe
s of the SQL*Plus Environment
n
g
a
i
r
-t change the look of the SQL*Plus environment by using the SQL*Plus Properties
You
Ican optionally
n
o
n
dialog box.
In the SQL*Plus window, right-click the title bar and in the shortcut menu that appears, select
Properties. You can then use the Colors tab of the SQL*Plus Properties dialog box to set Screen
Background and Screen Text.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Table
d
Displaying
the
o transStructure
g
i
In SQL*Plus,
I on-you can display the structure of a table using the DESCRIBE command. The result of
n is a display of column names and data types as well as an indication if a column must
the command
contain data.
In the syntax:
tablename The name of any existing table, view, or synonym that is accessible to
the user
To describe the DEPARTMENTS table, use this command:
SQL> DESCRIBE DEPARTMENTS
Name
Null?
Type
----------------------- -------- --------------DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 8
Cas Training
DESCRIBE departments
Name
----------------------DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
Null?
Type
-------- -----------NOT NULL NUMBER(4)
s
a
h
NOT NULL VARCHAR2(30)
s)
e
NUMBER(6)
a ide
u
g
NUMBER(4)
ta
Gu
es ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Table
d
Displaying
the
o transStructure (continued)
g
i
TheI
examplenin
- the slide displays the information about the structure of the DEPARTMENTS table. In
o
n
the result:
Null?: Specifies whether a column must contain data (NOT NULL indicates that a column must
contain data.)
Type: Displays the data type for a column
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 9
Cas Training
A[PPEND] text
C[HANGE] / old / new
C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nCommands
SQL*PlusoEditing
s
g
a
i
r
-t
SQL*Plus
are entered one line at a time and are not stored in the SQL buffer.
I ocommands
n
n
Comm and
D escription
A[PPEND] text
C[HANGE] / old / new
C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n
D eletes
D eletes
D eletes
D eletes
D eletes
Guidelines
If you press Enter before completing a command, SQL*Plus prompts you with a line number.
You terminate the SQL buffer either by entering one of the terminator characters (semicolon or
slash) or by pressing [Enter] twice. The SQL prompt then appears.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 10
Cas Training
I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nCommands
SQL*PlusoEditing
(continued)
s
g
a
i
r
-t
ICommand
n
o
Description
n
I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text
Note: You can enter only one SQL*Plus command for each SQL prompt. SQL*Plus commands are
not stored in the buffer. To continue a SQL*Plus command on the next line, end the first line with a
hyphen (-).
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 11
Cas Training
LIST
1 SELECT last_name
2* FROM
employees
1
1* SELECT last_name
a
s
a
)h
A , job_id
s
e
a ide
1* SELECT last_name, job_id
u
g
ta t Gu
s
e
g den
@
ra Stu
LIST
r
a
1 SELECT last_name, job_id
leg e this
i
(
2* FROM
employees lez
us
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe
dn,e andnAPPEND
Using LIST,
s
o
ig the L[IST]
tra command to display the contents of the SQL buffer. The asterisk (*) beside
IUse
n
o
linen2 in the buffer indicates that line 2 is the current line. Any edits that you made apply to the
current line.
Change the number of the current line by entering the number (n) of the line that you want to
edit. The new current line is displayed.
Use the A[PPEND] command to add text to the current line. The newly edited line is displayed.
Verify the new contents of the buffer by using the LIST command.
Note: Many SQL*Plus commands, including LIST and APPEND, can be abbreviated to just their
first letter. LIST can be abbreviated to L; APPEND can be abbreviated to A.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 12
Cas Training
LIST
1* SELECT * from employees
c/employees/departments
1* SELECT * from departments
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
LIST
e
g den
@
1* SELECT * from departments rra
tu
S
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nCommand
Using theoCHANGE
s
g
a
i
r
IUse L[IST]
-t to display the contents of the buffer.
n
o
Usenthe C[HANGE] command to alter the contents of the current line in the SQL buffer. In this
case, replace the employees table with the departments table. The new current line is
displayed.
Use the L[IST] command to verify the new contents of the buffer.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 13
Cas Training
SAVE filename
GET filename
START filename
@ filename
EDIT filename
SPOOL filename
EXIT
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
deCommands
SQL*PlusoFile
s
n
g
a
i
r
-t communicate with the Oracle server. SQL*Plus commands control the environment,
SQL
Istatements
n
o
n results, and manage files. You can use the commands described in the following table:
format query
Command
Description
@ filename
ED[IT]
ED[IT] [filename[.ext]]
SPO[OL]
[filename[.ext]|
OFF|OUT]
EXIT
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 14
Cas Training
a
s
a
)h
s
e
LAST_NAME
MANAGER_ID DEPARTMENT_ID
a ide
u
g
------------------------- ---------- ------------u
ta t G90
s
e
King
g den
@
Kochhar
100
90
ra Stu
r
a
...
leg e this
i
(
107 rows selected.
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de START,
Using theoSAVE,
s and EDIT Commands
n
g
a
i
r
SAVE
I on-t
Use the n
SAVE command to store the current contents of the buffer in a file. In this way, you can store
START my_query
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 15
Cas Training
EDIT my_query
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de START,
Using theoSAVE,
s and EDIT Commands (continued)
n
g
a
i
r
EDIT
I on-t
Use the n
EDIT command to edit an existing script. This opens an editor with the script file in it. When
you have made the changes, quit the editor to return to the SQL*Plus command line.
Note: The / is a delimiter that signifies the end of the statement. When encountered in a file,
SQL*Plus runs the statement prior to this delimiter. The delimiter must be the first character of a new
line immediately following the statement.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 16
Cas Training
SERVEROUTPUT Command
e ent
g
tud
ra@
r
S
SET SERVEROUT[PUT] {ON | OFF} [SIZE
{n
| UNL[IMITED]}]
a
leg e this | TRU[NCATED]}]
[FOR[MAT] {WRA[PPED] | WOR[D_WRAPPED]
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LCommand
era
f
d
SERVEROUTPUT
s
o tran
- programs perform input and output through SQL statements, to store data in
Most
IofigtheonPL/SQL
n
database tables or query those tables. All other PL/SQL input/output is done through APIs that
interact with other programs. For example, the DBMS_OUTPUT package has procedures such as
PUT_LINE. To see the result outside of PL/SQL requires another program, such as SQL*Plus, to
read and display the data passed to DBMS_OUTPUT.
SQL*Plus does not display DBMS_OUTPUT data unless you first issue the SQL*Plus command SET
SERVEROUTPUT ON as follows:
SET SERVEROUTPUT ON
Note
SIZE sets the number of bytes of the output that can be buffered within the Oracle Database
server. The default is UNLIMITED. n cannot be less than 2000 or greater than 1,000,000.
For additional information about SERVEROUTPUT, see the Oracle Database PL/SQL User's
Guide and Reference 11g.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 17
Cas Training
Description
file_name[.ext]
CRE[ATE]
a
s
a
)h
s
e
of theefile
Adds the contents of the buffer to theaend
APP[END]
u
g
you specify
uid
a
t
G
s
e ent
g
Stops spooling
OFF
ra@ Stud
r
a
Stops spooling
sends
OUT
his the file to your computers
leg and
i
t
(
e
standard
s printer
ez o(default)
l
u
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de nsSPOOL
Using theoSQL*Plus
Command
g
a
i
r
TheI
SPOOLn
command
stores query results in a file or optionally sends the file to a printer. The
-t
o
SPOOL n
command has been enhanced. You can now append to, or replace an existing file, where
REP[LACE]
previously you could only use SPOOL to create (and replace) a file. REPLACE is the default.
To spool output generated by commands in a script without displaying the output on the screen, use
SET TERMOUT OFF. SET TERMOUT OFF does not affect output from commands that run
interactively.
You must use quotes around file names containing white space. To create a valid HTML file using
SPOOL APPEND commands, you must use PROMPT or a similar command to create the HTML
page header and footer. The SPOOL APPEND command does not parse HTML tags. SET
SQLPLUSCOMPAT[IBILITY] to 9.2 or earlier to disable the CREATE, APPEND and SAVE
parameters.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 18
Cas Training
)h
s
e
a ide
u
g
SET AUTOTRACE ON
ta t Gu
s
e
n
-- The AUTOTRACE report includes bothgthe optimizer
e
@
d
u
-- execution path and the SQL statement
ra Stexecution
r
a
-- statistics
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
ra
de nsfeCommand
Using theoAUTOTRACE
EXPLAIN
-trathe query execution path by performing an EXPLAIN PLAN. STATISTICS
Iig oshows
n
n
displays SQL statement statistics. The formatting of your AUTOTRACE report may vary depending
on the version of the server to which you are connected and the configuration of the server. The
DBMS_XPLAN package provides an easy way to display the output of the EXPLAIN PLAN
command in several predefined formats.
Note
For additional information about the package and subprograms, see the Oracle Database
PL/SQL Packages and Types Reference 11g guide.
For additional information about the EXPLAIN PLAN, see the Oracle Database SQL Reference
11g.
For additional information about Execution Plans and the statistics, see the Oracle Database
Performance Tuning Guide 11g.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 19
Cas Training
Summary
In this appendix, you should have learned how to use SQL*Plus
as an environment to do the following:
Execute SQL statements
Edit SQL statements
Format the output
Interact with script files
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
Summaryo d
an environment that you can use to send SQL commands to the database
SQL*Plus
Iig oisnan-trexecution
n to edit and save SQL commands. You can execute commands from the SQL prompt or
server and
from a script file.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II D - 20
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this appendix, you should be able to do the
following:
Use the ROLLUP operation to produce subtotal values
Use the CUBE operation to produce cross-tabulation values
Use the GROUPING function to identify the row values
created by ROLLUP or CUBE
Use GROUPING SETS to produce a single result set
a
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
InIthis
n- you learn how to Group data to obtain the following:
o
n
Subtotal values by using the ROLLUP operator
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 2
Cas Training
[column,] group_function(column). . .
table
condition]
group_by_expression]
column];
a
s
a
)h
Example:
s
e
a ide
u
g
SELECT AVG(salary), STDDEV(salary),
ta t Gu
s
e
COUNT(commission_pct),MAX(hire_date)
g den
@
FROM
employees
ra Stu
r
a
WHERE job_id LIKE 'SA%'; ileg
his
t
(
e
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Group Functions
n
aGROUP
igouse -the
r
t
Ican
You
BY clause to divide the rows in a table into groups. You can then use
non
group functions to return summary information for each group. Group functions can appear in
select lists and in ORDER BY and HAVING clauses. The Oracle server applies the group
functions to each group of rows and returns a single result row for each group.
Types of group functions: Each of the group functionsAVG, SUM, MAX, MIN, COUNT,
STDDEV, and VARIANCEaccepts one argument. The AVG, SUM, STDDEV, and VARIANCE
functions operate only on numeric values. MAX and MIN can operate on numeric, character, or
date data values. COUNT returns the number of non-null rows for the given expression. The
example in the slide calculates the average salary, standard deviation on the salary, number of
employees earning a commission, and the maximum hire date for those employees whose
JOB_ID begins with SA.
Guidelines for Using Group Functions
The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE.
All group functions except COUNT(*) ignore null values. To substitute a value for null
values, use the NVL function. COUNT returns either a number or zero.
The Oracle server implicitly sorts the result set in ascending order of the grouping columns
specified, when you use a GROUP BY clause. To override this default ordering, you can use
DESC in an ORDER BY clause.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 3
Cas Training
Syntax:
SELECT
FROM
[WHERE
[GROUP BY
[ORDER BY
[column,] group_function(column). . .
table
condition]
group_by_expression]
column];
Example:
s
a
h
)
s
e
SELECT
department_id, job_id, SUM(salary),
a ide
u
g
COUNT(employee_id)
ta t Gu
s
e
FROM
employees
g den
@
GROUP BY department_id, job_id
ra; Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e GROUP
d
Review of
the
o trans BY Clause
g
i
-illustrated in the slide is evaluated by the Oracle server as follows:
Iexample
The
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 4
Cas Training
[column,] group_function(column)...
table
condition]
s
group_by_expression]
a
h
having_expression]
s)
e
column];
ua de
ag Gui
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
HAVING o
Clause
tra and group functions are calculated before the HAVING clause is applied to
Iig are
Groups
formed
n
no The HAVING clause can precede the GROUP BY clause, but it is recommended that
the groups.
you place the GROUP BY clause first because it is more logical.
The Oracle server performs the following steps when you use the HAVING clause:
1. It groups rows.
2. It applies the group functions to the groups and displays the groups that match the criteria in
the HAVING clause.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 5
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e Lthe sROLLUP
era and CUBE Operators
f
d
GROUP BY
with
an and CUBE operators in the GROUP BY clause of a query. ROLLUP
igo ROLLUP
r
t
Ispecify
You
n
noproduces
grouping
a result set containing the regular grouped rows and subtotal rows. The
ROLLUP operator also calculates a grand total. The CUBE operation in the GROUP BY clause
groups the selected rows based on the values of all possible combinations of expressions in the
specification and returns a single row of summary information for each group. You can use the
CUBE operator to produce cross-tabulation rows.
Note: When working with ROLLUP and CUBE, make sure that the columns following the
GROUP BY clause have meaningful, real-life relationships with each other; otherwise, the
operators return irrelevant information.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 6
Cas Training
ROLLUP Operator
[column,] group_function(column). . .
table
condition]
[ROLLUP] group_by_expression]
having_expression];
s
a
h
column];
s)
e e
a
u
ag Guid
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
ROLLUP o
Operator
ig -toperator
ra delivers aggregates and superaggregates for expressions within a GROUP
IROLLUP
The
n
no The ROLLUP operator can be used by report writers to extract statistics and
BY statement.
summary information from result sets. The cumulative aggregates can be used in reports, charts,
and graphs.
The ROLLUP operator creates groupings by moving in one direction, from right to left, along the
list of columns specified in the GROUP BY clause. It then applies the aggregate function to these
groupings.
Note
To produce subtotals in n dimensions (that is, n columns in the GROUP BY clause) without a
ROLLUP operator, n+1 SELECT statements must be linked with UNION ALL. This makes
the query execution inefficient because each of the SELECT statements causes table access.
The ROLLUP operator gathers its results with just one table access. The ROLLUP operator
is useful when there are many columns involved in producing the subtotals.
Subtotals and totals are produced with ROLLUP. CUBE produces totals as well but
effectively rolls up in each possible direction, producing cross-tabular data.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta2 t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
3
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
ExampleoofdaeROLLUP
s Operator
n
g
a
i
r
example
-t in the slide:
InIthe
n
o
n salaries for every job ID within a department for those departments whose department
Total
Cas Training
CUBE Operator
[column,] group_function(column)...
table
condition]
[CUBE] group_by_expression]
s
having_expression]
a
h
)
column];
es
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
CUBE Operator
an is an additional switch in the GROUP BY clause in a SELECT statement. The
igo operator
r
t
ICUBE
The
non can be applied to all aggregate functions, including AVG, SUM, MAX, MIN, and
CUBE operator
COUNT. It is used to produce result sets that are typically used for cross-tabular reports.
ROLLUP produces only a fraction of possible subtotal combinations, whereas CUBE produces
subtotals for all possible combinations of groupings specified in the GROUP BY clause, and a
grand total.
The CUBE operator is used with an aggregate function to generate additional rows in a result set.
Columns included in the GROUP BY clause are cross-referenced to produce a superset of groups.
The aggregate function specified in the select list is applied to these groups to produce summary
values for the additional superaggregate rows. The number of extra groups in the result set is
determined by the number of columns included in the GROUP BY clause.
In fact, every possible combination of the columns or expressions in the GROUP BY clause is
used to produce superaggregates. If you have n columns or expressions in the GROUP BY clause,
there will be 2n possible superaggregate combinations. Mathematically, these combinations form
an n-dimensional cube, which is how the operator got its name.
By using application or programming tools, these superaggregate values can then be fed into
charts and graphs that convey results and relationships visually and effectively.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 9
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g de3n
@
ra Stu
r
a
leg e this
i
4
(
z
s
e
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe
ExampleoofdaeCUBE
Operator
s
n
ig of-tthe
raSELECT statement in the example can be interpreted as follows:
Ioutput
The
n
nototal salary for every job within a department (for those departments whose department
The
2
Cas Training
GROUPING Function
The GROUPING function:
Is used with either the CUBE or ROLLUP operator
Is used to find the groups forming the subtotal in a row
Is used to differentiate stored NULL values from NULL
values created by ROLLUP or CUBE
Returns 0 or 1
[column,] group_function(column) .. , has
s)
GROUPING(expr)
e
a ide
u
FROM
table
g
ta t Gu
s
[WHERE
condition]
e
g den
[GROUP BY [ROLLUP][CUBE] group_by_expression]
@
ra Stu
r
[HAVING
having_expression]
a
s
g
[ORDER BY column];
(ile e thi
SELECT
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
GROUPING d
Function
n
igo -trafunction
The
can be used with either the CUBE or ROLLUP operator to help you
IGROUPING
n
o
understand
n how a summary value has been obtained.
The GROUPING function uses a single column as its argument. The expr in the GROUPING
function must match one of the expressions in the GROUP BY clause. The function returns a
value of 0 or 1.
The values returned by the GROUPING function are useful to:
Determine the level of aggregation of a given subtotal (that is, the group or groups on which
the subtotal is based)
Identify whether a NULL value in the expression column of a row of the result set indicates:
- A NULL value from the base table (stored NULL value)
- A NULL value created by ROLLUP or CUBE (as a result of a group function on that
expression)
A value of 0 returned by the GROUPING function based on an expression indicates one of the
following:
The expression has been used to calculate the aggregate value.
The NULL value in the expression column is a stored NULL value.
A value of 1 returned by the GROUPING function based on an expression indicates one of the
following:
The expression has not been used to calculate the aggregate value.
The NULL value in the expression column is created by ROLLUP or CUBE as a result of
grouping.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 11
Cas Training
2 ) has
es e
a
gu uid
a
t
es ent G
g
ra@ Stud
r
a
leg e this
i
3
(
z
s
e
l to u
z
n
o nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe Function
ExampleoofdaeGROUPING
s
n
trinathe slide, consider the summary value 4400 in the first row (labeled 1). This
igexample
InIthe
n
novalue is the total salary for the job ID of AD_ASST within department 10. To calculate
summary
this summary value, both the DEPARTMENT_ID and JOB_ID columns have been taken into
account. Thus, a value of 0 is returned for both the GROUPING(department_id) and
GROUPING(job_id)expressions.
Consider the summary value 4400 in the second row (labeled 2). This value is the total salary for
department 10 and has been calculated by taking into account the DEPARTMENT_ID column;
thus, a value of 0 has been returned by GROUPING(department_id). Because the JOB_ID
column has not been taken into account to calculate this value, a value of 1 has been returned for
GROUPING(job_id). You can observe similar output in the fifth row.
In the last row, consider the summary value 54800 (labeled 3). This is the total salary for those
departments whose department ID is less than 50 and all job titles. To calculate this summary
value, neither of the DEPARTMENT_ID and JOB_ID columns have been taken into account.
Thus, a value of 1 is returned for both the GROUPING(department_id)and
GROUPING(job_id)expressions.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 12
Cas Training
GROUPING SETS
a ide
u
g
performance benefit.
u
ta
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
GROUPING
SETS
o tran
- is a further extension of the GROUP BY clause that you can use to specify
Iig onSETS
GROUPING
n
multiple groupings of data. Doing so facilitates efficient aggregation and, therefore, facilitates
analysis of data across multiple dimensions.
A single SELECT statement can now be written using GROUPING SETS to specify various
groupings (which can also include ROLLUP or CUBE operators), rather than multiple SELECT
statements combined by UNION ALL operators. For example:
SELECT department_id, job_id, manager_id, AVG(salary)
FROM employees
GROUP BY
GROUPING SETS
((department_id, job_id, manager_id),
(department_id, manager_id),(job_id, manager_id));
Cas Training
This statement computes all the 8 (2 *2 *2) groupings, though only the(department_id,
job_id, manager_id), (department_id, manager_id), and (job_id,
manager_id) groups are of interest to you.
Another alternative is the following statement:
SELECT department_id, job_id, manager_id, AVG(salary)
FROM employees
GROUP BY department_id, job_id, manager_id
UNION ALL
SELECT department_id, NULL, manager_id, AVG(salary)
FROM employees
GROUP BY department_id, manager_id
UNION ALL
SELECT NULL, job_id, manager_id, AVG(salary)
FROM employees
GROUP BY job_id, manager_id;
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
This statement requires three scans of the base e
table,
which
l g e thismakes it inefficient.
i
(
CUBE and ROLLUP can be thought of as
z
ssets with very specific semantics and results.
egrouping
l
u
o
z fact:e t
The following equivalencies show
nthis
o
G cens
a
r
r GROUPING
li SETS
CUBE(a, b, c)
a
e
g
l
b b, c), (a, b), (a, c), (b, c),
a((a,
is equivalent L
to e
r
e
e
f
(a), (b), (c), ())
o d trans
g
i
- b,c) GROUPING SETS ((a, b, c), (a, b),(a), ())
IROLLUP(a,
non
is equivalent to
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 14
Cas Training
department_id, job_id,
manager_id,AVG(salary)
FROM
employees
GROUP BY GROUPING SETS
((department_id,job_id), (job_id,manager_id));
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
2
r
a
s
g
i
(ile se th
z
le to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e Example
fe
dSETS:
GROUPING
s
o
n
ig in-the
traslide calculates aggregates over two groupings. The table is divided into the
Iquery
The
n
nogroups:
following
Department ID, Job ID
Job ID, Manager ID
The average salaries for each of these groups are calculated. The result set displays the average
salary for each of the two groups.
In the output, the group marked as 1 can be interpreted as the following:
The average salary of all employees with the SH_CLERK job ID under manager 122 is
3,200.
The average salary of all employees with the AC_MGR job ID under manager 101 is 12,000,
and so on.
The group marked as 2 in the output is interpreted as the following:
The average salary of all employees with the AC_MGR job ID in department 110 is 12,000.
The average salary of all employees with the AD_PRES job ID in department 90 is 24,000,
and so on.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 15
Cas Training
In the absence of an optimizer that looks across query blocks to generate the execution plan, the
preceding query would need two scans of the base table, EMPLOYEES. This could be very
inefficient. Therefore, the usage of the GROUPING SETS statement is recommended.
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 16
Cas Training
Composite Columns
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Composite
Columns
o tran
ig n-column
A Icomposite
is a collection of columns that are treated as a unit during the computation
o
n
of groupings. You specify the columns in parentheses as in the following statement: ROLLUP
(a, (b, c), d)
Here, (b, c) forms a composite column and is treated as a unit. In general, composite
columns are useful in ROLLUP, CUBE, and GROUPING SETS. For example, in CUBE or
ROLLUP, composite columns would require skipping aggregation across certain levels.
That is, GROUP BY ROLLUP(a, (b, c) )is equivalent to:
GROUP BY a, b, c UNION ALL
GROUP BY a UNION ALL
GROUP BY ()
Here, (b, c) is treated as a unit and ROLLUP is not applied across (b, c). It is as though
you have an aliasfor example, z as an alias for (b, c), and the GROUP BY expression
reduces to: GROUP BY ROLLUP(a, z).
Note: GROUP BY( ) is typically a SELECT statement with NULL values for the columns a and
b and only the aggregate function. It is generally used for generating grand totals.
SELECT
NULL, NULL, aggregate_col
FROM
<table_name>
GROUP BY ( );
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 17
Cas Training
BY
BY
BY
BY
a, b, c UNION ALL
a, b UNION ALL
a UNION ALL
()
Similarly:
GROUP BY CUBE((a, b), c)
BY
BY
BY
By
a, b, c UNION ALL
a, b UNION ALL
c UNION ALL
()
a
s
a
) hGROUP BY
The following table shows the GROUPING SETS specification and the equivalent
s
e
a ide
specification.
u
g
ta t Gu
s
e
n BY Statements
g dGROUP
GROUPING SETS Statements
Equivalent
e
@
ra Stu
r
a
is
leg e thGROUP
i
(
BY a UNION ALL
GROUP BY GROUPING SETS(a, b, c)
z
s
e
GROUP BY b UNION ALL
l to u
z
n
GROUP BY c
o nse
G
e
rra SETS(a,
lic b,(b, c)) GROUP BY a UNION ALL
GROUP BY GROUPING
a
e
g
l
b
GROUP BY b UNION ALL
(The GROUPING
has a composite
Le SETS
aexpression
r
e
e
f
GROUP BY b, c
column.)d
o trans
g
i
IGROUPonBY- GROUPING SETS((a, b, c))
GROUP BY a, b, c
n
GROUP BY GROUPING SETS(a, (b), ())
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 18
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den 3
@
ra Stu
r
a
leg e this
i
(
4
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfeExample
d
Composite
Columns:
o tran
Iig othen-example:
Consider
n SELECT department_id, job_id,manager_id, SUM(salary)
2
FROM
employees
GROUP BY ROLLUP( department_id,job_id, manager_id);
This query results in the Oracle server computing the following groupings:
(job_id, manager_id)
(department_id, job_id, manager_id)
(department_id)
Grand total
If you are interested only in specific groups, you cannot limit the calculation to those groupings
without using composite columns. With composite columns, this is possible by treating JOB_ID
and MANAGER_ID columns as a single unit while rolling up. Columns enclosed in parentheses
are treated as a unit while computing ROLLUP and CUBE. This is illustrated in the example in
the slide. By enclosing the JOB_ID and MANAGER_ID columns in parentheses, you indicate to
the Oracle server to treat JOB_ID and MANAGER_ID as a single unitthat is, a composite
column.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 19
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en across query blocks to generate the execution plan, the
a Gthatliclooks
r
In the absence of an optimizer
r
le scans of the base table, EMPLOYEES. This could be very
ega need
b
preceding queryLwould
three
a
r
e sfe
inefficient.dTherefore,
the use of composite columns is recommended.
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 20
Cas Training
Concatenated Groupings
a
s
a
)h
s
e
a idd)
e
GROUP BY GROUPING SETS(a, b), GROUPING g
SETS(c,
u
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Groupings
d
Concatenated
o trans
g
i
I on- groupings offer a concise way to generate useful combinations of groupings. The
Concatenated
n groupings are specified by listing multiple grouping sets, CUBEs, and ROLLUPs,
concatenated
and separating them with commas. The following is an example of concatenated grouping sets:
GROUP BY GROUPING SETS(a, b), GROUPING SETS(c, d)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 21
Cas Training
s
a
h
s)
e
1
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
2
leg e this
i
(
3
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Groupings:
d
Concatenated
Example
o trans
g
i
Iexample
The
n-in the slide results in the following groupings:
o
n
(department_id,job_id,) (1)
(department_id,manager_id) (2)
(department_id) (3)
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 22
Cas Training
Summary
In this appendix, you should have learned how to use the:
ROLLUP operation to produce subtotal values
CUBE operation to produce cross-tabulation values
GROUPING function to identify the row values created by
ROLLUP or CUBE
GROUPING SETS syntax to define multiple groupings in the
same query
a
s
a
GROUP BY clause to combine expressions in various
s) hways:
e e
a
u
ag Guid
t
s
e ent
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
anCUBE are extensions of the GROUP BY clause.
igo -tand
r
IROLLUP
non is used to display subtotal and grand total values.
ROLLUP
Composite columns
Concatenated grouping sets
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II E - 23
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Hierarchical Retrieval
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
Interpret the concept of a hierarchical query
Create a tree-structured report
Format hierarchical data
Exclude branches from the tree structure
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
iglesson,
- you learn how to use hierarchical queries to create tree-structured reports.
InIthis
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 2
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
efrom
d
Sample Data
o transthe EMPLOYEES Table
g
i
I hierarchical
Using
n- queries, you can retrieve data based on a natural hierarchical relationship
o
n
between rows in a table. A relational database does not store records in a hierarchical way.
However, where a hierarchical relationship exists between the rows of a single table, a process
called tree walking enables the hierarchy to be constructed. A hierarchical query is a method of
reporting, with the branches of a tree in a specific order.
Imagine a family tree with the eldest members of the family found close to the base or trunk of
the tree and the youngest members representing branches of the tree. Branches can have their
own branches, and so on.
A hierarchical query is possible when a relationship exists between rows in a table. For example,
in the slide, you see that Kochhar, De Haan, and Hartstein report to MANAGER_ID 100, which is
Kings EMPLOYEE_ID.
Note: Hierarchical trees are used in various fields such as human genealogy (family trees),
livestock (breeding purposes), corporate management (management hierarchies), manufacturing
(product assembly), evolutionary research (species development), and scientific research.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 3
Cas Training
De Haan
Mourgos
Zlotkey
Hartstein
a
s
a
)h
s
Whalen Higgins Hunold Rajs Davies
e
Matos Vargas
a ide
u
g
ta t Gu Fay
s
e
g den
@
ra AbelStuTaylor Grant
Gietz Ernst
r
Lorentz
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eStructure
d
Natural Tree
o trans
g
i
IEMPLOYEES
The
n- table has a tree structure representing the management reporting line. The
o
n
hierarchy can be created by looking at the relationship between equivalent values in the
EMPLOYEE_ID and MANAGER_ID columns. This relationship can be exploited by joining the
table to itself. The MANAGER_ID column contains the employee number of the employees
manager.
The parent-child relationship of a tree structure enables you to control:
The direction in which the hierarchy is walked
The starting point inside the hierarchy
Note: The slide displays an inverted tree structure of the management hierarchy of the
employees in the EMPLOYEES table.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 4
Cas Training
Hierarchical Queries
a
s
a
)h
s
expr comparison_operator expr
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LClauses
era
f
d
s
Keywords
and
o tran
Iig on-queries
Hierarchical
can be identified by the presence of the CONNECT BY and START WITH
n
condition:
clauses.
In the syntax:
SELECT
LEVEL
FROM table
WHERE
condition
START WITH
CONNECT BY
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 5
Cas Training
Starting Point
slast
a
Using the EMPLOYEES table, start with the employee whose
h
s)
e
name is Kochhar.
a
e
gu uid
a
t
...START WITH last_name = 'Kochhar'
es ent G
g
ra@ Stud
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
deTreensfer
Walkingo
the
ig or rows
trato be used as the root of the tree are determined by the START WITH clause.
Irow
The
n
no WITH clause can contain any valid condition.
The START
Examples
Using the EMPLOYEES table, start with King, the president of the company.
... START WITH manager_id IS NULL
Using the EMPLOYEES table, start with employee Kochhar. A START WITH condition can
contain a subquery.
... START WITH employee_id = (SELECT employee_id
FROM
employees
WHERE last_name = 'Kochhar')
If the START WITH clause is omitted, the tree walk is started with all the rows in the table as
root rows.
Note: The CONNECT BY and START WITH clauses are not ANSI SQL standard.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 6
Cas Training
a
s
a
)h
s
e
a ide
u
Column1 = Parent
Key
Top down
g
taKey t Gu
s
Column2 = Child
e
g den
@
tu Key
ra = Child
r
Bottom up
S
Column1
a
g thi=s Parent Key
leColumn2
i
(
e
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
deTreen(continued)
s
Walkingo
the
g
a
i
r
-tof the query is determined by the CONNECT BY PRIOR column placement. For
Idirection
The
n
o
n the PRIOR operator refers to the parent row. For bottom-up, the PRIOR operator
top-down,
Direction
refers to the child row. To find the child rows of a parent row, the Oracle server evaluates the
PRIOR expression for the parent row and the other expressions for each row in the table. Rows
for which the condition is true are the child rows of the parent. The Oracle server always selects
child rows by evaluating the CONNECT BY condition with respect to a current parent row.
Examples
Walk from the top down using the EMPLOYEES table. Define a hierarchical relationship in
which the EMPLOYEE_ID value of the parent row is equal to the MANAGER_ID value of the
child row:
... CONNECT BY PRIOR employee_id = manager_id
Walk from the bottom up using the EMPLOYEES table:
... CONNECT BY PRIOR manager_id = employee_id
The PRIOR operator does not necessarily need to be coded immediately following CONNECT
BY. Thus, the following CONNECT BY PRIOR clause gives the same result as the one in the
preceding example:
... CONNECT BY employee_id = PRIOR manager_id
Note: The CONNECT BY clause cannot contain a subquery.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 7
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
deTree:nFrom
s the Bottom Up
Walkingo
the
g
a
i
r
-int the slide displays a list of managers starting with the employee whose employee
Iexample
The
n
o
n
ID is 101.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 8
Cas Training
SELECT
PRIOR
FROM
START
CONNECT
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
deTree:nFrom
s the Top Down
Walkingo
the
g
a
i
r
-tthe top down, display the names of the employees and their manager. Use
I ofrom
Walking
n
n King as the starting point. Print only one column.
employee
Example
In the following example, EMPLOYEE_ID values are evaluated for the parent row and
MANAGER_ID, and SALARY values are evaluated for the child rows. The PRIOR operator
applies only to the EMPLOYEE_ID value.
... CONNECT BY PRIOR employee_id = manager_id
AND salary > 15000;
To qualify as a child row, a row must have a MANAGER_ID value equal to the EMPLOYEE_ID
value of the parent row and must have a SALARY value greater than $15,000.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 9
Cas Training
Level 1
root/
parent
King
Kochhar
De Haan
Mourgos
Zlotkey Hartstein
Level 2
parent/
child/leaf
a
s
a
) hLevel 3
s
Fay
Whalen Higgins Hunold Rajs Davies
Matos Vargas
e
a idchild/leaf
eparent/
u
g
ta t Gu
s
e
g den
@
Level 4
a Taylor
tu Grant
rAbel
Gietz Ernst
Lorentz
r
S
a
leaf
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de with
RankingoRows
sthe LEVEL Pseudocolumn
n
g
a
i
r
-t show the rank or level of a row in the hierarchy by using the LEVEL
Ican oexplicitly
You
n
n
pseudocolumn.
This will make your report more readable. The forks where one or more
branches split away from a larger branch are called nodes, and the very end of a branch is called
a leaf or leaf node. The diagram in the slide shows the nodes of the inverted tree with their
LEVEL values. For example, employee Higgens is a parent and a child, whereas employee
Davies is a child and a leaf.
LEVEL Pseudocolumn
Value
1
2
3
In the slide, King is the root or parent (LEVEL = 1). Kochhar, De Haan, Mourgos, Zlotkey,
Hartstein, Higgens, and Hunold are children and also parents (LEVEL = 2). Whalen, Rajs,
Davies, Matos, Vargas, Gietz, Ernst, Lorentz, Abel, Taylor, Grant, and Fay are children and
leaves (LEVEL = 3 and LEVEL = 4).
Note: A root node is the highest node within an inverted tree. A child node is any nonroot node.
A parent node is any node that has children. A leaf node is any node without children. The
number of levels returned by a hierarchical query may be limited by available user memory.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 10
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sferaReports Using LEVEL and LPAD
d
Formatting
Hierarchical
anare assigned level numbers from the root. Use the LPAD function in
igo in-atrtree
Inodes
The
nonwith the LEVEL pseudocolumn to display a hierarchical report as an indented tree.
conjunction
In the example in the slide:
LPAD(char1,n [,char2]) returns char1, left-padded to length n with the sequence
of characters in char2. The argument n is the total length of the return value as it is
displayed on your terminal screen.
LPAD(last_name, LENGTH(last_name)+(LEVEL*2)-2,'_')defines the
display format
char1 is the LAST_NAME , n the total length of the return value, is length of the
LAST_NAME +(LEVEL*2)-2, and char2 is '_'.
That is, this tells SQL to take the LAST_NAME and left-pad it with the '_' character until the
length of the resultant string is equal to the value determined by
LENGTH(last_name)+(LEVEL*2)-2.
For King, LEVEL = 1. Therefore, (2 * 1) 2 = 2 2 = 0. So King does not get padded with
any '_' character and is displayed in column 1.
For Kochhar, LEVEL = 2. Therefore, (2 * 2) 2 = 4 2 = 2 . So Kochhar gets padded with 2
'_' characters and is displayed indented.
The rest of the records in the EMPLOYEES table are displayed similarly.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 11
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 12
Cas Training
Pruning Branches
a
s
a
)h
s
e
a ide
u
g
u
a
G
Whalen estHiggins
Whalen
Higgins
t
g den
@
ra Stu
r
a
leg e this
i
(
z
Gietz
Gietzle
us
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
de nsfe
Pruning o
Branches
ig use -the
traWHERE and CONNECT BY clauses to prune the tree (that is, to control which
Ican
You
n
norows are displayed). The predicate you use acts as a Boolean condition.
nodes or
Kochhar
Kochhar
Examples
Starting at the root, walk from the top down, and eliminate employee Higgins in the result, but
process the child rows.
SELECT
FROM
WHERE
START
CONNECT
Starting at the root, walk from the top down, and eliminate employee Higgins and all child rows.
SELECT
FROM
START
CONNECT
AND
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 13
Cas Training
Summary
In this lesson, you should have learned that:
You can use hierarchical queries to view a hierarchical
relationship between rows in a table
You specify the direction and starting point of the query
You can eliminate nodes or branches by pruning
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
an queries to retrieve data based on a natural hierarchical relationship
igouse -hierarchical
r
t
Ican
You
n
no
between
rows in a table. The LEVEL pseudocolumn counts how far down a hierarchical tree you
have traveled. You can specify the direction of the query using the CONNECT BY PRIOR clause.
You can specify the starting point using the START WITH clause. You can use the WHERE and
CONNECT BY clauses to prune the tree branches.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II F - 14
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this appendix, you should be able to do the
following:
Describe the type of problems that are solved by using
SQL to generate SQL
Write a script that generates a script of DROP TABLE
statements
Write a script that generates a script of INSERT INTO
statements
has
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
o tran
igappendix,
- you learn how to write a SQL script to generate a SQL script.
InIthis
non
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 2
Cas Training
a
s
a
Data dictionary
)h
SQL
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
eg this
lscript
i
(
SQL
e
z
s
e
l
u
nz se to
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Generate
d
Using SQL
to
o trans SQL
g
i
I can obena- powerful tool to generate other SQL statements. In most cases, this involves
SQL
writingna script file. You can use SQL from SQL to:
Avoid repetitive coding
Access information from the data dictionary
Drop or re-create database objects
Generate dynamic predicates that contain run-time parameters
The examples used in this lesson involve selecting information from the data dictionary. The
data dictionary is a collection of tables and views that contain information about the database.
This collection is created and maintained by the Oracle server. All data dictionary tables are
owned by the SYS user. Information stored in the data dictionary includes names of Oracle
server users, privileges granted to users, database object names, table constraints, and audit
information. There are four categories of data dictionary views. Each category has a distinct
prefix that reflects its intended use.
Prefix
Description
USER_
ALL_
DBA_
Contains details of objects to which the user has been granted access rights, in addition to
objects owned by the user
Contains details of users with DBA privileges to access any object in the database
V$_
Stores information about database server performance and locking; available only to the DBA
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 3
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
A Basic o
Script
ig -intrathe slide produces a report with CREATE TABLE statements from every table
Iexample
The
n
noEach
you own.
CREATE TABLE statement produced in the report includes the syntax to create a
table using the table name with a suffix of _test and having only the structure of the
corresponding existing table. The old table name is obtained from the TABLE_NAME column of
the data dictionary view USER_TABLES.
The next step is to enhance the report to automate the process.
Note: You can query the data dictionary tables to view various database objects that you own.
The data dictionary views frequently used include:
USER_TABLES: Displays description of the users own tables
USER_OBJECTS: Displays all the objects owned by the user
USER_TAB_PRIVS_MADE: Displays all grants on objects owned by the user
USER_COL_PRIVS_MADE: Displays all grants on columns of objects owned by the user
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 4
Cas Training
a
s
a
)h
s
e
a ide
u
g
SET FEEDBACK ON
u
tavariables
G
s
t
SET PAGESIZE 24
Set system
e
g den
@
SET ECHO ON
back
a toSthe
tu default
rvalue.
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LEnvironment
era
f
d
s
Controlling
the
an statements that are generated, you must capture them in a file that can then
igo -trSQL
ToI
executenthe
o
be run. n
You must also plan to clean up the output that is generated and make sure that you
SQL statement
suppress elements such as headings, feedback messages, top titles, and so on. In SQL Developer,
you can save these statements to a script. To save the contents of the Enter SQL Statement box,
click the Save icon or use the File > Save menu item. Alternatively, you can right-click in the
Enter SQL Statement box and select the Save File option from the drop-down menu.
Note: Some of the SQL*Plus statements are not supported by SQL Worksheet. For the complete
list of SQL*Plus statements that are supported, and not supported by SQL Worksheet, refer to
the topic titled SQL*Plus Statements Supported and Not Supported in SQL Worksheet in the
SQL Developer online Help.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 5
Cas Training
a
s
a
)h
s
e
a ide
u
SET FEEDBACK ON
g
ta t Gu
s
SET PAGESIZE 24
e
g den
SET ECHO ON
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
e Picture
d
The Complete
o trans
g
i
Ioutput
The
nof- the command in the slide is saved into a file called dropem.sql in SQL
o
n
Developer. To save the output into a file in SQL Developer, you use the Save File option under
the Script Output pane. The dropem.sql file contains the following data. This file can now be
started from SQL Developer by locating the script file, loading it, and executing it.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 6
Cas Training
SELECT
'INSERT INTO departments_test VALUES
(' || department_id || ', ''' || department_name ||
''', ''' || location_id || ''');'
s
a
h
AS "Insert Statements Script"
s)
e
FROM
departments
a ide
u
g
/
u
ta
es ent G
g
ra@ Stud
r
a
SET PAGESIZE 24
leg eONthis
i
(
SET HEADING ON ECHO ON FEEDBACK
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Contents
s
DumpingoTable
to a File
n
g
a
i
r
I onit-tis useful to have the values for the rows of a table in a text file in the format of an
Sometimes,
n INTO VALUES statement. This script can be run to populate the table in case the table
INSERT
has been dropped accidentally.
The example in the slide produces INSERT statements for the DEPARTMENTS_TEST table,
captured in the data.sql file using the Save File option in SQL Developer.
The contents of the data.sql script file are as follows:
INSERT
(10,
INSERT
(20,
INSERT
(50,
INSERT
(60,
...
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 7
Cas Training
Source
Result
'''X'''
'X'
''''
'
''''||department_name||'''' 'Administration'
a
s
a
)h
s
e
''');'
');
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Contents
s
DumpingoTable
to a File (continued)
n
g
a
i
r
-t noticed the large number of single quotation marks in the previous slide. A set of
Imayohave
You
n
n quotation marks produces one single quotation mark in the final statement. Also
four single
''', '''
','
remember that character and date values must be surrounded by quotation marks.
Within a string, to display one single quotation mark, you need to prefix it with another single
quotation mark. For example, in the fifth example in the slide, the surrounding quotation marks
are for the entire string. The second quotation mark acts as a prefix to display the third quotation
mark. Thus, the result is one single quotation mark followed by the parenthesis, followed by the
semicolon.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 8
Cas Training
a
s
a
)h
s
e
a ide
u
g
u
SELECT last_name FROM employees &dyn_where_clause; sta
G
t
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eDynamic
d
Generating
a
o trans Predicate
g
i
Iexample
The
n-in the slide generates a SELECT statement that retrieves data of all employees in a
o
n
department who were hired on a specific day. The script generates the WHERE clause
dynamically.
Note: After the user variable is in place, you must use the UNDEFINE command to delete it.
The first SELECT statement prompts you to enter the department number. If you do not enter
any department number, the department number is treated as null by the DECODE function, and
the user is then prompted for the hire date. If you do not enter any hire date, the hire date is
treated as null by the DECODE function and the dynamic WHERE clause that is generated is also
a null, which causes the second SELECT statement to retrieve all rows from the EMPLOYEES
table.
Note: The NEW_V[ALUE] variable specifies a variable to hold a column value. You can
reference the variable in TTITLE commands. Use NEW_VALUE to display column values or the
date in the top title. You must include the column in a BREAK command with the SKIP PAGE
action. The variable name cannot contain a pound sign (#). NEW_VALUE is useful for
master/detail reports in which there is a new master record for each page.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 9
Cas Training
a
s
a
)h
s
e
a which
e will be
u
d
The returned string becomes the value of the DYN_WHERE_CLAUSEgvariable,
i
ta t Gu
s
used in the second SELECT statement.
e
g den
@
Note: Use SQL*Plus for these examples.
ra Stu
r
a
leg e this
i
(
ez o the
When the first example in the slide isexecuted,
l
ususer is prompted for the values for DEPTNO
z
t
and HIREDATE:
on nse
G
ce
ra
i
r
l
a
eg rable
L
de nsfe
o
ig -tvalue
ra for MY_COL is generated:
Ifollowing
The
n
no
When the second example in the slide is executed, the following output is generated:
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 10
Cas Training
Summary
In this appendix, you should have learned that:
You can write a SQL script to generate another SQL script
Script files often use the data dictionary
You can capture the output in a file
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Summary
gobe used
aton generate SQL scripts. These scripts can be used to avoid repetitive coding,
r
t
Iican
SQL
on
drop ornre-create objects, get help from the data dictionary, and generate dynamic predicates that
contain run-time parameters.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II G - 11
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Objectives
After completing this lesson, you should be able to do the
following:
List the major database architectural components
Describe the background processes
Explain the memory structures
Correlate the logical and physical storage structures
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Objectives
go provides
an an overview of the Oracle Database architecture. You learn about the
r
t
Iilesson
This
noandn logical structures and various components of the Oracle Database and their
physical
functions.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 2
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Architecture:
era
f
d
s
Oracle Database
Overview
o tran
g
i
A Idatabase
nis-a collection of data treated as a unit. The purpose of a database is to store and
o
n
retrieve related information.
An Oracle Database reliably manages a large amount of data in a multiuser environment so that
many users can concurrently access the same data. This is accomplished while delivering high
performance. At the same time, it prevents unauthorized access and provides efficient solutions
for failure recovery.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 3
Cas Training
Memory structures
SGA
Database
buffer
cache
User
process
Shared pool
Redo log
buffer
Server
process
Processes
DBWn
CKPT
LGWR
SMON
PMON
Library
cache
Data dictionary
cache
ARCn
RECO Others
a
s
a
)h
s
e
a ide
u
Storage structures
g
ta t Gu
s
e
g den
@
ra Stu
r
a
s
leg e thiControl
i
(
Online redo
zData files
s
e
files
log files
l
u
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe Structures
de nServer
s
Oracle Database
o
ig Database
tra consists of two main componentsthe instance and the database.
IOracle
The
n
noinstance consists of the System Global Area (SGA), which is a collection of memory
The
Database
structures, and the background processes that perform tasks within the database. Every time
an instance is started, the SGA is allocated and the background processes are started.
The database consists of both physical structures and logical structures. Because the
physical and logical structures are separate, the physical storage of data can be managed
without affecting access to logical storage structures. The physical storage structures
include:
- The control files where the database configuration is stored
- The redo log files that have information required for database recovery
- The data files where all data is stored
An Oracle instance uses memory structures and processes to manage and access the database
storage structures. All memory structures exist in the main memory of the computers that
constitute the database server. Processes are jobs that work in the memory of these computers. A
process is defined as a thread of control or a mechanism in an operating system that can run a
series of steps.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 4
Cas Training
a
s
a
)h
s
e
Session
SQL> Select
User
a ide
u
User
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez Connection
l
us
o
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
e the sDatabase
fe
dto
Connecting
o
n
ig -tra in the database, the user needs to connect to the database using a tool
ToI
access information
on
(such asnSQL*Plus). After the user establishes connection, a session is created for the user.
Connection and session are closely related to user process but are very different in meaning.
A connection is a communication pathway between a user process and an Oracle Database
instance. A communication pathway is established using available interprocess communication
mechanisms or network software (when different computers run the database application and
Oracle Database, and communicate through a network).
A session represents the state of a current user login to the database instance. For example, when
a user starts SQL*Plus, the user must provide a valid username and password, and then a session
is established for that user. A session lasts from the time the user connects until the time the user
disconnects or exits the database application.
In the case of a dedicated connection, the session is serviced by a permanent dedicated process.
In the case of a shared connection, the session is serviced by an available server process selected
from a pool, either by the middle tier or by Oracle shared server architecture.
Multiple sessions can be created and exist concurrently for a single Oracle Database user using
the same username, but through different applications, or multiple invocations of the same
application.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 5
Cas Training
Server
process
Instance
SGA
Database
buffer
cache
DBWn CKPT
Shared pool
Redo log
buffer
Library
cache
Data dictionary
cache
RECO Others
User
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LansOracle
era Database
f
d
Interacting
with
an describes Oracle Database operations at the most basic level. It
igo -texample
r
Ifollowing
The
noann Oracle Database configuration where the user and associated server process are on
illustrates
separate computers, connected through a network.
1. An instance has started on a node where Oracle Database is installed, often called the host
or database server.
2. A user starts an application spawning a user process. The application attempts to establish a
connection to the server. (The connection may be local, client server, or a three-tier
connection from a middle tier.)
3. The server runs a listener that has the appropriate Oracle Net Services handler. The server
detects the connection request from the application and creates a dedicated server process
on behalf of the user process.
4. The user runs a DML-type SQL statement and commits the transaction. For example, the
user changes the address of a customer in a table and commits the change.
5. The server process receives the statement and checks the shared pool (an SGA component)
for any shared SQL area that contains a similar SQL statement. If a shared SQL area is
found, then the server process checks the users access privileges to the requested data, and
the existing shared SQL area is used to process the statement. If not, then a new shared SQL
area is allocated for the statement, so it can be parsed and processed.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 6
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 7
Cas Training
Server
process 1
PGA
Server
process 2
Library
cache
Background
processes
PGA
Shared
SQL area
DB structures
Memory
- Process
- Storage
Data Dictionary
cache
PGA
SGA
Other
a
s
a
)h
Shared pool
Redo log
s
e
buffer
a ide
u
Free
g
u
I/O Buffer ta
Database buffer
G
s
memory
t
e
n
g dRequest
cache
e
@
Response
raqueueStu queue
r
a
Java
Streams
leg e this Large pool
i
pool
pool
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e LStructures
era
f
d
s
Oracle Memory
o tran
IigDatabase
Oracle
n- creates and uses memory structures for various purposes. For example, memory
o
n
stores program code being run, data shared among users, and private data areas for each
connected user.
Two basic memory structures are associated with an instance:
The System Global Area (SGA) is a group of shared memory structures, known as SGA
components, that contain data and control information for one Oracle Database instance.
The SGA is shared by all server and background processes. Examples of data stored in the
SGA include cached data blocks and shared SQL areas.
The Program Global Areas (PGA) are memory regions that contain data and control
information for a server or background process. A PGA is nonshared memory created by
Oracle Database when a server or background process is started. Access to the PGA is
exclusive to the server process. Each server process and background process has its own
PGA.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 8
Cas Training
a
u
d
i
g
The Oracle database uses initialization parameters to create and configure
u structures.
a memory
t
G
s
t
e
For example, the SGA_TARGET parameter specifies the totalgsize of the
nSGA components. If
e
@
d
you set SGA_TARGET to 0, Automatic Shared Memory
Management
is
tu disabled.
ra
r sS
a
g
le e thi
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 9
Cas Training
Process Architecture
User process:
DB structures
- Memory
Process
- Storage
Database processes:
Server process: Connects to the Oracle instance and is
started when a user establishes a session
Background processes: Are started when an Oracle instance
is started
Instance
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
PGA
@
Background
a Stu processes
r
r
a
User
Server
g LGWR
DBWnleCKPT
his SMON PMON
process
process
i
t
(
e
RECO
ARCn
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
ProcessoArchitecture
ig -tinraan Oracle Database server can be categorized into two major groups:
Iprocesses
The
n
noprocesses
User
that run the application or Oracle tool code
SGA
Others
Oracle Database processes that run the Oracle database server code. These include server
processes and background processes.
When a user runs an application program or an Oracle tool such as SQL*Plus, Oracle Database
creates a user process to run the users application. The Oracle Database also creates a server
process to execute the commands issued by the user process. In addition, the Oracle server also
has a set of background processes for an instance that interact with each other and with the
operating system to manage the memory structures and asynchronously perform I/O to write
data to disk, and perform other required tasks.
The process structure varies for different Oracle Database configurations, depending on the
operating system and the choice of Oracle Database options. The code for connected users can
be configured as a dedicated server or a shared server.
With dedicated server, for each user, the database application is run by a user process,
which is served by a dedicated server process that executes Oracle database server code.
A shared server eliminates the need for a dedicated server process for each connection. A
dispatcher directs multiple incoming network session requests to a pool of shared server
processes. A shared server process serves any client request.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 10
Cas Training
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 11
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
DBWn
s
e
g den
@
Database writer
ra StuData files
Database buffer
r
a
process
cache
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Process
era (DBWn)
f
d
s
Database
Writer
an process (DBWn) writes the contents of buffers to data files. The DBWn
igo -writer
r
t
Idatabase
The
n
noare
processes
responsible for writing modified (dirty) buffers in the database buffer cache to
disk. Although one database writer process (DBW0) is adequate for most systems, you can
configure additional processes (DBW1 through DBW9 and DBWa through DBWj) to improve
write performance if your system modifies data heavily. These additional DBWn processes are
not useful on uniprocessor systems.
When a buffer in the database buffer cache is modified, it is marked dirty and is added to the
LRUW list of dirty buffers that is kept in SCN order, thereby matching the order of Redo
corresponding to these changed buffers that is written to the Redo logs. When the number of
available buffers in the buffer cache falls below an internal threshold such that server processes
find it difficult to obtain available buffers, DBWn writes dirty buffers to the data files in the
order that they were modified by following the order of the LRUW list.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 12
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
LGWR
s
e
g den
@
u log files
tRedo
Log writerrra
Redo log buffer
S
a
process
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L s(LGWR)
era
f
d
Log Writer
Process
an (LGWR) is responsible for redo log buffer management by writing the
igowriter-tprocess
r
Ilog
The
on
redo lognbuffer entries to a redo log file on disk. LGWR writes all redo entries that have been
copied into the buffer since the last time it wrote.
The redo log buffer is a circular buffer. When LGWR writes redo entries from the redo log
buffer to a redo log file, server processes can then copy new entries over the entries in the redo
log buffer that have been written to disk. LGWR normally writes fast enough to ensure that
space is always available in the buffer for new entries, even when access to the redo log is
heavy.
LGWR writes one contiguous portion of the buffer to disk. LGWR writes:
When a user process commits a transaction
When the redo log buffer is one-third full
Before a DBWn process writes modified buffers to disk, if necessary
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 13
Cas Training
Checkpoint Process
a
s
a
)h
s
e
a ide
u
Checkpoint
g
ta t Gu
process
s
e
g den
@
ra Stu
r
a
leg e this Data files
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
ra
e L sfe(CKPT)
d
Checkpoint
Process
o
n
ig n-tisraa data structure that defines a system change number (SCN) in the redo thread of
A Icheckpoint
no Checkpoints are recorded in the control file and each data file header, and are a
a database.
CKPT
Control
file
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 14
Cas Training
a
s
a
)h
s
e
a ide
u
System monitor
g
ta t Gu
process
s
e
g den
@
tu
raTemporary
r
S
a
is
leg e thsegment
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Process
era (SMON)
f
d
s
System Monitor
an process (SMON) performs recovery, if necessary, at instance startup.
igo monitor
r
t
Isystem
The
non
SMON
Instance
SMON is also responsible for cleaning up temporary segments that are no longer in use. If any
terminated transactions were skipped during instance recovery because of file-read or offline
errors, SMON recovers them when the tablespace or file is brought back online. SMON checks
regularly to see whether it is needed. Other processes can call SMON if they detect a need for it.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 15
Cas Training
a
s
a
)h
s
e
a ide
u
g
PMON
User
ta t Gu
s
e
g den
Failed user @
ra Stu
r
process
Process monitor
a
process
leg e this
i
Database buffer
(
z
s
e
cache
l to u
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe (PMON)
de nProcess
s
ProcessoMonitor
ig monitor
tra (PMON) performs process recovery when a user process fails. PMON is
Iprocess
The
n
no for cleaning up the database buffer cache and freeing resources that the user process
responsible
was using. For example, it resets the status of the active transaction table, releases locks, and
removes the process ID from the list of active processes.
PMON periodically checks the status of dispatcher and server processes, and restarts any that
have stopped running (but not any that Oracle Database has terminated intentionally). PMON
also registers information about the instance and dispatcher processes with the network listener.
Like SMON, PMON checks regularly to see whether it is needed and can be called if another
process detects the need for it.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 16
Cas Training
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
Parameter file
@
Password file
ra Stu
r
a
Network files
leg e this
i
(
Alert and trace files
ez oBackup
l
us files Archived log files
z
t
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
fe Architecture
de nStorage
s
Oracle Database
o
ig that-constitute
tra
Ifiles
The
an Oracle database are organized into the following:
n
o
n
Control files: Contain data about the database itself (that is, physical database structure
Data files
Control
files
Online redo
log files
information). These files are critical to the database. Without them, you cannot open data
files to access the data within the database.
Data files: Contain the user or application data of the database, as well as metadata and the
data dictionary
Online redo log files: Allow for instance recovery of the database. If the database server
crashes and does not lose any data files, then the instance can recover the database with the
information in these files.
The following additional files are important to the successful running of the database:
Backup files: Are used for database recovery. You typically restore a backup file when a
media failure or user error has damaged or deleted the original file.
Archived log files: Contain an ongoing history of the data changes (redo) that are generated
by the instance. Using these files and a backup of the database, you can recover a lost data
file. That is, archive logs enable the recovery of restored data files.
Parameter file: Is used to define how the instance is configured when it starts up
Password file: Allows sysdba/sysoper/sysasm to connect remotely to the database
and perform administrative tasks
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 17
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 18
Cas Training
Physical
Database
Schema
Tablespace
Data file
Segment
s
a
h
s)
e
a ide
u
Extent
g
ta t Gu
s
e
g den
@
rra s Stu
Oracle data ga
OS block
le e thi
i
(
block
z
le to us
z
on nse
G
ce 2009, Oracle. All rights reserved.
ra Copyright
i
r
l
a
eg rable
L
feDatabase Structures
dePhysical
s
Logical and
o
n
ig Database
tra has logical and physical storage structures.
AnI
Oracle n
no
Tablespaces
A database is divided into logical storage units called tablespaces, which group related logical
structures together. For example, tablespaces commonly group all of an applications objects to
simplify some administrative operations. You may have a tablespace for application data and an
additional one for application indexes.
Databases, Tablespaces, and Data Files
The relationship among databases, tablespaces, and data files is illustrated in the slide. Each
database is logically divided into one or more tablespaces. One or more data files are explicitly
created for each tablespace to physically store the data of all logical structures in a tablespace. If
it is a TEMPORARY tablespace, instead of a data file, then the tablespace has a temporary file.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 19
Cas Training
a
information.
gu uide
a
t
Segments
es ent G
g
@ a tsegment.
The level of logical database storage above an extentris
ud A segment is a set of
racalled
S
a
extents allocated for a certain logical structure.eFor
his the different types of segments
l g example,
i
t
(
include:
e
z
enon-indexed-organized
l
us
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 20
Cas Training
)
s
e
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eSQL
d
Processing
a
o transStatement
g
i
Iall theoncomponents
Not
of an Oracle instance are used to process SQL statements. The user and
n
server processes are used to connect a user to an Oracle instance. These processes are not part of
the Oracle instance, but are required to process a SQL statement.
Some of the background processes, SGA structures, and database files are used to process SQL
statements. Depending on the type of SQL statement, different components are used:
Queries require additional processing to return rows to the user.
Data manipulation language (DML) statements require additional processing to log the
changes made to the data.
Commit processing ensures that the modified data in a transaction can be recovered.
Some required background processes do not directly participate in processing a SQL statement,
but are used to improve performance and to recover the database. For example, the optional
Archiver background process, ARCn, is used to ensure that a production database can be
recovered.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 21
Cas Training
Processing a Query
Parse:
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eQuery
d
Processing
a
o trans
g
i
I are
Queries
from other types of SQL statements because, if successful, they return data
ndifferent
o
n
as results. Other statements simply return success or failure, whereas a query can return one row
or thousands of rows.
There are three main stages in the processing of a query:
Parse
Execute
Fetch
During the parse stage, the SQL statement is passed from the user process to the server process,
and a parsed representation of the SQL statement is loaded into a shared SQL area.
During parse, the server process performs the following functions:
Searches for an existing copy of the SQL statement in the shared pool
Validates the SQL statement by checking its syntax
Performs data dictionary lookups to validate table and column definitions
The execute stage executes the statement using the best optimizer approach and the fetch
retrieves the rows back to the user.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 22
Cas Training
Shared Pool
a
s
a
)h
s
e
cache
a ide
u
g
ta t Gu
s
e
g den
@
Data dictionary
ra Stu
r
a
cache
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Shared Pool
o tran
- stage, the server process uses the area in the SGA known as the shared pool to
Iigtheonparse
During
n
compile the SQL statement. The shared pool has two primary components:
Library
Library cache
Data dictionary cache
Library Cache
The library cache stores information about the most recently used SQL statements in a memory
structure called a shared SQL area. The shared SQL area contains:
The text of the SQL statement
The parse tree, which is a compiled version of the statement
The execution plan, with steps to be taken when executing the statement
The optimizer is the function in the Oracle server that determines the optimal execution plan.
If a SQL statement is reexecuted and a shared SQL area already contains the execution plan for
the statement, then the server process does not need to parse the statement. The library cache
improves the performance of applications that reuse SQL statements by reducing parse time and
memory requirements. If the SQL statement is not reused, it is eventually aged out of the library
cache.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 23
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 24
Cas Training
Database buffer
cache
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L Cache
era
f
d
s
Database
Buffer
o tran
Iiga query
When
n- is processed, the server process looks in the database buffer cache for any blocks
o
n
it needs. If the block is not found in the database buffer cache, the server process reads the block
from the data file and places a copy in the buffer cache. Because subsequent requests for the
same block may find the block in memory, the requests may not require physical reads. The
Oracle server uses a least recently used algorithm to age out buffers that have not been accessed
recently to make room for new blocks in the buffer cache.
Sizing the Database Buffer Cache
The size of each buffer in the buffer cache is equal to the size of an Oracle block, and it is
specified by the DB_BLOCK_SIZE parameter. The number of buffers is equal to the value of
the DB_BLOCK_BUFFERS parameter.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 25
Cas Training
Is not shared
Is writable only by the server process
Contains:
Sort area
Session information
Cursor state
Stack space
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
Server
e
n
g process
e
@
d
ra Stu
r
a
PGA
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
de Area
s (PGA)
ProgramoGlobal
n
g
a
i
r
-t Area (PGA) is a memory region that contains data and control information
A IProgram
Global
n
o
n process. It is a nonshared memory created by Oracle when a server process is
for a server
started. Access to it is exclusive to that server process, and is read and written only by the Oracle
server code acting on behalf of it. The PGA memory allocated by each server process attached to
an Oracle instance is referred to as the aggregated PGA memory allocated by the instance.
In a dedicated server configuration, the PGA of the server includes the following components:
Sort area: Is used for any sorts that may be required to process the SQL statement
Session information: Includes user privileges and performance statistics for the session
Cursor state: Indicates the stage in the processing of the SQL statements that are currently
used by the session
Stack space: Contains other session variables
The PGA is allocated when a process is created, and deallocated when the process is terminated.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 26
Cas Training
User
process
Shared pool
Database
buffer
cache
Redo log
buffer
UPDATE
employees ...
Server
process
a
s
a
h
Redo s)
Data
Control
e
logufiles
a ide
files
files
g
ta t Gu
s
e
g den
1
@
ra Stu
r
a
leg e this
i
(
ez o us Database
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L fera
eDML
d
Processing
a
o transStatement
g
i
manipulation
A Idata
language (DML) statement requires only two phases of processing:
no
n
Parse is the same as the parse phase used for processing a query.
Execute requires additional processing to make data changes.
DML Execute Phase
To execute a DML statement:
If the data and rollback blocks are not already in the buffer cache, the server process reads
them from the data files into the buffer cache
The server process places locks on the rows that are to be modified
In the redo log buffer, the server process records the changes to be made to the rollback and
data blocks
The rollback block changes record the values of the data before it is modified. The rollback
block is used to store the before image of the data, so that the DML statements can be
rolled back if necessary.
The data block changes record the new values of the data
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 27
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 28
Cas Training
a
s
a
Redo log buffer
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
e L sfera
d
Redo Log
Buffer
anrecords most of the changes made to data file blocks in the redo log buffer,
igo process
r
t
Iserver
The
n
noa part
which is
of the SGA. The redo log buffer has the following characteristics:
Its size in bytes is defined by the LOG_BUFFER parameter.
It records the block that is changed, the location of the change, and the new value in a redo
entry. A redo entry makes no distinction between the types of block that is changed; it only
records which bytes are changed in the block.
The redo log buffer is used sequentially, and changes made by one transaction may be
interleaved with changes made by other transactions.
It is a circular buffer that is reused after it is filled, but only after all the old redo entries are
recorded in the redo log files.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 29
Cas Training
Rollback Segment
Old image
Rollback segment
New image
a
s
a
)h
Table
s
e
a ide
u
g
ta t Gu
s
e
g den
@
tu
ra DMLSstatement
r
a
leg e this
i
(
ez o us
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
RollbackoSegment
traachange, the server process saves the old data value in a rollback segment. This
Iigmaking
Before
n
o
beforenimage is used to:
Undo the changes if the transaction is rolled back
Provide read consistency by ensuring that other transactions do not see uncommitted
changes made by the DML statement
Recover the database to a consistent state in case of failures
Rollback segments, such as tables and indexes, exist in data files, and rollback blocks are
brought into the database buffer cache as required. Rollback segments are created by the DBA.
Changes to rollback segments are recorded in the redo log buffer.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 30
Cas Training
COMMIT Processing
1
Instance
SGA
Server
process
Shared pool
Database
buffer
cache
Redo log
buffer
3
DBWn
LGWR
a
s
a
h
Redos)
User
Data
Control
e
log
afiles
process
e2
files
files
u
d
i
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us Database
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
L
a
de nsfer
COMMIT o
Processing
ig server
tra uses a fast COMMIT mechanism that guarantees that the committed changes
IOracle
The
n
o
can be n
recovered in case of instance failure.
System Change Number
Whenever a transaction commits, the Oracle server assigns a commit system change number
(SCN) to the transaction. The SCN is monotonically incremented and is unique within the
database. It is used by the Oracle server as an internal time stamp to synchronize data and to
provide read consistency when data is retrieved from the data files. Using the SCN enables the
Oracle server to perform consistency checks without depending on the date and time of the
operating system.
Steps in Processing COMMITs
When a COMMIT is issued, the following steps are performed:
1. The server process places a commit record, along with the SCN, in the redo log buffer.
2. LGWR performs a contiguous write of all the redo log buffer entries up to and including
the commit record to the redo log files. After this point, the Oracle server can guarantee that
the changes will not be lost even if there is an instance failure.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 31
Cas Training
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 32
Cas Training
PMON
RECO
SGA
Shared pool
Database
buffer
cache
Redo log
buffer
DBWn
CKPT
PGA
Server
process
Others
Library
cache
Data dictionary
cache
LGWR
ARCn
a
s
a
)h
s
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu Archived
User
r
a
Control
process
isredo log files
hfiles
leg eOnline
files
i
t
log
(
Data files
ez o us
Database
l
nz se t
o
en 2009, Oracle. All rights reserved.
a GCopyright
c
r
i
r
l
a ble
g
e
etheL Oracle
eraDatabase Architecture
f
d
s
Summary
of
igo Database
tran comprises an instance and its associated database:
AnI
Oracle n
o
Anninstance comprises the System Global Area (SGA) and the background processes
- SGA: Database buffer cache, redo log buffer, shared pool, and so on
- Background processes: SMON, PMON, DBWn, CKPT, LGWR, and so on
A database comprises storage structures:
- Logical: Tablespaces, schemas, segments, extents, and Oracle block
- Physical: Data files, control files, redo log files
When a user accesses the Oracle Database through an application, a server process
communicates with the instance on behalf of the user process.
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Oracle Database 11g: SQL Fundamentals II H - 33
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
Index
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.
Cas Training
A
ALTER 1-13, 1-15, 1-23, 2-3, 2-4, 2-5, 2-6, 2-7, 2-8, 2-9,
2-10, 2-11, 2-12, 2-13, 2-14, 2-15, 2-18, 2-19, 2-20, 2-22, 2-23,
2-24, 2-25, 2-28, 2-32, 2-36, 2-47, 5-5, 5-7, 5-9, 5-12, 6-24,
7-24
ALTER SESSION 2-15, 5-5, 5-7, 5-9
ALTER TABLE 2-3, 2-4, 2-5, 2-6, 2-7, 2-8, 2-9, 2-10, 2-11,
2-12, 2-13, 2-14, 2-15, 2-18, 2-19, 2-20, 2-22, 2-23, 2-24, 2-25,
2-28, 2-32, 2-36, 2-47, 5-12, 6-24, 7-24
ALTER USER 1-13, 1-23
C
s
a
h
s)
Check Constraints 7-24
e
a ide
u
Conditional INSERT 4-2, 4-3, 4-11, 4-15, 4-18, 4-19, 4-20, 4-23,
g
ta t Gu
s
e
4-24, 4-25, 4-26, 4-27, 4-31, 4-37, 4-42
g den
@
tu
raF-13, F-14
CONNECT BY 6-11, F-5, F-6, F-7, F-8, F-9, F-11,
r
S
a
s
eg F-13,
hiF-14
lF-11,
CONNECT BY PRIOR F-5, F-7, F-8, F-9,
i
t
(
e
s 3-10, 3-14,
ez 2-21,
l
u3-3,
Constraint 2-12, 2-13, 2-18, 2-19,2-20,
o
z
t
on nse
3-15, 3-17, 3-25
G
a
ce
ri-24
i
r
l
Conversion functions
a
le
b
Leg fe6-15
a
Correlatede
Subquery
r
d
s
o a Database
Creating
an Connection i-13, C-7, C-8
r
t
ig E-2,
ICUBE
non E-6, E-7, E-9, E-10, E-11, E-13, E-14, E-17, E-18,
Cascading Constraints 2-22, 2-23
D
Database Architecture H-3, H-33
Datetime 5-11
Daylight Saving 5-29, 5-30
DBTIMEZONE 5-2, 5-9, 5-23, 5-31, 5-33
Unauthorized reproduction
or distribution
prohibited.
Copyright II2009,
Oracle
Oracle
Database 11g:
SQL Fundamentals
Index
- 2 and/or its affiliates.
Cas Training
D
DEFAULT DIRECTORY 2-40, 2-41, 2-42, 2-45
Deferring Constraints 2-15, 2-17
Disabling Constraints 2-19
DROP TABLE 2-31, 2-35, G-2
Dropping a column 2-8
E
Enabling Constraints 2-20
External Table 2-38, 2-39, 2-40, 2-41, 2-42, 2-43, 2-45
EXTRACT 5-2, 5-3, 5-14, 5-21, 5-22, 5-31, 5-32, 5-34
F
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
G
@
ra Stu
r
a
Greenwich Mean Time 5-4, 5-7
hisE-7,
legE-5,e E-6,
i
t
(
GROUP BY 6-11, 6-26, 6-31, 6-32, E-3,
E-4,
ez o us
l
H
HAVING i-26, i-35, 6-26, E-3, E-5, E-7, E-9, E-11
Hierarchical Queries F-5
I
INSERT i-27, 1-15, 1-22, 2-16, 2-17, 2-43, 3-5, 4-2, 4-3, 4-4,
4-7, 4-8, 4-9, 4-10, 4-11, 4-12, 4-13, 4-14, 4-15, 4-16, 4-17,
4-18, 4-19, 4-20, 4-21, 4-22, 4-23, 4-24, 4-25, 4-26, 4-27, 4-28,
4-29, 4-30, 4-31, 4-32, 4-33, 4-34, 4-36, 4-37, 4-42, 4-47, 5-13,
5-18, 5-20, 7-24, D-19, G-2, G-7, H-28
INTERVAL DAY TO SECOND 5-15, 5-17, 5-19, 5-20, 5-28
INTERVAL YEAR TO MONTH 5-15, 5-17, 5-18, 5-19, 5-27
Unauthorized reproduction
or distribution
prohibited.
Copyright II2009,
Oracle
Oracle
Database 11g:
SQL Fundamentals
Index
- 3 and/or its affiliates.
Cas Training
L
LEVEL F-5, F-10, F-11, F-12, F-14
LOCALTIMESTAMP 5-2, 5-3, 5-6, 5-7, 5-8, 5-14, 5-21, 5-31,
5-32, 5-33
LPAD F-11, F-12
M
MERGE i-27, 4-2, 4-32, 4-33, 4-34, 4-36, 4-42, 4-43
Multiple-Column Subqueries 6-4
N
Nonpairwise Comparisons 6-5
NOT IN 6-22, 6-36
s
a
O
h
s)
e
P
nz se t
o
G cen
Pseudocolumn F-10 rra
li
a
e
g
l
R
Le ferab
e
s
Ranking
F-10
o dRows
n
g
a
i
r
I on-t
REGEXP_COUNT
7-3, 7-6, 7-7, 7-11, 7-12, 7-17, 7-22, 7-23
n
REGEXP_INSTR 7-3, 7-6, 7-7, 7-11, 7-12, 7-15, 7-17, 7-18, 7-19,
7-20, 7-22
REGEXP_LIKE 7-3, 7-6, 7-7, 7-11, 7-12, 7-13, 7-17, 7-22, 7-24
REGEXP_REPLACE 7-3, 7-6, 7-7, 7-11, 7-12, 7-14, 7-17, 7-22
REGEXP_SUBSTR 7-3, 7-6, 7-7, 7-11, 7-12, 7-16, 7-17, 7-18,
7-19, 7-21, 7-22
Regular Expression Support i-6, 7-1, 7-19
Replacing Patterns 7-14
ROLLUP E-2, E-6, E-7, E-8, E-9, E-10, E-11, E-12, E-13, E-14,
E-17, E-18, E-19, E-21, E-22, E-23
Row Versions 4-48
S
Scalar Subquery 6-11
Unauthorized reproduction
or distribution
prohibited.
Copyright II2009,
Oracle
Oracle
Database 11g:
SQL Fundamentals
Index
- 4 and/or its affiliates.
Cas Training
S
Scalar Subquery 6-11
SESSIONTIMEZONE 5-2, 5-7, 5-9, 5-23, 5-31, 5-33
SET TIME_ZONE 5-5, 5-7, 5-9
SET UNUSED 2-9
SQL Developer i-2, i-3, i-7, i-9, i-10, i-11, i-12, i-13,
i-14, i-15, i-16, i-19, i-20, i-28, i-29, i-32, i-33, 1-13, 1-25,
3-30, 7-24, C-2, C-3, C-4, C-5, C-6, C-7, C-15, C-21, C-22,
C-24, C-25, C-26, C-27, C-28, C-29, C-30, C-31, C-32,
G-5, G-6, G-7
SQL Worksheet i-14, i-15, i-16, i-17, i-18, i-32, i-34, 2-48,
3-31, C-6, C-11, C-13, C-14, C-15, C-16, C-17 C-18, C-22,
C-23, C-24, C-32, C-33, G-5
s
a
h
s)
e
a ide
u
START WITH F-5, F-6, F-11, F-14
g
ta t Gu
s
Subquery 4-5, 4-6, 4-7, 4-8, 4-16, 6-4, 6-6, 6-7, 6-8,
e
g den
@
6-9, 6-11, 6-15
ra Stu
r
a
leg e this
T
i
(
ez o us
l
Time Zone 5-7, 5-8
z et
on5-3,
TIMESTAMP 2-34, 4-39, G
5-2,
5-6,
ns 5-7, 5-8, 5-10, 5-11,
e
a
c
r
r 5-21,le5-25,
li 5-26, 5-31, 5-32, 5-33, 5-34
5-12, 5-13, 5-14,
a
g
e TIME
LWITH
abZONE 5-6, 5-8, 5-10, 5-12, 5-13, 5-25, 5-26,
TIMESTAMP
r
e
e
f
o d trans
5-34
g
i
I onTO_DSINTERVAL
5-2, 5-3, 5-14, 5-21, 5-28, 5-31
n
U
Unconditional INSERT ALL 4-21, 4-22
UNION E-7, E-10, E-13, E-14, E-16, E-17, E-18, E-20, E-23
UNION ALL E-7, E-10, E-13, E-14, E-16, E-17, E-18, E-20, E-23
Using Snippets C-22, C-23
V
VERSIONS BETWEEN 4-39, 4-41
W
Walking the Tree F-6, F-7, F-8, F-9
WITH Clause 6-29, 6-30, 6-31
Unauthorized reproduction
or distribution
prohibited.
Copyright II2009,
Oracle
Oracle
Database 11g:
SQL Fundamentals
Index
- 5 and/or its affiliates.
Cas Training
s
a
h
s)
e
a ide
u
g
ta t Gu
s
e
g den
@
ra Stu
r
a
leg e this
i
(
ez o us
l
nz se t
o
a G licen
r
r
a ble
g
e
e L sfera
d
o
n
Iig on-tra
n
Unauthorized reproduction or distribution prohibited. Copyright 2009, Oracle and/or its affiliates.