Académique Documents
Professionnel Documents
Culture Documents
Fundamentals II
Electronic Presentation
D49994GC20
Edition 2.0
September 2009
Authors
Chaitanya Koratamaddi
Brian Pottle
Tulika Srivastava
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
The information contained in this document is subject to change without notice. If you find any
problems in the document, please report them in writing to: Oracle University, 500 Oracle Parkway,
Redwood Shores, California 94065 USA. This document is not warranted to be error-free.
Restricted Rights Notice
If this documentation is delivered to the United States Government or anyone using the
documentation on behalf of the United States Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these
training materials are restricted by the terms of the applicable Oracle license agreement and/or the
applicable U.S. Government contract.
Trademark Notice
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be
trademarks of their respective owners.
Editors
Amitha Narayan
Daniel Milne
Graphic Designer
Satish Bettegowda
Publisher
Veena Narasimhan
Introduction
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
Review some of the basic concepts of SQL
I-2
Lesson Agenda
I-3
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
Manipulate large data sets in the Oracle database by using
subqueries
Manage data in different time zones
Write multiple-column subqueries
Use scalar and correlated subqueries
Use the regular expression support in SQL
I-4
Course Prerequisites
The Oracle Database 11g: SQL Fundamentals I course is a
prerequisite for this course.
I-5
Course Agenda
Day 1:
Day 2:
I-6
Introduction
Controlling User Access
Managing Schema Objects
Managing Objects with Data Dictionary Views
Manipulating Large Data Sets
Managing Data in Different Time Zones
Retrieving Data by Using Subqueries
Regular Expression Support
Lesson Agenda
I-7
DEPARTMENTS
LOCATIONS
department_id
department_name
manager_id
location_id
location_id
street_address
postal_code
city
state_province
country_id
JOB_HISTORY
employee_id
start_date
end_date
job_id
department_id
JOBS
job_id
job_title
min_salary
max_salary
EMPLOYEES
employee_id
first_name
last_name
email
phone_number
hire_date
job_id
salary
commission_pct
manager_id
department_id
country_id
country_name
region_id
REGIONS
JOB_GRADES
grade_level
lowest_sal
highest_sal
I-8
COUNTRIES
region_id
region_name
I-9
Development Environments
There are two development environments for this course:
The primary tool is Oracle SQL Developer.
You can also use SQL*Plus command-line interface.
SQL Developer
I - 10
SQL *Plus
Lesson Agenda
I - 11
I - 12
Meaning
BETWEEN
...AND...
IN(set)
LIKE
I - 13
Functions
I - 14
Single-row
functions
Multiple-row
functions
Character
Single-row
functions
General
Conversion
I - 15
Number
Date
I - 16
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
Group
functions
Syntax:
SELECT select_list
FROM
table
WHERE expr operator
(SELECT select_list
FROM
table );
I - 17
Types of subqueries:
Single-row subquery
Multiple-row subquery
I - 18
Function
Description
INSERT
UPDATE
DELETE
MERGE
Lesson Agenda
I - 19
I - 20
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
I - 21
Summary
In this lesson, you should have learned the following:
The course objectives
The sample tables used in the course
I - 22
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 tables
Executing SQL statements using the SQL Worksheet
Reviewing the basic concepts of SQL
I - 23
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
1-2
Lesson Agenda
1-3
System privileges
Creating a role
Object privileges
Revoking object privileges
Database
administrator
1-4
Privileges
Database security:
System security
Data security
1-5
System Privileges
1-6
Creating Users
The DBA creates users with the CREATE USER statement.
CREATE USER user
IDENTIFIED BY
password;
CREATE USER demo
IDENTIFIED BY demo;
1-7
1-8
CREATE
CREATE
CREATE
CREATE
CREATE
SESSION
TABLE
SEQUENCE
VIEW
PROCEDURE
1-9
Lesson Agenda
1 - 10
System privileges
Creating a role
Object privileges
Revoking object privileges
What Is a Role?
Users
Manager
Privileges
Allocating privileges
without a role
1 - 11
Allocating privileges
with a role
Create a role:
1 - 12
1 - 13
Lesson Agenda
1 - 14
System privileges
Creating a role
Object privileges
Revoking object privileges
Object Privileges
Object
privilege
Table
View
ALTER
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE
1 - 15
Sequence
Object Privileges
1 - 16
GRANT
ON
TO
GRANT
ON
TO
1 - 17
select
employees
demo;
GRANT
ON
TO
WITH
select, insert
departments
demo
GRANT OPTION;
GRANT select
ON
alice.departments
TO
PUBLIC;
1 - 18
Description
ROLE_SYS_PRIVS
ROLE_TAB_PRIVS
USER_ROLE_PRIVS
USER_SYS_PRIVS
USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
USER_COL_PRIVS_MADE
USER_COL_PRIVS_RECD
1 - 19
Lesson Agenda
1 - 20
System privileges
Creating a role
Object privileges
Revoking object privileges
1 - 21
1 - 22
select, insert
departments
demo;
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.
3. Users can change their own passwords.
4. Users can view the privileges granted to them and those
that are granted on their objects.
1 - 23
Summary
In this lesson, you should have learned how to:
Differentiate system privileges from object privileges
Grant privileges on tables
Grant roles
Distinguish between privileges and roles
1 - 24
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
1 - 25
Objectives
After completing this lesson, you should be able to do the
following:
Add constraints
Create indexes
Create indexes by using the CREATE TABLE statement
2-2
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2-3
2-4
2-5
Adding a Column
2-6
Modifying a Column
2-7
Dropping a Column
Use the DROP COLUMN clause to drop columns that you no
longer need from the table:
ALTER TABLE
DROP COLUMN
2-8
dept80
job_id;
ALTER
SET
OR
ALTER
SET
TABLE <table_name>
UNUSED(<column_name> [ , <column_name>]);
TABLE <table_name>
UNUSED COLUMN <column_name> [ , <column_name>];
2-9
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2 - 11
2 - 12
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;
2 - 13
ON DELETE Clause
2 - 14
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
2 - 15
Deferring constraint on
creation
Changing a specific
constraint attribute
INITIALLY IMMEDIATE
2 - 16
Dropping a Constraint
2 - 18
Disabling Constraints
2 - 19
Enabling Constraints
ALTER TABLE
emp2
ENABLE CONSTRAINT emp_dt_fk;
2 - 20
Cascading Constraints
2 - 22
Cascading Constraints
Example:
ALTER TABLE emp2
DROP COLUMN employee_id CASCADE CONSTRAINTS;
2 - 23
2 - 24
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2 - 25
Overview of Indexes
Indexes are created:
Automatically
PRIMARY KEY creation
UNIQUE KEY creation
Manually
The CREATE INDEX statement
The CREATE TABLE statement
2 - 26
2 - 27
Function-Based Indexes
SELECT *
FROM
dept2
WHERE UPPER(department_name) = 'SALES';
2 - 29
Removing an Index
2 - 30
2 - 31
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2 - 32
SCN
2 - 33
Syntax:
FLASHBACK TABLE[schema.]table[,
[ schema.]table ]...
TO { TIMESTAMP | SCN } expr
[ { ENABLE | DISABLE } TRIGGERS ];
2 - 34
2 - 35
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2 - 36
Temporary Tables
When
session/transaction
completes
2 - 37
2 - 38
Lesson Agenda
Creating indexes:
Using the CREATE TABLE statement
Creating function-based indexes
Removing an index
2 - 39
External Tables
2 - 40
2 - 41
2 - 43
2 - 45
SELECT *
FROM oldemp
OLDEMP
2 - 47
emp.dat
2 - 48
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
2 - 49
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
2 - 50
Summary
In this lesson, you should have learned how to:
Add constraints
Create indexes
Create indexes by using the CREATE TABLE statement
2 - 51
Practice 2: Overview
This practice covers the following topics:
Altering tables
Adding columns
Dropping columns
Creating indexes
Creating external tables
2 - 52
Managing Objects
with Data Dictionary Views
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
3-2
Lesson Agenda
3-3
View information
Sequence information
Synonym information
Index information
Data Dictionary
Oracle Server
Tables containing
business data:
EMPLOYEES
DEPARTMENTS
LOCATIONS
JOB_HISTORY
...
3-4
Data dictionary
views:
DICTIONARY
USER_OBJECTS
USER_TABLES
USER_TAB_COLUMNS
...
Oracle Server
Consists of:
Base tables
User-accessible views
3-5
3-6
View Prefix
USER
Purpose
ALL
DBA
V$
Performance-related data
SELECT *
FROM
dictionary
WHERE table_name = 'USER_OBJECTS';
3-7
ALL_OBJECTS:
Query ALL_OBJECTS to see all the objects to which you
have access.
3-8
USER_OBJECTS View
3-9
Lesson Agenda
3 - 10
View information
Sequence information
Synonym information
Index information
Table Information
USER_TABLES:
DESCRIBE user_tables
SELECT table_name
FROM
user_tables;
3 - 11
Column Information
USER_TAB_COLUMNS:
DESCRIBE user_tab_columns
3 - 12
Column Information
3 - 13
Constraint Information
3 - 14
USER_CONSTRAINTS: Example
SELECT constraint_name, constraint_type,
search_condition, r_constraint_name,
delete_rule, status
FROM
user_constraints
WHERE table_name = 'EMPLOYEES';
3 - 15
Querying USER_CONS_COLUMNS
DESCRIBE user_cons_columns
3 - 16
Lesson Agenda
3 - 17
View information
Sequence information
Synonym information
Index information
View Information
DESCRIBE user_views
3 - 18
Sequence Information
DESCRIBE user_sequences
3 - 19
Confirming Sequences
3 - 20
Index Information
3 - 21
USER_INDEXES: Examples
3 - 22
Querying USER_IND_COLUMNS
DESCRIBE user_ind_columns
3 - 23
Synonym Information
DESCRIBE user_synonyms
SELECT *
FROM
user_synonyms;
3 - 24
Lesson Agenda
3 - 25
View information
Sequence information
Synonym information
Index information
3 - 26
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Copyright 2009, Oracle. All rights reserved.
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. Privileges and roles that each user has been granted
5. All of the above
3 - 27
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
USER_CONS_COLUMNS
USER_VIEWS
USER_SEQUENCES
USER_INDEXES
USER_SYNONYMS
3 - 28
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
Querying the dictionary views for index information
Adding a comment to a table and querying the dictionary
views for comment information
3 - 29
Objectives
After completing this lesson, you should be able to do the
following:
Manipulate data by 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:
4-2
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
Lesson Agenda
4-3
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
4-4
4-5
4-7
4-8
4-9
Lesson Agenda
4 - 11
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
4 - 12
UPDATE deptm3
SET manager_id = DEFAULT
WHERE department_id = 10;
4 - 13
4 - 14
Lesson Agenda
4 - 15
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
Target_a
Sourcetab
Subquery
INSERT ALL
INTO target_a VALUES(,,)
INTO target_b VALUES(,,)
INTO target_c VALUES(,,)
SELECT
FROM sourcetab
WHERE ;
Target_b
Target_c
4 - 16
4 - 17
4 - 18
conditional_insert_clause:
[ALL|FIRST]
[WHEN condition THEN] [insert_into_clause values_clause]
[ELSE] [insert_into_clause values_clause]
4 - 19
INSERT ALL
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 > 200;
4 - 21
Hired before
1995
EMP_HISTORY
Employees
With sales
commission
EMP_SALES
4 - 23
ALL
4 - 24
employees
4 - 26
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
INTO sal_high VALUES (employee_id, last_name, salary)
SELECT employee_id, last_name, salary
FROM employees
4 - 27
Pivoting INSERT
Convert the set of sales records from the nonrelational
database table to relational format.
4 - 29
Emp_ID
Week_ID
MON
TUES
WED
THUR
FRI
176
2000
3000
4000
5000
6000
Employee_ID
WEEK
SALES
176
2000
176
3000
176
4000
176
5000
176
6000
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;
4 - 30
Lesson Agenda
4 - 32
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
MERGE Statement
4 - 33
4 - 34
4 - 35
Lesson Agenda
4 - 38
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
Version
query
SELECT
COMMIT;
SELECT salary FROM employees3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE employee_id = 107;
4 - 40
4 - 42
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
4 - 43
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:
4 - 44
Unconditional INSERT
Pivoting INSERT
Conditional INSERT ALL
Conditional INSERT FIRST
Practice 4: Overview
This practice covers the following topics:
Performing multitable INSERTs
Performing MERGE operations
4 - 45
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:
5-2
CURRENT_DATE
CURRENT_TIMESTAMP
LOCALTIMESTAMP
DBTIMEZONE
SESSIONTIMEZONE
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
5-3
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
Time Zones
+07:00
-08:00
+02:00
+10:00
-05:00
An absolute offset
Database time zone
OS local time zone
A named region
ALTER
ALTER
ALTER
ALTER
5-5
SESSION
SESSION
SESSION
SESSION
SET
SET
SET
SET
TIME_ZONE
TIME_ZONE
TIME_ZONE
TIME_ZONE
=
=
=
=
'-05:00';
dbtimezone;
local;
'America/New_York';
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:
Returns the current date and time from the user session
Has a data type of TIMESTAMP
5-6
5-7
1
2
3
5-8
5-9
Data Type
Fields
Year, Month, Day, Hour, Minute, Second
with fractional seconds
TIMESTAMP
5 - 10
TIMESTAMP Fields
Datetime Field
5 - 11
Valid Values
YEAR
MONTH
01 to 12
DAY
01 to 31
HOUR
00 to 23
MINUTE
00 to 59
SECOND
TIMEZONE_HOUR
12 to 14
TIMEZONE_MINUTE
00 to 59
-- when hire_date is
of type DATE
SELECT hire_date
FROM employees;
SELECT hire_date
FROM employees;
5 - 12
5 - 13
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
5 - 14
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
5 - 15
Data Type
Fields
Year, Month
INTERVAL Fields
5 - 17
INTERVAL Field
YEAR
MONTH
00 to 11
DAY
HOUR
00 to 23
MINUTE
00 to 59
SECOND
5 - 18
TO SECOND);
5 - 20
Lesson Agenda
CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP
INTERVAL data types
5 - 21
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
EXTRACT
5 - 22
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;
5 - 23
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;
5 - 25
TO_TIMESTAMP
Display the character string '2007-03-06 11:00:00'
as a TIMESTAMP value:
5 - 26
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;
5 - 27
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;
5 - 28
5 - 29
Quiz
The TIME_ZONE session parameter may be set to:
1.
2.
3.
4.
5 - 31
A relative offset
Database time zone
OS local time zone
A named region
Summary
In this lesson, you should have learned how to use the
following functions:
5 - 32
CURRENT_DATE
CURRENT_TIMESTAMP
LOCALTIMESTAMP
DBTIMEZONE
SESSIONTIMEZONE
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
Copyright 2009, Oracle. All rights reserved.
Practice 5: Overview
This practice covers using the datetime functions.
5 - 33
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 by using correlated subqueries
Use the EXISTS and NOT EXISTS operators
Use the WITH clause
6-2
Lesson Agenda
6-3
Multiple-Column Subqueries
Main query
WHERE (MANAGER_ID, DEPARTMENT_ID)
IN
Subquery
100
102
124
90
60
50
6-4
Column Comparisons
Multiple-column comparisons involving subqueries can be:
Nonpairwise comparisons
Pairwise comparisons
6-5
6-6
6-8
Lesson Agenda
6 - 10
6 - 11
SELECT
employee_id, last_name
FROM
employees e
ORDER BY (SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id);
6 - 12
Lesson Agenda
6 - 14
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
EXECUTE
inner query using candidate row value
USE
values from inner query to qualify or
disqualify candidate row
6 - 15
Correlated Subqueries
The subquery references a column from a table in the parent
query.
SELECT column1, column2, ...
Outer_table
FROM
table1
WHERE column1 operator
(SELECT column1, column2
FROM
table2
WHERE
expr1 =
Outer_table .expr2);
6 - 16
6 - 18
Lesson Agenda
6 - 19
6 - 20
6 - 21
6 - 22
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);
6 - 23
6 - 24
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);
6 - 26
6 - 27
Lesson Agenda
6 - 28
WITH Clause
6 - 29
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.
6 - 30
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;
6 - 31
6 - 32
FLIGHTS Table
3
6 - 33
Quiz
With a correlated subquery, the inner SELECT statement drives
the outer SELECT statement.
1. True
2. False
6 - 34
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
6 - 35
Summary
6 - 36
Practice 6: Overview
This practice covers the following topics:
Creating multiple-column subqueries
Writing correlated subqueries
Using the EXISTS operator
6 - 37
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
7-2
Lesson Agenda
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
Accessing subexpressions
Using the REGEXP_COUNT function
7-3
7-4
7-5
Description
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
REGEXP_COUNT
7-6
Lesson Agenda
7-7
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
Accessing subexpressions
Using the REGEXP_COUNT function
7-8
The literals f or ht
The t literal
The p literal, optionally followed by the s literal
The colon : literal at the end of the string
{m}
{m, }
{m,n}
[]
|
( ... )
7-9
Description
Syntax
^
\n
\d
A digit character
[:class:]
[^:class:]
7 - 10
Description
Lesson Agenda
7 - 11
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
Accessing subexpressions
Using the REGEXP_COUNT function
REGEXP_INSTR
7 - 12
7 - 13
Replacing Patterns by
Using the REGEXP_REPLACE Function
REGEXP_REPLACE(source_char, pattern [,replacestr
[, position [, occurrence [, match_option]]]])
Original
7 - 14
Partial results
Finding Patterns by
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;
7 - 15
Extracting Substrings by
Using the REGEXP_SUBSTR Function
REGEXP_SUBSTR (source_char, pattern [, position
[, occurrence [, match_option]]])
SELECT REGEXP_SUBSTR(street_address , ' [^ ]+ ') AS Road
FROM locations;
7 - 16
Lesson Agenda
7 - 17
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
Accessing subexpressions
Using the REGEXP_COUNT function
Subexpressions
Examine this expression:
4
2
7 - 18
7 - 19
'(gtc(tcac)(aaag))',
1, 1, 0, 'i',
1) "Position"
FROM dual;
7 - 20
REGEXP_SUBSTR: Example
SELECT
REGEXP_SUBSTR
1
('acgctgcactgca',
2 'acg(.*)gca',
3 1,
4 1,
5 'i',
6 1)
"Value"
FROM dual;
7 - 21
-------
Lesson Agenda
7 - 22
REGEXP_LIKE
REGEXP_REPLACE
REGEXP_INSTR
REGEXP_SUBSTR
Accessing subexpressions
Using the REGEXP_COUNT function
'gtc') AS Count
FROM dual;
7 - 23
7 - 24
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
7 - 25
Summary
In this lesson, you should have learned how to use regular
expressions to search for, match, and replace strings.
7 - 26
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
Testing the adding of some phone numbers into the
p_number column by using various formats
7 - 27
Objectives
After completing this appendix, you should be able to do the
following:
List the key features of Oracle SQL Developer
Identify menu items of Oracle SQL Developer
Create a database connection
Manage database objects
Use SQL Worksheet
Save and run SQL scripts
Create and save reports
C-2
SQL Developer
C-3
C-4
C-5
C-7
C-8
C - 10
C - 11
Browsing Files
Use the File Navigator to explore the file system and open
system files.
C - 12
C - 13
C - 14
Select SQL
Worksheet from the
Tools menu, or
C - 15
C - 16
Enter SQL
statements.
Results are
shown here.
C - 17
F9
F5
F5
F9
C - 18
C - 19
Identify a location,
enter a file name,
and click Save.
1
To run the code, click either:
Execute Script (F9), or
3
Run Script (F5)
C - 20
2
Select a connection from
the drop-down list.
C - 21
After
formatting
C - 22
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.
C - 23
Inserting a
snippet
Editing the
snippet
C - 24
C - 25
Database Reporting
SQL Developer provides a number of predefined reports about
the database and its objects.
C - 26
C - 27
Shortcuts to
frequently used tools
Links to popular
search engines and
discussion forums
C - 28
Setting Preferences
C - 29
C - 30
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
C - 31
Using SQL*Plus
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
D-2
SQL statements
Server
SQL*Plus
Query results
Buffer
SQL
scripts
D-3
D-4
SQL
buffer
SQL*Plus
An environment
Oracle-proprietary
Keywords can be
abbreviated.
Commands do not
allow manipulation of
values in the database.
SQL*Plus
commands
SQL*Plus
buffer
Overview of SQL*Plus
D-5
Log in to SQL*Plus.
Describe the table structure.
Edit your SQL statement.
Execute SQL from SQL*Plus.
Save SQL statements to files and append SQL statements
to files.
Execute saved files.
Load commands from the file to buffer to edit.
Logging In to SQL*Plus
sqlplus [username[/password[@database]]]
D-6
D-7
DESCRIBE departments
Name
----------------------DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
D-8
Null?
Type
-------- -----------NOT NULL NUMBER(4)
NOT NULL VARCHAR2(30)
NUMBER(6)
NUMBER(4)
D-9
A[PPEND] text
C[HANGE] / old / new
C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n
D - 10
I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text
LIST
1 SELECT last_name
2* FROM
employees
1
1* SELECT last_name
A , job_id
1* SELECT last_name, job_id
LIST
1 SELECT last_name, job_id
2* FROM
employees
D - 11
LIST
1* SELECT * from employees
c/employees/departments
1* SELECT * from departments
LIST
1* SELECT * from departments
D - 12
D - 13
SAVE filename
GET filename
START filename
@ filename
EDIT filename
SPOOL filename
EXIT
START my_query
LAST_NAME
MANAGER_ID DEPARTMENT_ID
------------------------- ---------- ------------King
90
Kochhar
100
90
...
107 rows selected.
D - 14
SERVEROUTPUT Command
D - 15
Description
file_name[.ext]
CRE[ATE]
REP[LACE]
APP[END]
OFF
Stops spooling
OUT
D - 16
SET AUTOTRACE ON
-- The AUTOTRACE report includes both the optimizer
-- execution path and the SQL statement execution
-- statistics
D - 17
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
D - 18
Using JDeveloper
Objectives
After completing this appendix, you should be able to do the
following:
List the key features of Oracle JDeveloper
Create a database connection in JDeveloper
Manage database objects in Jdeveloper
Use JDeveloper to execute SQL Commands
Create and run PL/SQL Program Units
E-2
Oracle JDeveloper
E-3
Database Navigator
E-4
Creating a Connection
1
2
4
E-5
Click OK.
E-6
1
2
E-7
3
Skeleton of the function
E-8
Compiling
E - 10
1
2
E - 11
Structure Window
E - 12
Editor Window
E - 13
Application Navigator
E - 14
E - 15
E - 16
Topic
Web site
Oracle JDeveloper
Product Page
http://www.oracle.com/technology/products/jdev/index.html
http://www.oracle.com/technology/obe/obe11jdev/11/index.html
http://www.oracle.com/technology/documentation/jdev.html
http://forums.oracle.com/forums/forum.jspa?forumID=83
E - 17
Summary
In this appendix, you should have learned how to use
JDeveloper to do the following:
List the key features of Oracle JDeveloper
Create a database connection in JDeveloper
Manage database objects in JDeveloper
Use JDeveloper to execute SQL Commands
Create and run PL/SQL Program Units
E - 18
Objectives
After completing this appendix, you should be able 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 to produce a single result set
F-2
[column,] group_function(column). . .
table
condition]
group_by_expression]
column];
Example:
SELECT AVG(salary), STDDEV(salary),
COUNT(commission_pct),MAX(hire_date)
FROM
employees
WHERE job_id LIKE 'SA%';
F-3
Syntax:
SELECT
FROM
[WHERE
[GROUP BY
[ORDER BY
[column,] group_function(column). . .
table
condition]
group_by_expression]
column];
Example:
SELECT
F-4
F-5
[column,] group_function(column)...
table
condition]
group_by_expression]
having_expression]
column];
F-6
ROLLUP Operator
F-7
[column,] group_function(column). . .
table
condition]
[ROLLUP] group_by_expression]
having_expression];
column];
2
3
F-8
CUBE Operator
F-9
[column,] group_function(column)...
table
condition]
[CUBE] group_by_expression]
having_expression]
column];
2
3
4
F - 10
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
SELECT
[column,] group_function(column) .. ,
GROUPING(expr)
FROM
table
[WHERE
condition]
[GROUP BY [ROLLUP][CUBE] group_by_expression]
[HAVING
having_expression]
[ORDER BY column];
F - 11
3
F - 12
GROUPING SETS
F - 13
department_id, job_id,
manager_id,AVG(salary)
FROM
employees
GROUP BY GROUPING SETS
((department_id,job_id), (job_id,manager_id));
F - 15
Composite Columns
F - 17
1
2
3
4
F - 19
Concatenated Groupings
F - 21
2
F - 22
3
Copyright 2009, Oracle. All rights reserved.
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
GROUP BY clause to combine expressions in various ways:
Composite columns
Concatenated grouping sets
F - 23
Hierarchical Retrieval
Objectives
After completing this appendix, 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
G-2
G-3
Kochhar
Whalen Higgins
Mourgos
De Haan
Hunold
Rajs Davies
Zlotkey
Matos
Hartstein
Vargas
Fay
Gietz Ernst
G-4
Lorentz
Abel
Taylor
Grant
Hierarchical Queries
condition:
expr comparison_operator expr
G-5
Starting Point
Using the EMPLOYEES table, start with the employee whose last
name is Kochhar.
...START WITH last_name = 'Kochhar'
G-6
Direction
G-7
Top down
Bottom up
G-8
SELECT
PRIOR
FROM
START
CONNECT
G-9
Kochhar
De Haan
Gietz Ernst
G - 10
King
Level 1
root/
parent
Mourgos
Level 2
parent/
child/leaf
Rajs Davies
Lorentz
Zlotkey Hartstein
Matos Vargas
Abel
Fay
Taylor Grant
Level 3
parent/
child/leaf
Level 4
leaf
G - 11
Pruning Branches
Kochhar
Whalen
Higgins
Whalen
Gietz
G - 13
Higgins
Gietz
Summary
In this appendix, you should have learned that you can:
Use hierarchical queries to view a hierarchical relationship
between rows in a table
Specify the direction and starting point of the query
Eliminate nodes or branches by pruning
G - 14
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
H-2
Data dictionary
SQL
SQL script
H-3
H-4
SQL statement
SET FEEDBACK ON
SET PAGESIZE 24
SET ECHO ON
H-5
H-6
SELECT
'INSERT INTO departments_test VALUES
(' || department_id || ', ''' || department_name ||
''', ''' || location_id || ''');'
AS "Insert Statements Script"
FROM
departments
/
SET PAGESIZE 24
SET HEADING ON ECHO ON FEEDBACK ON
H-7
Source
Result
'''X'''
'X'
''''
'
''''||department_name||'''' 'Administration'
H-8
''', '''
','
''');'
');
H-9
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
H - 11
Objectives
After completing this appendix, 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
I-2
I-3
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
Database
Storage structures
Data files
I-4
Control
files
Online redo
log files
SQL> Select
User
User
Connection
I-5
Session
Server
process
Instance
SGA
Shared pool
Database
buffer
cache
DBWn CKPT
Redo log
buffer
Data dictionary
cache
User
I-6
Library
cache
RECO Others
Server
process 1
Server
process 2
PGA
Library
cache
Database buffer
cache
I-8
Data Dictionary
cache
Other
Shared pool
Redo log
buffer
Java
pool
Background
processes
PGA
Shared
SQL area
Streams
pool
DB structures
Memory
- Process
- Storage
I/O Buffer
Free
memory
Response
queue
Request
queue
Large pool
PGA
SGA
Process Architecture
DB structures
- Memory
Process
- Storage
User process:
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
SGA
PGA
User
process
Server
process
Background processes
DBWn
CKPT
LGWR
SMON
PMON
ARCn
I - 10
RECO Others
DBWn
Database buffer
cache
I - 12
Database writer
process
Data files
LGWR
Redo log buffer
I - 13
Log writer
process
Checkpoint Process
Records checkpoint information in:
The control file
Each datafile header
CKPT
Control
file
Checkpoint
process
Data files
I - 14
SMON
Instance
System monitor
process
Temporary
segment
I - 15
PMON
Process monitor
process
I - 16
User
Failed user
process
Database buffer
cache
Data files
Control
files
Online redo
log files
Parameter file
Password file
Network files
Alert and trace files
I - 17
Backup files
Physical
Database
Schema
Tablespace
Data file
Segment
Extent
Oracle data
block
I - 19
OS block
I - 21
Processing a Query
Parse:
I - 22
Shared Pool
I - 23
Database buffer
cache
I - 25
Is not shared
Is writable only by the server process
Contains:
Sort area
Session information
Cursor state
Stack space
Server
process
PGA
I - 26
User
process
Shared pool
Database
buffer
cache
Redo log
buffer
UPDATE
employees ...
Server
process
Data
files
Control
files
1
Database
I - 27
Redo
log files
I - 29
Rollback Segment
Old image
Rollback segment
New image
Table
DML statement
I - 30
COMMIT Processing
1
Instance
SGA
Server
process
Shared pool
Database
buffer
cache
Redo log
buffer
3
LGWR
DBWn
User
process
Data
files
Control
files
Database
I - 31
Redo
log files
PMON
RECO
SGA
Shared pool
Database
buffer
cache
Redo log
buffer
DBWn
CKPT
PGA
Server
process
User
process
Data files
I - 33
Others
Control
files
Library
cache
Data dictionary
cache
LGWR
Online redo
log files
Database
ARCn
Archived
log files