Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

n
-tra
n

o
an
has 10g: SQL
Oracle Database ฺ
)
comGuide
Fundamentals I
ailฺ nt
gm de
@Student Guide • Volume 2
t
tu
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

D17108GC30
Edition 3.0
January 2009
D57871
SQL Star International Limited
Copyright © 2009, Oracle. All rights reserved.

Salome Clement
Chaitanya Koratamaddi
Nancy Greenberg

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Authors

Disclaimer

Technical Contributors
and Reviewers
Wayne Abbott
Christian Bauwens
Claire Bennett
Perry Benson
Brian Boxx
Zarko Cesljas
Dairy Chan
Laszlo Czinkoczki
Joel Goodman
Matthew Gregory
Sushma Jagannath
Yash Jain
Angelika Krupp
Isabelle Marchand
Malika Marghadi
Valli Pataballa
Narayanan Radhakrishnan
Bryan Roberts
Helen Robertson
Lata Shivaprasad
John Soltani
James Spiller
Priya Vennapusa

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

s

Arijit Ghosh
Raj Kumar
Graphic Designer
Rajiv Chandrabhanu
Publisher
Giri Venugopal

n
-tra
n

U.S. GOVERNMENT RIGHTS
The U.S. Government’s 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.

o

Trademark Notice

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other
names may be trademarks of their respective owners.

e

l
rab
fe

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:

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM
ASEditors
R

NA

This document contains proprietary information and is protected by copyright and
other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered in
any way. Except where your use constitutes "fair use" under copyright law, you may
not use, share, download, upload, copy, print, display, perform, reproduce, publish,
license, post, transmit, or distribute this document in whole or in part without the
express authorization of Oracle.
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Contents

Preface
I

Introduction
Lesson Objectives I-2
Goals of the Course I-3
Oracle10g I-4
Oracle Database 10g I-6
Oracle Application Server 10g I-7
Oracle Enterprise Manager 10g Grid Control I-8
Relational and Object Relational Database Management Systems I-9
Oracle Internet Platform I-10
System Development Life Cycle I-11
Data Storage on Different Media I-13
Relational Database Concept I-14
Definition of a Relational Database I-15
Data Models I-16
Entity Relationship Model I-17
Entity Relationship Modeling Conventions I-19
Relating Multiple Tables I-21
Relational Database Terminology I-23
Relational Database Properties I-25
Communicating with an RDBMS Using SQL I-26
Oracle’s Relational Database Management System I-27
SQL Statements I-28
Tables Used in the Course I-29
Summary I-30

IM

S
RA

NA

1

Retrieving Data Using the SQL SELECT Statement
Objectives 1-2
Capabilities of SQL SELECT Statements 1-3
Basic SELECT Statement 1-4
Selecting All Columns 1-5
Selecting Specific Columns 1-6
Writing SQL Statements 1-7
Column Heading Defaults 1-8

iii

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

2

e

Restricting and Sorting Data
Objectives 2-2
Limiting Rows Using a Selection 2-3
Limiting the Rows That Are Selected 2-4
Using the WHERE Clause 2-5
Character Strings and Dates 2-6
Comparison Conditions 2-7
Using Comparison Conditions 2-8
Using the BETWEEN Condition 2-9
Using the IN Condition 2-10
Using the LIKE Condition 2-11
Using the NULL Conditions 2-13
Logical Conditions 2-14

iv

l
rab
fe

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Arithmetic Expressions 1-9
Using Arithmetic Operators 1-10
Operator Precedence 1-11
Defining a Null Value 1-12
Null Values in Arithmetic Expressions 1-13
Defining a Column Alias 1-14
Using Column Aliases 1-15
Concatenation Operator 1-16
Literal Character Strings 1-17
Using Literal Character Strings 1-18
Alternative Quote (q) Operator 1-19
Duplicate Rows 1-20
Development Environments for SQL 1-21
What Is Oracle SQL Developer? 1-22
Oracle SQL Developer Interface 1-23
Creating a Database Connection 1-24
Browsing Database Objects 1-27
Using the SQL Worksheet 1-28
Executing SQL Statements 1-31
Formatting the SQL Code 1-32
Saving SQL Statements 1-33
Running Script Files 1-34
Displaying the Table Structure 1-35
Using the DESCRIBE Command 1-36
Summary 1-37
Practice 1: Overview 1-38
SQL Star International Limited

Using the AND Operator 2-15

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the OR Operator 2-16
Using the NOT Operator 2-17
Rules of Precedence 2-18
Using the ORDER BY Clause 2-20
Sorting 2-21
Substitution Variables 2-22
Using the & Substitution Variable 2-24
Character and Date Values with Substitution Variables 2-26
Specifying Column Names, Expressions, and Text 2-27
Using the && Substitution Variable 2-28

e

Using the DEFINE Command 2-29

s

Using the VERIFY Command 2-30
Summary 2-31
Practice 2: Overview 2-32

N

n
-tra
n

o

an
has ฺ
)
e
3 Using Single-Row Functions to Customizecom
Output
ilฺ t Guid
a
Objectives 3-2
gm den
SQL Functions 3-3
@
n t is Stu
Two Types of SQL Functionsc 3-4
a
Single-Row Functions 3-5
mh se th
i
ras to u
Character Functions 3-7
(na se
Case-Manipulation Functions 3-9
N C licen
AUsing Case-Manipulation Functions 3-10
IMH Character-Manipulation Functions 3-11

S

A
AR

l
rab
fe

Using the Character-Manipulation Functions 3-12
Number Functions 3-13
Using the ROUND Function 3-14
Using the TRUNC Function 3-15
Using the MOD Function 3-16
Working with Dates 3-17
Arithmetic with Dates 3-20
Using Arithmetic Operators with Dates 3-21
Date Functions 3-22
Using Date Functions 3-23
Practice 3: Overview of Part 1 3-25
Conversion Functions 3-26
Implicit Data Type Conversion 3-27
Explicit Data Type Conversion 3-29
Using the TO_CHAR Function with Dates 3-32

v
SQL Star International Limited

Elements of the Date Format Model 3-33
Using the TO_CHAR Function with Dates 3-37
Using the TO_CHAR Function with Numbers 3-38

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the TO_NUMBER and TO_DATE Functions 3-41
RR Date Format 3-43
RR Date Format: Example 3-44
Nesting Functions 3-45
General Functions 3-47
NVL Function 3-48
Using the NVL Function 3-49

e

l
rab
fe

Using the NVL2 Function 3-50
Using the NULLIF Function 3-51

s

Using the COALESCE Function 3-52
Conditional Expressions 3-54
CASE Expression 3-55

an
has ฺ
Using the CASE Expression 3-56
)
DECODE Function 3-57
comGuide
ailฺ nt
Using the DECODE Function 3-58
m
@g tude
Summary 3-60
t
anc this S
Practice 3: Overview of Part 2 h3-61
m
asi use
r
4 Reporting Aggregated Data Using the Group Functions
(na se to
Objectives C
4-2
ANGroupicen
l Functions? 4-3
What Are
IMH of Group Functions 4-4
S Types

A

R
NA

o

n
-tra
n

Group Functions: Syntax 4-5
Using the AVG and SUM Functions 4-6
Using the MIN and MAX Functions 4-7
Using the COUNT Function 4-8
Using the DISTINCT Keyword 4-9
Group Functions and Null Values 4-10
Creating Groups of Data 4-11
Creating Groups of Data: GROUP BY Clause Syntax 4-12
Using the GROUP BY Clause 4-13
Grouping by More Than One Column 4-15
Using the GROUP BY Clause on Multiple Columns 4-16
Illegal Queries Using Group Functions 4-17
Restricting Group Results 4-19
Restricting Group Results with the HAVING Clause 4-20

vi
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the HAVING Clause 4-21
Nesting Group Functions 4-23
Summary 4-24
Practice 4: Overview 4-25
5

Displaying Data from Multiple Tables
Objectives 5-2
Obtaining Data from Multiple Tables 5-3
Types of Joins 5-4
Joining Tables Using SQL:1999 Syntax 5-5
Creating Natural Joins 5-6
Retrieving Records with Natural Joins 5-7
Creating Joins with the USING Clause 5-8
Joining Column Names 5-9
Retrieving Records with the USING Clause 5-10
Qualifying Ambiguous Column Names 5-11
Using Table Aliases 5-12
Creating Joins with the ON Clause 5-13

e

s

NA

RA

Outer Joins 5-21
INNER Versus OUTER Joins 5-22
LEFT OUTER JOIN 5-23
RIGHT OUTER JOIN 5-24

FULL OUTER JOIN 5-25
Cartesian Products 5-26
Generating a Cartesian Product 5-27
Creating Cross Joins 5-28
Summary 5-29
Practice 5: Overview 5-30
6

Using Subqueries to Solve Queries
Objectives 6-2
Using a Subquery to Solve a Problem 6-3
Subquery Syntax 6-4
Using a Subquery 6-5

vii

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
Retrieving Records with the ON Clause 5-14 e
@g tud
t
Self-Joins Using the ON Clause 5-15 S
anc tohais 5-17
Applying Additional mh
Conditions t Join
asi Joinsse the ON Clause 5-18
r
Creating Three-Way
u with
(na 5-19 to
Nonequijoins se
N C licen
ARetrieving Records with Nonequijoins 5-20

IMH
S

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Guidelines for Using Subqueries 6-6
Types of Subqueries 6-7
Single-Row Subqueries 6-8
Executing Single-Row Subqueries 6-9
Using Group Functions in a Subquery 6-10
The HAVING Clause with Subqueries 6-11
What Is Wrong with This Statement? 6-12
Will This Statement Return Rows? 6-13
Multiple-Row Subqueries 6-14
Using the ANY Operator in Multiple-Row Subqueries 6-15
Using the ALL Operator in Multiple-Row Subqueries 6-16
Null Values in a Subquery 6-17
Summary 6-19
Practice 6: Overview 6-20

s

MINUS Operator 7-15
Set Operator Guidelines 7-17
The Oracle Server and Set Operators 7-18
Matching the SELECT Statements 7-19

Matching the SELECT Statement: Example 7-20
Controlling the Order of Rows 7-21
Summary 7-22
Practice 7: Overview 7-23
8

Manipulating Data
Objectives 8-2
Data Manipulation Language 8-3
Adding a New Row to a Table 8-4
INSERT Statement Syntax 8-5
Inserting New Rows 8-6

viii

n
-tra
n

o

an
7 Using the Set Operators
has ฺ
)
Objectives 7-2
comGuide
Set Operators 7-3
ailฺ nt
m
Tables Used in This Lesson 7-4
@g tude
t
UNION Operator 7-8
anc this S
Using the UNION Operator mh
7-9
si use
UNION ALL Operator a
ar 7-11to
nALL Operator 7-12
Using the UNION
C ( ense
N lic
INTERSECT Operator 7-13
HA INTERSECT Operator 7-14
Using
SIM the

A

R
NA

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Inserting Rows with Null Values 8-7
Inserting Special Values 8-8
Inserting Specific Date Values 8-9
Creating a Script 8-10
Copying Rows from Another Table 8-11
Changing Data in a Table 8-12
UPDATE Statement Syntax 8-13
Updating Rows in a Table 8-14
Updating Two Columns with a Subquery 8-15
Updating Rows Based on Another Table 8-16
Removing a Row from a Table 8-17
DELETE Statement 8-18
Deleting Rows from a Table 8-19
Deleting Rows Based on Another Table 8-20

e

s

IMH
S

A

R
NA

9

State of the Data After ROLLBACK 8-34
Statement-Level Rollback 8-36
Read Consistency 8-37
Implementation of Read Consistency 8-38
Summary 8-39
Practice 8: Overview 8-40

Using DDL Statements to Create and Manage Tables
Objectives 9-2
Database Objects 9-3
Naming Rules 9-4
CREATE TABLE Statement 9-5
Referencing Another User’s Tables 9-6
DEFAULT Option 9-7
Creating Tables 9-8
Data Types 9-9

ix

n
-tra
n

o

an
Using a Subquery in an INSERT Statement 8-22
has ฺ
)
Database Transactions 8-24
comGuide
Advantages of COMMIT and ROLLBACK Statements 8-26
ailฺ nt
m
Controlling Transactions 8-27
@g tude
Rolling Back Changes to a nct
Marker 8-28
S
ha this
Implicit Transactionm
Processing 8-29
i COMMIT
State of the Datas
ra Beforeuse or ROLLBACK 8-31
a After
o
State of (n Data e t COMMIT 8-32
the
s
N C lic Data
ACommittingen 8-33
TRUNCATE Statement 8-21

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Datetime Data Types 9-11
Including Constraints 9-17
Constraint Guidelines 9-18
Defining Constraints 9-19
NOT NULL Constraint 9-21
UNIQUE Constraint 9-22
PRIMARY KEY Constraint 9-24
FOREIGN KEY Constraint 9-25
FOREIGN KEY Constraint: Keywords 9-27
CHECK Constraint 9-28
CREATE TABLE: Example 9-29
Violating Constraints 9-30
Creating a Table by Using a Subquery 9-32
ALTER TABLE Statement 9-34
Dropping a Table 9-35
Summary 9-36
Practice 9: Overview 9-37

s

Retrieving Data from a View 10-10
Modifying a View 10-11
Creating a Complex View 10-12
Rules for Performing DML Operations on a View 10-13
Using the WITH CHECK OPTION Clause 10-16
Denying DML Operations 10-18
Removing a View 10-20
Practice 10: Overview of Part 1 10-21
Sequences 10-22
CREATE SEQUENCE Statement: Syntax 10-24
Creating a Sequence 10-25
NEXTVAL and CURRVAL Pseudocolumns 10-26
Using a Sequence 10-28
Caching Sequence Values 10-29
Modifying a Sequence 10-30

x

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
10 Creating Other Schema Objects
@g tude
t
Objectives 10-2
anc this S
h
Database Objects 10-3 im
ras to use
What Is a View? 10-4
na 10-5
AdvantagesC Views se
of (
n
Simple Views and e
AN lic Complex Views 10-6
IMH a View 10-7
S Creating

A

R
NA

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Guidelines for Modifying a Sequence 10-31
Indexes 10-33
How Are Indexes Created? 10-35
Creating an Index 10-36
Index Creation Guidelines 10-37
Removing an Index 10-38
Synonyms 10-39
Creating and Removing Synonyms 10-41
Summary 10-42
Practice 10: Overview of Part 2 10-43
11 Managing Objects with Data Dictionary Views
Objectives 11-2
The Data Dictionary 11-3
Data Dictionary Structure 11-4
How to Use the Dictionary Views 11-6
USER_OBJECTS and ALL_OBJECTS Views 11-7

e

s

A

R
NA

A

Adding Comments to a Table 11-19
Summary 11-20
Practice 11: Overview 11-21
Practice Solutions

B Table Descriptions and Data
C Oracle Join Syntax
D Using SQL*Plus
E Using SQL Developer
Index

xi

n
-tra
n

o

an
has ฺ
)
comGuide
USER_OBJECTS View 11-8
ailฺ nt
m
Table Information 11-9
@g tude
Column Information 11-10 ct
S
n
Constraint Information ha
11-12 this
m
View Informations11-15use
a i
r
Sequence Information 11-16
(na se to
N C li Information 11-18
ASynonymcen

IMH
S

l
rab
fe
SQL Star International Limited

Additional Practices

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Additional Practices: Table Descriptions and Data
Additional Practices: Solutions

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

xii
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Using DDL Statements
to Create and Manage Tables

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Objectives
After completing this lesson, you should be able to do the
following:
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
e
abl
r
• Explain how constraints are created at the time of table sfe
n
creation
-tra
non
• Describe how schema objects work
sa

NA

) ha eฺ
m
ฺco Guid
il
ma ent
g
t@ Stud
c
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C
AN licen
Objectives
IMH you are introduced to the data definition language (DDL) statements. You are
AS
RIn this lesson,

taught the basics of how to create simple tables, alter them, and remove them. The data types
available in DDL are shown, and schema concepts are introduced. Constraints are tied into this
lesson. Exception messages that are generated from violating constraints during DML are shown
and explained.

Oracle Database 10g: SQL Fundamentals I 9 - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Database Objects

Object

Description

Table

Basic unit of storage; composed of rows

View

Logically represents subsets of data from one or
more tables

Sequence

Generates numeric values

Index

Improves the performance of some queries

Synonym

Gives alternative names to objects

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
DatabaseH
Objects
IM Database can contain multiple data structures. Each structure should be outlined in
AS
RAn Oracle

the database design so that it can be created during the build stage of database development.
• Table: Stores data
• View: Subset of data from one or more tables
• Sequence: Generates numeric values
• Index: Improves the performance of some queries
• Synonym: Gives alternative names to objects
Oracle Table Structures
• Tables can be created at any time, even while users are using the database.
• You do not need to specify the size of a table. The size is ultimately defined by the amount
of space allocated to the database as a whole. It is important, however, to estimate how
much space a table will use over time.
• Table structure can be modified online.
Note: More database objects are available but are not covered in this course.

Oracle Database 10g: SQL Fundamentals I 9 - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Naming Rules
Table names and column names:
• Must begin with a letter
• Must be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $, and #
• Must not duplicate the name of another object owned by
the same user
e
abl
r
• Must not be an Oracle server–reserved word
sfe

n

a
n-tr
o

N

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Naming Rules
IMHdatabase tables and columns according to the standard rules for naming any Oracle
AS
RYou nameobject:
A Database
• Table names and column names must begin with a letter and be 1–30 characters long.
• Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $, and # (legal
characters, but their use is discouraged).
• Names must not duplicate the name of another object owned by the same Oracle server
user.
• Names must not be an Oracle server–reserved word.
Naming Guidelines
Use descriptive names for tables and other database objects.
Note: Names are case-insensitive. For example, EMPLOYEES is treated as the same name as
eMPloyees or eMpLOYEES.
For more information, see “Object Names and Qualifiers” in the Oracle Database SQL
Reference.

Oracle Database 10g: SQL Fundamentals I 9 - 4
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

CREATE TABLE Statement
•

You must have:
– The CREATE TABLE privilege
– A storage area
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);

•

You specify the:
– Table name
– Column name, column data type, and column size

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Statement
CREATE TABLE
lic
H
IM
You create tables to store data by executing the SQL CREATE TABLE statement. This
AS
ARstatement is one of the DDL statements, which are a subset of SQL statements used to create,
modify, or remove Oracle Database structures. These statements have an immediate effect on
the database, and they also record information in the data dictionary.
To create a table, a user must have the CREATE TABLE privilege and a storage area in which to
create objects. The database administrator uses data control language statements to grant
privileges to users (DCL statements are covered in a later lesson).
In the syntax:
schema
Is the same as the owner’s name
table
is the name of the table
DEFAULT expr
Specifies a default value if a value is omitted in the INSERT
statement
column
Is the name of the column
datatype
Is the column’s data type and length

Oracle Database 10g: SQL Fundamentals I 9 - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Referencing Another User’s Tables
•
•

Tables belonging to other users are not in the user’s
schema.
You should use the owner’s name as a prefix to those
tables.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
USERA
USERB
)
comGuide
SELECT *
SELECT *
ailฺ userA.employees;
FROM userB.employees;
gmFROMent
d
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
N C licUser’s
AAnother en Tables
Referencing
IMH a collection of objects. Schema objects are the logical structures that directly refer
AS
RA schema is

to the data in a database. Schema objects include tables, views, synonyms, sequences, stored
procedures, indexes, clusters, and database links.
If a table does not belong to the user, the owner’s name must be prefixed to the table. For
example, if there are schemas named USERA and USERB, and both have an EMPLOYEES table,
then if USERA wants to access the EMPLOYEES table that belongs to USERB, he or she must
prefix the table name with the schema name:
SELECT *
FROM
userb.employees;

If USERB wants to access the EMPLOYEES table that is owned by USERA, he must prefix the
table name with the schema name:
SELECT *
FROM
usera.employees;

Oracle Database 10g: SQL Fundamentals I 9 - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DEFAULT Option
•

Specify a default value for a column during an insert.
... hire_date DATE DEFAULT SYSDATE, ...

•
•
•

Literal values, expressions, or SQL functions are legal
values.
Another column’s name or a pseudocolumn are illegal
e
abl
r
values.
sfe
n
The default data type must match the column data type.
-tra
n

N

o
an
CREATE TABLE hire_dates
has ฺ
(id
NUMBER(8),
)
om uide
hire_date DATE DEFAULT cSYSDATE);
ailฺ nt G
CREATE TABLE succeeded.
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
DEFAULT H
Option
IM define a table, you can specify that a column be given a default value by using the
When you
AS
RDEFAULT option. This option prevents null values from entering the columns if a row is
A

inserted without a value for the column. The default value can be a literal, an expression, or a
SQL function (such as SYSDATE or USER), but the value cannot be the name of another column
or a pseudocolumn (such as NEXTVAL or CURRVAL). The default expression must match the
data type of the column.
Note: CURRVAL and NEXTVAL are explained later in this lesson.

Oracle Database 10g: SQL Fundamentals I 9 - 7
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating Tables
•

Create the table.
CREATE TABLE dept
(deptno
NUMBER(2),
dname
VARCHAR2(14),
loc
VARCHAR2(13),
create_date DATE DEFAULT SYSDATE);
CREATE TABLE succeeded.

•

Confirm table creation.
DESCRIBE dept

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating H
Tables
IM in the slide creates the DEPT table, with four columns: DEPTNO, DNAME, LOC,
S
The example
RA

and CREATE_DATE. The CREATE_DATE column has a default value. If a value is not provided
for an INSERT statement, the system date is automatically inserted.
It further confirms the creation of the table by issuing the DESCRIBE command.
Because creating a table is a DDL statement, an automatic commit takes place when this
statement is executed.

Oracle Database 10g: SQL Fundamentals I 9 - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Data Types
Data Type

Description

VARCHAR2(size) Variable-length character data
CHAR(size)

Fixed-length character data

NUMBER(p,s)

Variable-length numeric data

DATE

Date and time values

LONG

Variable-length character data (up to 2 GB)

CLOB

Character data (up to 4 GB)

RAW and LONG
RAW

Raw binary data

e

l
rab
fe

s

n
-tra
n

o
an
BLOB
Binary data (up to 4 GB)
has ฺ
)
BFILE
Binary data stored in an external file (up e 4 GB)
comGuid to
ailฺ representing the unique
ROWID
A base-64 number m
g system ent
d
address of atrow in its table
@
nc is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Data Types
IMHidentify a column for a table, you need to provide a data type for the column. There
When you
AS
Rare several data types available:
A

N

Data Type

Description

VARCHAR2(size)

Variable-length character data (A maximum size must be
specified: minimum size is 1; maximum size is 4,000.)
Fixed-length character data of length size bytes (Default and
minimum size is 1; maximum size is 2,000.)

CHAR [(size)]
NUMBER [(p,s)]

Number having precision p and scale s (The precision is the
total number of decimal digits, and the scale is the number of
digits to the right of the decimal point; the precision can range
from 1 to 38, and the scale can range from –84 to 127.)

DATE

Date and time values to the nearest second between January 1,
4712 B.C., and December 31, 9999 A.D.

LONG

Variable-length character data (up to 2 GB)

CLOB

Character data (up to 4 GB)
Oracle Database 10g: SQL Fundamentals I 9 - 9
SQL Star International Limited

Data Types (continued)
D escription

RAW(size)

R aw binary data of length size (A m axim um size m ust be specified:
m axim um size is 2,000.)

LONG RAW

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

D ata T ype

R aw binary data of variable length (up to 2 G B )

BLOB

B inary data (up to 4 G B )

BFILE

B inary data stored in an external file (up to 4 G B )

ROWID

A base-64 num ber system representing the unique address of a row
in its table

Guidelines
• A LONG column is not copied when a table is created using a subquery.
• A LONG column cannot be included in a GROUP BY or an ORDER BY clause.
e
abl
r
• Only one LONG column can be used per table.
sfe
n
• No constraints can be defined on a LONG column.
-tra
• You might want to use a CLOB column rather than a LONG column. on

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 9 - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Datetime Data Types
You can use several datetime data types:
Data Type

Description

TIMESTAMP

Date with fractional seconds

INTERVAL YEAR TO
MONTH

Stored as an interval of years
and months

INTERVAL DAY TO
SECOND

Stored as an interval of days, hours, minutes,
and seconds

e

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN DatacTypes
li
Other Datetime
IMH
S
Description
RA Data Type
A

N

l
rab
fe

TIMESTAMP

Enables the time to be stored as a date with fractional seconds. There
are several variations of this data type.

INTERVAL YEAR TO
MONTH

Enables time to be stored as an interval of years and months. Used to
represent the difference between two datetime values in which the only
significant portions are the year and month.
Enables time to be stored as an interval of days, hours, minutes, and
seconds. Used to represent the precise difference between two datetime
values.

INTERVAL DAY TO
SECOND

Note: These datetime data types are available with Oracle9i and later releases. For detailed
information about the datetime data types, see the topics “TIMESTAMP Datatype,” “INTERVAL
YEAR TO MONTH Datatype,” and “INTERVAL DAY TO SECOND Datatype” in the Oracle
SQL Reference.

Oracle Database 10g: SQL Fundamentals I 9 - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Datetime Data Types
•
•

•

The TIMESTAMP data type is an extension of the DATE
data type.
It stores the year, month, and day of the DATE data type
plus hour, minute, and second values as well as the
fractional second value.
You can optionally specify the time zone.

s

n
-tra
n

TIMESTAMP[(fractional_seconds_precision)]
TIMESTAMP[(fractional_seconds_precision)] a
WITH TIME ZONE
has

e

l
rab
fe

no

N

)
ฺ
comGuide
TIMESTAMP[(fractional_seconds_precision)]
ailฺ nt
m
WITH LOCAL TIME ZONE
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C e
AN Type n
TIMESTAMP Data lic
IMH
The TIMESTAMP data type is an extension of the DATE data type. It stores the year, month, and
AS
Rday of the DATE data type plus hour, minute, and second values. This data type is used for
A

storing precise time values.
The fractional_seconds_precision optionally specifies the number of digits in the
fractional part of the SECOND datetime field and can be a number in the range 0 to 9. The
default is 6.
Example
In this example, a table is created named NEW_EMPLOYEES, with a column START_DATE that
has a data type of TIMESTAMP:
CREATE TABLE new_employees
(employee_id NUMBER,
first_name VARCHAR2(15),
last_name VARCHAR2(15),
...
start_date TIMESTAMP(7),
...);

Suppose that two rows are inserted in the NEW_EMPLOYEES table. The displayed output shows
the differences. (A DATE data type defaults to display the DD-MON-RR format.):
Oracle Database 10g: SQL Fundamentals I 9 - 12
SQL Star International Limited

TIMESTAMP Data Type (continued)
SELECT start_date
FROM
new_employees;

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

17-JUN-03 12.00.00.000000 AM
21-SEP-03 12.00.00.000000 AM

TIMESTAMP WITH TIME ZONE Data Type
TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time-zone
displacement in its value. The time-zone displacement is the difference (in hours and
minutes) between local time and UTC (Universal Time Coordinate, formerly known as
Greenwich Mean Time). This data type is used for collecting and evaluating date
information across geographic regions.
For example,
TIMESTAMP '2003-04-15 8:00:00 -8:00'

is the same as

s

n
-tra
n

N

o
a n Standard Time.
That is, 8:00 a.m. Pacific Standard Time is the same as 11:00 a.m.s
Eastern
ha ฺ
This can also be specified as follows:
)
TIMESTAMP '2003-04-15 8:00:00 US/Pacific'
comGuide
ailฺ nt
m e
TIMESTAMP WITH LOCAL TIME ZONE Data Type
d
@gis another variant of TIMESTAMP that
TIMESTAMP WITH LOCAL TIME ct
n ZONE Stu
a
s
includes a time-zone displacement in its thi It differs from TIMESTAMP WITH TIME
mh se value.
i
ZONE in that data stored as database is normalized to the database time zone, and the
r in theo u
(na se
time-zone displacement is nottstored as part of the column data. When users retrieve the
C en
data, it is AN
returned in the users' local session time zone. The time-zone displacement is the
lic
H
difference (in hours and minutes) between local time and UTC.
SIM
AUnlike TIMESTAMP WITH TIME ZONE, you can specify columns of type TIMESTAMP
AR
TIMESTAMP '2003-04-15 11:00:00 -5:00'

WITH LOCAL TIME ZONE as part of a primary or unique key, as in the following example:
CREATE TABLE time_example
(order_date TIMESTAMP WITH LOCAL TIME ZONE);
INSERT INTO time_example VALUES('15-JAN-04 09:34:28 AM');
SELECT *
FROM
time_example;
ORDER_DATE
---------------------------15-JAN-04 09.34.28.000000 AM

The TIMESTAMP WITH LOCAL TIME ZONE type is appropriate for two-tier
applications in which you want to display dates and times using the time zone of the client
system.
Oracle Database 10g: SQL Fundamentals I 9 - 13

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Datetime Data Types
•

The INTERVAL YEAR TO MONTH data type stores a
period of time using the YEAR and MONTH datetime fields:
INTERVAL YEAR [(year_precision)] TO MONTH

•

The INTERVAL DAY TO SECOND data type stores a
period of time in terms of days, hours, minutes, and
seconds:
INTERVAL DAY [(day_precision)]
TO SECOND [(fractional_seconds_precision)]

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN TOcen Data Type
INTERVAL YEAR li MONTH
IMH YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime
S
INTERVAL
RA

fields.
Use INTERVAL YEAR TO MONTH to represent the difference between two datetime values,
where the only significant portions are the year and month. For example, you might use this
value to set a reminder for a date that is 120 months in the future, or check whether 6 months
have elapsed since a particular date.
In the syntax:
year_precision

is the number of digits in the YEAR datetime field.
The default value of year_precision is 2.

Examples
•

INTERVAL '123-2' YEAR(3) TO MONTH

•

INTERVAL '123' YEAR(3)

Indicates an interval of 123 years, 2 months
Indicates an interval of 123 years 0 months
•

INTERVAL '300' MONTH(3)

•

INTERVAL '123' YEAR

Indicates an interval of 300 months
Returns an error because the default precision is 2, and 123 has 3 digits
Oracle Database 10g: SQL Fundamentals I 9 - 14
SQL Star International Limited

INTERVAL YEAR TO MONTH Data Type (continued)
CREATE TABLE time_example2
(loan_duration INTERVAL YEAR (3) TO MONTH);

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

INSERT INTO time_example2 (loan_duration)
VALUES (INTERVAL '120' MONTH(3));
SELECT TO_CHAR(sysdate+loan_duration, 'dd-mon-yyyy')
FROM
time_example2;
--today’s date is 11-11-2008

INTERVAL DAY TO SECOND Data Type

e

l
rab
INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes,e
and
nsf
seconds.
a
n-tr datetime
o
Use INTERVAL DAY TO SECOND to represent the precise difference between two
a n is 36 hours in the
values. For example, you might use this value to set a reminder for a time that
s
harepresent long spans of time,
)
future, or to record the time between the start and end of a race. To
ฺ
ide
coamGuvalue for the days portion.
including multiple years, with high precision, you canlฺ
use large
ai nt
m
In the syntax:
@g Isude
t
day_precision
t the number of digits in the DAY datetime
anc this Sfield. Accepted values are 0 to 9. The default
imh se
s
is 2.
ara to u
fractional_seconds_precision
Is the number of digits in the fractional part of
n
C ( ense
the SECOND datetime field. Accepted values
AN lic
are 0 to 9. The default is 6.
IMH
AS
RExamples
A • INTERVAL '4 5:12:10.222' DAY TO SECOND(3)

N

Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second.
•

INTERVAL '180' DAY(3)

Indicates 180 days.
•

INTERVAL '4 5:12:10.222' DAY TO SECOND(3)

Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second
•

INTERVAL '4 5:12' DAY TO MINUTE

Indicates 4 days, 5 hours, and 12 minutes
•

INTERVAL '400 5' DAY(3) TO HOUR

Indicates 400 days and 5 hours.
•

INTERVAL '11:12:10.2222222' HOUR TO SECOND(7)

Indicates 11 hours, 12 minutes, and 10.2222222 seconds.

Oracle Database 10g: SQL Fundamentals I 9 - 15
SQL Star International Limited

INTERVAL DAY TO SECOND Data Type (continued)
Example

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

CREATE TABLE time_example3
(day_duration INTERVAL DAY (3) TO SECOND);
INSERT INTO time_example3 (day_duration)
VALUES (INTERVAL '180' DAY(3));
SELECT sysdate + day_duration "Half Year"
FROM
time_example3;
--today’s date is 11-11-2008

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 9 - 16
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Including Constraints
•
•
•

Constraints enforce rules at the table level.
Constraints prevent the deletion of a table if there are
dependencies.
The following constraint types are valid:
–
–
–
–
–

NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK

e

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Constraints
IMH server uses constraints to prevent invalid data entry into tables.
AS
RThe Oracle

NA

l
rab
fe

You can use constraints to do the following:
• Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that
table. The constraint must be satisfied for the operation to succeed.
• Prevent the deletion of a table if there are dependencies from other tables
• Provide rules for Oracle tools, such as Oracle Developer

Data Integrity Constraints
Constraint
Description
NOT NULL

Specifies that the column cannot contain a null value

UNIQUE

Specifies a column or combination of columns whose values
must be unique for all rows in the table

PRIMARY KEY

Uniquely identifies each row of the table

FOREIGN KEY

Establishes and enforces a foreign key relationship between the
column and a column of the referenced table

CHECK

Specifies a condition that must be true
Oracle Database 10g: SQL Fundamentals I 9 - 17
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Constraint Guidelines
•

You can name a constraint, or the Oracle server generates
a name with the SYS_Cn format.

•

Create a constraint at either of the following times:
– At the same time as the table is created
– After the table has been created

•
•

Define a constraint at the column or table level.
View a constraint in the data dictionary.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Constraint Guidelines
IMH are stored in the data dictionary. Constraints are easy to reference if you give
AS
RAll constraints

them a meaningful name. Constraint names must follow the standard object-naming rules. If you
do not name your constraint, the Oracle server generates a name with the format SYS_Cn,
where n is an integer so that the constraint name is unique.
Constraints can be defined at the time of table creation or after the table has been created.
For more information, see “Constraints” in Oracle Database SQL Reference.

Oracle Database 10g: SQL Fundamentals I 9 - 18
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Defining Constraints
•

Syntax:
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

•

e

l
rab
fe

Column-level constraint:
column [CONSTRAINT constraint_name] constraint_type, s

•

Table-level constraint:

n

a
n-tr
o

N

an
column,...
has ฺ
)
[CONSTRAINT constraint_name] constraint_type
comGuide
(column, ...),
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Defining Constraints
IMH the syntax for defining constraints when creating a table. You can create the
AS
RThe slide gives the column level or table level. Constraints defined at the column level are
A constraints at either
included when the column is defined. Table-level constraints are defined at the end of the table
definition and must refer to the column or columns on which the constraint pertains in a set of
parentheses.
NOT NULL constraints must be defined at the column level.
Constraints that apply to more than one column must be defined at the table level.
In the syntax:
schema
Is the same as the owner’s name
table
Is the name of the table
DEFAULT expr
Specifies a default value to use if a value is omitted in the
INSERT statement
column
Is the name of the column
datatype
Is the column’s data type and length
column_constraint
Is an integrity constraint as part of the column definition
table_constraint
Is an integrity constraint as part of the table definition

Oracle Database 10g: SQL Fundamentals I 9 - 19
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Defining Constraints
•

Column-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6)
CONSTRAINT emp_emp_id_pk PRIMARY KEY,
first_name
VARCHAR2(20),
...);

•

1

Table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6),
first_name
VARCHAR2(20),
a
...
as
job_id
VARCHAR2(10) NOT NULL,h
)
ฺ
CONSTRAINT emp_emp_id_pk
comGuide
ailฺ t
PRIMARY KEY (EMPLOYEE_ID));
m

e

l
rab
fe

s

n
-tra
n

no

2

N

n
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN lic(continued)
Defining Constraints
IMH are usually created at the same time as the table. Constraints can be added to a table
AS
RConstraints and also temporarily disabled.
A after its creation
Both slide examples create a primary key constraint on the EMPLOYEE_ID column of the
EMPLOYEES table.
1. The first example uses the column-level syntax to define the constraint.
2. The second example uses the table-level syntax to define the constraint.
More details about the primary key constraint are provided later in this lesson.

Oracle Database 10g: SQL Fundamentals I 9 - 20
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

NOT NULL Constraint
Ensures that null values are not permitted for the column:

e

…
NOT NULL constraint
(No row can contain
a null value for
this column.)

NOT NULL
constraint

l
rab
fe

s

n
-tra
n

Absence of NOT NULL
constraint
(Any row can contain
a null value for this
column.)

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
NOT NULL Constraint
IMH
The NOT NULL constraint ensures that the column contains no null values. Columns without
AS
Rthe NOT NULL constraint can contain null values by default. NOT NULL constraints must be
A
defined at the column level.

Oracle Database 10g: SQL Fundamentals I 9 - 21
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

UNIQUE Constraint
UNIQUE constraint

EMPLOYEES

e

l
rab
fe

…
INSERT INTO

Allowed
Not allowed: a
already exists
as

s

n
-tra
n

no

N

h
m) ideฺ
o
ilฺc t Gu
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
UNIQUE Constraint
IMH key integrity constraint requires that every value in a column or set of columns (key)
A UNIQUE
AS
Rbe unique—that is, no two rows of a table can have duplicate values in a specified column or set
A
of columns. The column (or set of columns) included in the definition of the UNIQUE key
constraint is called the unique key. If the UNIQUE constraint comprises more than one column,
that group of columns is called a composite unique key.
UNIQUE constraints enable the input of nulls unless you also define NOT NULL constraints for
the same columns. In fact, any number of rows can include nulls for columns without NOT
NULL constraints because nulls are not considered equal to anything. A null in a column (or in
all columns of a composite UNIQUE key) always satisfies a UNIQUE constraint.

Note: Because of the search mechanism for UNIQUE constraints on more than one column, you
cannot have identical values in the non-null columns of a partially null composite UNIQUE key
constraint.

Oracle Database 10g: SQL Fundamentals I 9 - 22
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

UNIQUE Constraint
Defined at either the table level or the column level:

CREATE TABLE employees(
employee_id
NUMBER(6),
last_name
VARCHAR2(25) NOT NULL,
email
VARCHAR2(25),
e
salary
NUMBER(8,2),
abl
r
commission_pct
NUMBER(2,2),
sfe
n
hire_date
DATE NOT NULL,
-tra
...
non
CONSTRAINT emp_email_uk UNIQUE(email));
sa

N

) ha eฺ
m
ฺco Guid
il
ma ent
g
t@ Stud
c
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C en
AN li(continued)
UNIQUE Constraint c
IMH
UNIQUE constraints can be defined at the column level or table level. A composite unique key is
AS
Rcreated by using the table-level definition.
A
The example in the slide applies the UNIQUE constraint to the EMAIL column of the
EMPLOYEES table. The name of the constraint is EMP_EMAIL_UK.
Note: The Oracle server enforces the UNIQUE constraint by implicitly creating a unique index
on the unique key column or columns.

Oracle Database 10g: SQL Fundamentals I 9 - 23
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

PRIMARY KEY Constraint

DEPARTMENTS
PRIMARY KEY

e

…

Not allowed
(null value)

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
Not allowed
@g tude
t
(50 already exists) anc
S
h
his
t
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C
AN licen
PRIMARY H
KEY Constraint
IM KEY constraint creates a primary key for the table. Only one primary key can be
S
A PRIMARY
RA
INSERT INTO

created for each table. The PRIMARY KEY constraint is a column or set of columns that
uniquely identifies each row in a table. This constraint enforces uniqueness of the column or
column combination and ensures that no column that is part of the primary key can contain a
null value.
Note: Because uniqueness is part of the primary key constraint definition, the Oracle server
enforces the uniqueness by implicitly creating a unique index on the primary key column or
columns.

Oracle Database 10g: SQL Fundamentals I 9 - 24
SQL Star International Limited

FOREIGN KEY Constraint

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DEPARTMENTS

PRIMARY
KEY

…

EMPLOYEES
FOREIGN
KEY

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
…
INSERT INTO m) Not allowed
o u de
ilฺc t G(9idoes not
a
exist)
gm den
@
Allowed
nct is Stu
a th
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
FOREIGN H Constraint
KEY
IM
S
The FOREIGN KEY (or referential integrity) constraint designates a column or combination of
RA

columns as a foreign key and establishes a relationship between a primary key or a unique key in
the same table or a different table.
In the example in the slide, DEPARTMENT_ID has been defined as the foreign key in the
EMPLOYEES table (dependent or child table); it references the DEPARTMENT_ID column of
the DEPARTMENTS table (the referenced or parent table).
Guidelines
• A foreign key value must match an existing value in the parent table or be NULL.
• Foreign keys are based on data values and are purely logical, rather than physical, pointers.

Oracle Database 10g: SQL Fundamentals I 9 - 25
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

FOREIGN KEY Constraint
Defined at either the table level or the column level:

CREATE TABLE employees(
employee_id
NUMBER(6),
last_name
VARCHAR2(25) NOT NULL,
email
VARCHAR2(25),
salary
NUMBER(8,2),
commission_pct
NUMBER(2,2),
hire_date
DATE NOT NULL,
...
department_id
NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)
REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen (continued)
FOREIGN H Constraint
KEY
IM KEY constraints can be defined at the column or table constraint level. A composite
S
FOREIGN
RA

foreign key must be created by using the table-level definition.
The example in the slide defines a FOREIGN KEY constraint on the DEPARTMENT_ID column
of the EMPLOYEES table, using table-level syntax. The name of the constraint is
EMP_DEPTID_FK.
The foreign key can also be defined at the column level, provided the constraint is based on a
single column. The syntax differs in that the keywords FOREIGN KEY do not appear. For
example:
CREATE TABLE employees
(...
department_id NUMBER(4) CONSTRAINT emp_deptid_fk
REFERENCES departments(department_id),
...
)

Oracle Database 10g: SQL Fundamentals I 9 - 26
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

FOREIGN KEY Constraint:
Keywords
•
•
•
•

FOREIGN KEY: Defines the column in the child table at the
table-constraint level
REFERENCES: Identifies the table and column in the parent
table
ON DELETE CASCADE: Deletes the dependent rows in the
child table when a row in the parent table is deleted
e
abl
ON DELETE SET NULL: Converts dependent foreign key fer
s
values to null
tran

-

non
a

NA

has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen Keywords
FOREIGN H Constraint:
KEY
IM key is defined in the child table, and the table containing the referenced column is
AS
RThe foreign

the parent table. The foreign key is defined using a combination of the following keywords:
• FOREIGN KEY is used to define the column in the child table at the table-constraint level.
• REFERENCES identifies the table and column in the parent table.
• ON DELETE CASCADE indicates that when the row in the parent table is deleted, the
dependent rows in the child table are also deleted.
• ON DELETE SET NULL converts foreign key values to null when the parent value is
removed.
The default behavior is called the restrict rule, which disallows the update or deletion of
referenced data.
Without the ON DELETE CASCADE or the ON DELETE SET NULL options, the row in the
parent table cannot be deleted if it is referenced in the child table.

Oracle Database 10g: SQL Fundamentals I 9 - 27
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

CHECK Constraint
•
•

Defines a condition that each row must satisfy
The following expressions are not allowed:
– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM
pseudocolumns
– Calls to SYSDATE, UID, USER, and USERENV functions
– Queries that refer to other values in other rows
..., salary NUMBER(2)
CONSTRAINT emp_salary_min
CHECK (salary > 0),...

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
CHECK Constraint
IMH constraint defines a condition that each row must satisfy. The condition can use the
The CHECK
AS
Rsame constructs as query conditions, with the following exceptions:
A
• References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns
• Calls to SYSDATE, UID, USER, and USERENV functions
• Queries that refer to other values in other rows
A single column can have multiple CHECK constraints that refer to the column in its definition.
There is no limit to the number of CHECK constraints that you can define on a column.
CHECK constraints can be defined at the column level or table level.
CREATE TABLE employees
(...
salary NUMBER(8,2) CONSTRAINT emp_salary_min
CHECK (salary > 0),
...

Oracle Database 10g: SQL Fundamentals I 9 - 28
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

CREATE TABLE: Example
CREATE TABLE employees
( employee_id
NUMBER(6)
CONSTRAINT
emp_employee_id
, first_name
VARCHAR2(20)
, last_name
VARCHAR2(25)
CONSTRAINT
emp_last_name_nn
, email
VARCHAR2(25)
CONSTRAINT
emp_email_nn
CONSTRAINT
emp_email_uk
, phone_number
VARCHAR2(20)
, hire_date
DATE
CONSTRAINT
emp_hire_date_nn
, job_id
VARCHAR2(10)
CONSTRAINT
emp_job_nn
, salary
NUMBER(8,2)
CONSTRAINT
emp_salary_ck
, commission_pct NUMBER(2,2)
, manager_id
NUMBER(6)
, department_id NUMBER(4)
CONSTRAINT
emp_dept_fk
departments (department_id));

PRIMARY KEY

NOT NULL
NOT NULL
UNIQUE

e

NOT NULL
NOT NULL

l
rab
fe

s

n
-tra
n

o
an
CHECK (salary>0)
has ฺ
)
comGuide
ailฺ nt
m
REFERENCES
@g tude
ct
S
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C en
AN Example
CREATE TABLE: lic
IMH shows the statement used to create the EMPLOYEES table in the HR schema.
S
The example
RA
A

N

Oracle Database 10g: SQL Fundamentals I 9 - 29
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Violating Constraints

UPDATE employees
SET
department_id = 55
WHERE department_id = 110;

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
Department 55 does not exist. gm de
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Integrity Constraint Error
IMHhave constraints in place on columns, an error is returned to you if you try to violate
AS
RWhen you rule.
A the constraint
For example, if you attempt to update a record with a value that is tied to an integrity constraint,
an error is returned.
In the example in the slide, department 55 does not exist in the parent table, DEPARTMENTS,
and so you receive the parent key violation ORA-02291.

Oracle Database 10g: SQL Fundamentals I 9 - 30
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Violating Constraints
You cannot delete a row that contains a primary key that is
used as a foreign key in another table.

DELETE FROM departments
WHERE
department_id = 60;

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen (continued)
Integrity Constraint Error
IMH to delete a record with a value that is tied to an integrity constraint, an error is
AS
RIf you attempt
A returned.
The example in the slide tries to delete department 60 from the DEPARTMENTS table, but it
results in an error because that department number is used as a foreign key in the EMPLOYEES
table. If the parent record that you attempt to delete has child records, then you receive the child
record found violation ORA-02292.
The following statement works because there are no employees in department 70:
DELETE FROM
WHERE

departments
department_id = 70;

1 row deleted.

Oracle Database 10g: SQL Fundamentals I 9 - 31
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Table
by Using a Subquery
•

Create a table and insert rows by combining the CREATE
TABLE statement and the AS subquery option.
CREATE TABLE table
[(column, column...)]
AS subquery;

•
•

Match the number of specified columns to the number of
e
abl
r
subquery columns.
sfe
n
Define columns with column names and
-tra
non
default values.
a

NA

has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN fromen in Another Table
Creating HTable lic Rows
a
IM method for creating a table is to apply the AS subquery clause, which both creates
S
A second
RA
the table and inserts rows returned from the subquery.

In the syntax:
table
is the name of the table
column
is the name of the column, default value, and integrity constraint
subquery is the SELECT statement that defines the set of rows to be inserted into
the new table
Guidelines
• The table is created with the specified column names, and the rows retrieved by the
SELECT statement are inserted into the table.
• The column definition can contain only the column name and default value.
• If column specifications are given, the number of columns must equal the number of
columns in the subquery SELECT list.
• If no column specifications are given, the column names of the table are the same as the
column names in the subquery.
• The column data type definitions and the NOT NULL constraint are passed to the new
table. The other constraint rules are not passed to the new table. However, you can add
constraints in the column definition.
Oracle Database 10g: SQL Fundamentals I 9 - 32
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Table
by Using a Subquery
CREATE TABLE dept80
AS
SELECT employee_id, last_name,
salary*12 ANNSAL,
hire_date
FROM
employees
WHERE
department_id = 80;
CREATE TABLE Succeeded.
DESCRIBE dept80

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN fromen in Another Table (continued)
Creating HTable lic Rows
a
IM example creates a table named DEPT80, which contains details of all the employees
S
The slide
RA
working in department 80. Notice that the data for the DEPT80 table comes from the
EMPLOYEES table.

You can verify the existence of a database table and check column definitions by using the
DESCRIBE command.
Be sure to provide a column alias when selecting an expression. The expression SALARY*12 is
given the alias ANNSAL. Without the alias, the following error is generated:

Oracle Database 10g: SQL Fundamentals I 9 - 33
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

ALTER TABLE Statement
Use the ALTER TABLE statement to:
•
•
•
•

Add a new column
Modify an existing column
Define a default value for the new column
Drop a column

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
ALTER TABLE Statement
M
IyouH a table, you may need to change the table structure for any of the following
After
AS create
ARreasons:
• You omitted a column.
• Your column definition needs to be changed.
• You need to remove columns.
You can do this by using the ALTER TABLE statement. For information about the
ALTER TABLE statement, see the Oracle Database 10g SQL Fundamentals II course.

Oracle Database 10g: SQL Fundamentals I 9 - 34
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Dropping a Table
•
•
•
•
•

All data and structure in the table are deleted.
Any pending transactions are committed.
All indexes are dropped.
All constraints are dropped.
You cannot roll back the DROP TABLE statement.

e

DROP TABLE dept80;
DROP TABLE succeeded.

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
DroppingH Table
a
IM TABLE statement removes the definition of an Oracle table. When you drop a table,
S
The DROP
RA
the database loses all the data in the table and all the indexes associated with it.
Syntax
DROP TABLE table
In the syntax, table is the name of the table.
Guidelines
• All data is deleted from the table.
• Any views and synonyms remain but are invalid.
• Any pending transactions are committed.
• Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a
table.
Note: The DROP TABLE statement, once executed, is irreversible. The Oracle server does not
question the action when you issue the DROP TABLE statement. If you own that table or have a
high-level privilege, then the table is immediately removed. As with all DDL statements, DROP
TABLE is committed automatically.

Oracle Database 10g: SQL Fundamentals I 9 - 35
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Summary
In this lesson, you should have learned how to:
• Use the CREATE TABLE statement to create a table and
include constraints
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
e
abl
r
• Create a simple table
sfe
an
• Explain how constraints are created at the time of n-tr
table
o
creation
an
has ฺ
• Describe how schema objects work m)
e

NA

o
ilฺc t Guid
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Summary
IMH you should have learned how to do the following:
AS
RIn this lesson,

CREATE TABLE
• Use the CREATE TABLE statement to create a table and include constraints.
• Create a table based on another table by using a subquery.
DROP TABLE
• Remove rows and a table structure.
• Once executed, this statement cannot be rolled back.

Oracle Database 10g: SQL Fundamentals I 9 - 36
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 9: Overview
This practice covers the following topics:
• Creating new tables
• Creating a new table by using the CREATE TABLE AS
syntax
• Verifying that tables exist
• Dropping tables

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Practice 9: Overview
IMH tables by using the CREATE TABLE statement. Confirm that the new table is added
Create new
AS
Rto the database. Create the syntax in the command file, and then execute the command file to
A
create the table.

Oracle Database 10g: SQL Fundamentals I 9 - 37
SQL Star International Limited

Practice 9
1. Create the DEPT table based on the following table instance chart. Place the
syntax in a script called lab_09_01.sql, and then execute the statement in the script to
create the table. Confirm that the table is created.
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Column Name

ID

Key Type

Primary key

NAME

Nulls/Unique
FK Table
FK Column
Data type

NUMBER

VARCHAR2

Length

7

25

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
g DEPARTMENTS table. Include only columns
2. Populate the DEPT table with data from them de
t@ Stu
that you need.
a c this
hthenfollowing table instance chart. Place the syntax in
m
3. Create the EMP table based on
asi use then execute the statement in the script to create the
r
a script called lab_09_03.sql, and
(na se to created.
table. Confirm that the table is
C
ANNameicen
LAST_NAME
FIRST_NAME
DEPT_ID
l ID
Column
IMH Type
S
RA Key
Nulls/Unique
FK Table

DEPT

FK Column

ID

Data type

NUMBER

VARCHAR2

VARCHAR2

NUMBER

Length

7

25

25

7

Oracle Database 10g: SQL Fundamentals I 9 - 38
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 9 (continued)
4. 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.
5. Drop the EMP table.

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 9 - 39
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Creating Other Schema Objects

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Objectives
After completing this lesson, you should be able to do the
following:
• Create simple and complex views
• Retrieve data from views
• Create, maintain, and use sequences
• Create and maintain indexes
• Create private and public synonyms

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Objectives
IMH you are introduced to the view, sequence, synonym, and index objects. You are
AS
RIn this lesson,
taught the basics of creating and using views, sequences, and indexes.

Oracle Database 10g: SQL Fundamentals I 10 - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Database Objects

Object

Description

Table

Basic unit of storage; composed of rows

View

Logically represents subsets of data from one or
more tables

Sequence

Generates numeric values

Index

Improves the performance of some queries

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
DatabaseH
Objects
IM several other objects in a database in addition to tables. In this lesson, you learn about
AS
RThere are
Synonym

Gives alternative names to objects

views, sequences, indexes, and synonyms.

With views, you can present and hide data from tables.
Many applications require the use of unique numbers as primary key values. You can either
build code into the application to handle this requirement or use a sequence to generate unique
numbers.
If you want to improve the performance of some queries, you should consider creating an index.
You can also use indexes to enforce uniqueness on a column or a collection of columns.
You can provide alternative names for objects by using synonyms.

Oracle Database 10g: SQL Fundamentals I 10 - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

What Is a View?

EMPLOYEES table

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
What Is aH
View?
IMpresent logical subsets or combinations of data by creating views of tables. A view is a
AS
RYou can based on a table or another view. A view contains no data of its own but is like a
A logical table
window through which data from tables can be viewed or changed. The tables on which a view
is based are called base tables. The view is stored as a SELECT statement in the data dictionary.

Oracle Database 10g: SQL Fundamentals I 10 - 4
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Advantages of Views

To restrict
data access

To make complex
queries easy

e

l
rab
fe

s

n
-tra
n

N

o
an
To present
To provide
has ฺ
different views of
data
)
same data
independence
comGuthee
ilฺ t id
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
ANViews en
lic
Advantages of
H
IM
•
ASViews restrict access to the data because the view can display selected columns from the
AR table.
• Views can be used to make simple queries to retrieve the results of complicated queries. For
example, views can be used to query information from multiple tables without the user
knowing how to write a join statement.
• Views provide data independence for ad hoc users and application programs. One view can
be used to retrieve data from several tables.
• Views provide groups of users access to data according to their particular criteria.
For more information, see “CREATE VIEW” in the Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Simple Views and Complex Views

Feature

Simple Views

Complex Views

Number of tables

One

One or more

Contain functions

No

Yes

Contain groups of data

No

Yes

DML operations through a
view

Yes

Not always

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Complex Views
Simple Views and lic
IMH classifications for views: simple and complex. The basic difference is related to
AS two
RThere are (INSERT, UPDATE, and DELETE) operations.
A the DML
• A simple view is one that:
- Derives data from only one table
- Contains no functions or groups of data
- Can perform DML operations through the view
• A complex view is one that:
- Derives data from many tables
- Contains functions or groups of data
- Does not always allow DML operations through the view

Oracle Database 10g: SQL Fundamentals I 10 - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a View
•

You embed a subquery in the CREATE VIEW statement:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];

•

e

l
rab
fe

The subquery can contain complex SELECT syntax.

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating HView
a
IMcreate a view by embedding a subquery in the CREATE VIEW statement.
S
You can
RA
In the syntax:
OR REPLACE
FORCE
NOFORCE
view
alias

Re-creates the view if it already exists
Creates the view regardless of whether or not the base tables exist
Creates the view only if the base tables exist (This is the default.)
Is the name of the view
Specifies names for the expressions selected by the view’s query
(The number of aliases must match the number of expressions
selected by the view.)
subquery
Is a complete SELECT statement (You can use aliases for the
columns in the SELECT list.)
WITH CHECK OPTION Specifies that only those rows that are accessible to the view can
be inserted or updated
constraint
Is the name assigned to the CHECK OPTION constraint
WITH READ ONLY
ensures that no DML operations can be performed on this view

Oracle Database 10g: SQL Fundamentals I 10 - 7
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a View
•

Create the EMPVU80 view, which contains details of
employees in department 80:
CREATE VIEW
AS SELECT
FROM
WHERE
CREATE VIEW

empvu80
employee_id, last_name, salary
employees
department_id = 80;
succeeded.

e

N

l
rab
• Describe the structure of the view by using the DESCRIBEfe
s
tran
command:
non
a
DESCRIBE empvu80
as
h
m) ideฺ
o
ilฺc t Gu
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C en
AN (continued)
Creating HView lic
a
IM in the slide creates a view that contains the employee number, last name, and
AS
RThe example employee in department 80.
A salary for each
You can display the structure of the view by using the DESCRIBE command.

Guidelines for Creating a View
• The subquery that defines a view can contain complex SELECT syntax, including joins,
groups, and subqueries.
• If you do not specify a constraint name for a view created with the WITH CHECK
OPTION, the system assigns a default name in the format SYS_Cn.
• You can use the OR REPLACE option to change the definition of the view without
dropping and re-creating it or regranting object privileges previously granted on it.

Oracle Database 10g: SQL Fundamentals I 10 - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a View
•

Create a view by using column aliases in the subquery:
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM
employees
WHERE
department_id = 50;
CREATE VIEW succeeded.

•

Select the columns from this view by the given alias ns
a
names:
n-tr
o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN (continued)
Creating HView lic
a
IMcontrol the column names by including column aliases in the subquery.
AS
RYou can

NA

The example in the slide creates a view containing the employee number (EMPLOYEE_ID) with
the alias ID_NUMBER, name (LAST_NAME) with the alias NAME, and annual salary (SALARY)
with the alias ANN_SALARY for every employee in department 50.
As an alternative, you can use an alias after the CREATE statement and before the SELECT
subquery. The number of aliases listed must match the number of expressions selected in the
subquery.
CREATE OR REPLACE VIEW
salvu50 (ID_NUMBER, NAME, ANN_SALARY)
AS SELECT employee_id, last_name, salary*12
FROM
employees
WHERE
department_id = 50;
CREATE VIEW succeeded.

Oracle Database 10g: SQL Fundamentals I 10 - 9

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Retrieving Data from a View

SELECT *
FROM
salvu50;

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C e
AN from a n
lic View
Retrieving Data
H
IM
You can retrieve data from a view as you would from any table. You can display either the
AS
R
contents of the entire view or just specific rows and columns.

Oracle Database 10g: SQL Fundamentals I 10 - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Modifying a View
•

Modify the EMPVU80 view by using a CREATE OR
REPLACE VIEW clause. Add an alias for each column
name:
CREATE OR REPLACE VIEW empvu80
(id_number, name, sal, department_id)
AS SELECT employee_id, first_name || ' '
|| last_name, salary, department_id
FROM
employees
WHERE
department_id = 80;
CREATE VIEW succeeded.

•

e

l
rab
fe

s

n
-tra
n

o

Column aliases in the CREATE OR REPLACE VIEW
an
s
clause are listed in the same order as ) ha ฺ
the columns in the
m
e
subquery.
ฺco uid
il

NA

G
a
gm dent
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Modifying a View
M
Ithe H REPLACE option, a view can be created even if one exists with this name already,
With
AS OR
R
thus replacing the old version of the view for its owner. This means that the view can be altered
without dropping, re-creating, and regranting object privileges.
Note: When assigning column aliases in the CREATE OR REPLACE VIEW clause, remember
that the aliases are listed in the same order as the columns in the subquery.

Oracle Database 10g: SQL Fundamentals I 10 - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Complex View
Create a complex view that contains group functions to display
values from two tables:
CREATE OR REPLACE VIEW dept_sum_vu
(name, minsal, maxsal, avgsal)
AS SELECT
d.department_name, MIN(e.salary),
MAX(e.salary),AVG(e.salary)
FROM
employees e JOIN departments d
ON
(e.department_id = d.department_id)
GROUP BY d.department_name;
CREATE VIEW succeeded.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating HComplex View
a
IM in the slide creates a complex view of department names, minimum salaries,
AS
RThe example

maximum salaries, and average salaries by department. Note that alternative names have been
specified for the view. This is a requirement if any column of the view is derived from a
function or an expression.
You can view the structure of the view by using the DESCRIBE command. Display the contents
of the view by issuing a SELECT statement.
SELECT
FROM

*
dept_sum_vu;

Oracle Database 10g: SQL Fundamentals I 10 - 12
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Rules for Performing
DML Operations on a View
•
•

You can usually perform DML operations
on simple views.
You cannot remove a row if the view contains the
following:
–
–
–
–

Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudocolumn ROWNUM keyword

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Operations on a View
Performing DML lic
IMH
AS
RYou can perform DML operations on data through a view if those operations follow certain
rules.

You can remove a row from a view unless it contains any of the following:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword

Oracle Database 10g: SQL Fundamentals I 10 - 13
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Rules for Performing
DML Operations on a View
You cannot modify data in a view if it contains:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword
•

e

l
rab
fe

Columns defined by expressions

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Operations on a View (continued)
Performing DML lic
IMH data through a view unless it contains any of the conditions mentioned in the
AS
RYou can modify
previous slide or columns defined by expressions (for example, SALARY * 12).

Oracle Database 10g: SQL Fundamentals I 10 - 14
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Rules for Performing
DML Operations on a View
You cannot add data through a view if the view includes:
• Group functions
• A GROUP BY clause
• The DISTINCT keyword
• The pseudocolumn ROWNUM keyword
•
•

e
Columns defined by expressions
abl
r
NOT NULL columns in the base tables that are not selectede
sf
n
-tra
by the view
on

NA

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Operations on a View (continued)
Performing DML lic
IMH data through a view unless it contains any of the items listed in the slide. You
AS
RYou can add

cannot add data to a view if the view contains NOT NULL columns without default values in the
base table. All required values must be present in the view. Remember that you are adding
values directly to the underlying table through the view.
For more information, see “CREATE VIEW” in the Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 15
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the WITH CHECK OPTION Clause
•

You can ensure that DML operations performed on the
view stay in the domain of the view by using the WITH
CHECK OPTION clause:
CREATE OR REPLACE VIEW empvu20
AS SELECT
*
FROM
employees
WHERE
department_id = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck ;
CREATE VIEW succeeded.

•

e

l
rab
fe

s

n
-tra
n

o

Any attempt to change the department numbern any row
a for
as CHECK
h
in the view fails because it violates the)WITH ฺ
m ide
o u
OPTION constraint.
ilฺc

N

G
a
gm dent
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C e
AN CHECKnOPTION Clause
Using the WITH
lic
H
IM
It is possible to perform referential integrity checks through views. You can also enforce
AS
ARconstraints at the database level. The view can be used to protect data integrity, but the use is
very limited.
The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs performed through
the view cannot create rows that the view cannot select, and therefore it enables integrity
constraints and data validation checks to be enforced on data being inserted or updated.
Note: The WITH CHECK OPTION clause relates to inserts and updates on the view only. It has
no effect on deletes.
If there is an attempt to perform DML operations on rows that the view has not selected, an
error is displayed, along with the constraint name if that has been specified.
UPDATE empvu20
SET
department_id = 10
WHERE employee_id = 201;

Oracle Database 10g: SQL Fundamentals I 10 - 16
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the WITH CHECK OPTION Clause (continued)

e

l
rab
fe

ns
trathe view
Note: No rows are updated because if the department number were to changen-10,
no to clause,
would no longer be able to see that employee. With the WITH CHECKaOPTION
therefore, the view can see only employees in department 20 and does not allow the department
has ฺ
)
number for those employees to be changed through the view.
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
IM
AS
AR

N

Oracle Database 10g: SQL Fundamentals I 10 - 17
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Denying DML Operations
•

You can ensure that no DML operations occur by adding
the WITH READ ONLY option to your view definition.

•

Any attempt to perform a DML operation on any row in the
view results in an Oracle server error.

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Denying DML Operations
IMH that no DML operations occur on your view by creating it with the WITH READ
You can ensure
AS
RONLY option. The example in the next slide modifies the EMPVU10 view to prevent any DML
A
operations on the view.

Oracle Database 10g: SQL Fundamentals I 10 - 18
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Denying DML Operations

CREATE OR REPLACE VIEW empvu10
(employee_number, employee_name, job_title)
AS SELECT
employee_id, last_name, job_id
FROM
employees
WHERE
department_id = 10
WITH READ ONLY ;
CREATE VIEW succeeded.

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen (continued)
Denying DML Operations
IMH to remove a row from a view with a read-only constraint results in an error:
AS
RAny attempt
A
DELETE FROM empvu10
WHERE employee_number = 200;

Any attempt to insert a row or modify a row using the view with a read-only constraint results in
an Oracle server error:
01733: virtual column not allowed here.
Oracle Database 10g: SQL Fundamentals I 10 - 19
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Removing a View
You can remove a view without losing data because a view is
based on underlying tables in the database.
DROP VIEW view;

e

DROP VIEW empvu80;
DROP VIEW empvu80 succeeded.

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Removing a View
H
IMthe DROP VIEW statement to remove a view. The statement removes the view
S
You use
RA

NA

l
rab
fe

definition from the database. Dropping views has no effect on the tables on which the view was
based. Views or other applications based on deleted views become invalid. Only the creator or a
user with the DROP ANY VIEW privilege can remove a view.
In the syntax:
view
is the name of the view

Oracle Database 10g: SQL Fundamentals I 10 - 20
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 10: Overview of Part 1
This practice covers the following topics:
• Creating a simple view
• Creating a complex view
• Creating a view with a check constraint
• Attempting to modify data in the view
• Removing views

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen Part 1
Practice 10: Overview of
IMH lesson’s practice provides you with a variety of exercises in creating, using, and
Part 1 of
AS
Rremovingthis
A
views.
Complete questions 1–6 at the end of this lesson.

Oracle Database 10g: SQL Fundamentals I 10 - 21
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Sequences

Object

Description

Table

Basic unit of storage; composed of rows

View

Logically represents subsets of data from one or
more tables

Sequence

Generates numeric values

Index

Improves the performance of some queries

Synonym

Gives alternative names to objects

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Sequences
IMH is a database object that creates integer values. You can create sequences and then
AS
RA sequence
use them to generate numbers.

Oracle Database 10g: SQL Fundamentals I 10 - 22
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Sequences
A sequence:
• Can automatically generate unique numbers
• Is a sharable object
• Can be used to create a primary key value
• Replaces application code
• Speeds up the efficiency of accessing sequence values
when cached in memory

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
c6omGuide 10
2
4
8
ailฺ nt7
1
3 m 5
9
g
e
d
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Sequences (continued)
IMH is a user-created database object that can be shared by multiple users to generate
AS
RA sequence
integers.

You can define a sequence to generate unique values or to recycle and use the same numbers
again.
A typical usage for sequences is to create a primary key value, which must be unique for each
row. The sequence is generated and incremented (or decremented) by an internal Oracle routine.
This can be a time-saving object because it can reduce the amount of application code needed to
write a sequence-generating routine.
Sequence numbers are stored and generated independently of tables. Therefore, the same
sequence can be used for multiple tables.

Oracle Database 10g: SQL Fundamentals I 10 - 23
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

CREATE SEQUENCE Statement:
Syntax
Define a sequence to generate sequential numbers
automatically:

CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating HSequence
a
IM
S
Automatically generate sequential numbers by using the CREATE SEQUENCE statement.
RA
In the syntax:
sequence
INCREMENT BY n

START WITH n
MAXVALUE n
NOMAXVALUE

MINVALUE n
NOMINVALUE

Is the name of the sequence generator
Specifies the interval between sequence numbers, where
n is an integer (If this clause is omitted, the sequence
increments by 1.)
Specifies the first sequence number to be generated (If this
clause is omitted, the sequence starts with 1.)
Specifies the maximum value the sequence can generate
Specifies a maximum value of 10^27 for an ascending
sequence and –1 for a descending sequence (This is the
default option.)
Specifies the minimum sequence value
Specifies a minimum value of 1 for an ascending sequence
and –(10^26) for a descending sequence (This is the default
option.)

Oracle Database 10g: SQL Fundamentals I 10 - 24
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Sequence
•
•

Create a sequence named DEPT_DEPTID_SEQ to be used
for the primary key of the DEPARTMENTS table.
Do not use the CYCLE option.

CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
CREATE SEQUENCE succeeded.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating HSequence (continued)
a
IM | NOCYCLE
S
CYCLE
Specifies whether the sequence continues to generate
RA

values after reaching its maximum or minimum value
(NOCYCLE is the default option.)
CACHE n | NOCACHE
Specifies how many values the Oracle server preallocates
and keeps in memory (By default, the Oracle server
caches 20 values.)
The example in the slide creates a sequence named DEPT_DEPTID_SEQ to be used for the
DEPARTMENT_ID column of the DEPARTMENTS table. The sequence starts at 120, does not
allow caching, and does not cycle.
Do not use the CYCLE option if the sequence is used to generate primary key values, unless you
have a reliable mechanism that purges old rows faster than the sequence cycles.
For more information, see “CREATE SEQUENCE” in the Oracle SQL Reference.
Note: The sequence is not tied to a table. Generally, you should name the sequence after its
intended use. However, the sequence can be used anywhere, regardless of its name.

Oracle Database 10g: SQL Fundamentals I 10 - 25
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

NEXTVAL and CURRVAL Pseudocolumns
•

•
•

NEXTVAL returns the next available sequence value. It
returns a unique value every time it is referenced, even for
different users.
CURRVAL obtains the current sequence value.
NEXTVAL must be issued for that sequence before
CURRVAL contains a value.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
NEXTVAL H CURRVAL Pseudocolumns
M and
Iyou create your sequence, it generates sequential numbers for use in your tables. Reference
AS
RAfter
the sequence values by using the NEXTVAL and CURRVAL pseudocolumns.

The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a specified
sequence. You must qualify NEXTVAL with the sequence name. When you reference
sequence.NEXTVAL, a new sequence number is generated and the current sequence number
is placed in CURRVAL.
The CURRVAL pseudocolumn is used to refer to a sequence number that the current user has just
generated. NEXTVAL must be used to generate a sequence number in the current user’s session
before CURRVAL can be referenced. You must qualify CURRVAL with the sequence name.
When you reference sequence.CURRVAL, the last value returned to that user’s process is
displayed.

Oracle Database 10g: SQL Fundamentals I 10 - 26
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

NEXTVAL and CURRVAL Pseudocolumns (continued)
Rules for Using NEXTVAL and CURRVAL
You can use NEXTVAL and CURRVAL in the following contexts:
• The SELECT list of a SELECT statement that is not part of a subquery
• The SELECT list of a subquery in an INSERT statement
• The VALUES clause of an INSERT statement
• The SET clause of an UPDATE statement
You cannot use NEXTVAL and CURRVAL in the following contexts:
• The SELECT list of a view
• A SELECT statement with the DISTINCT keyword
• A SELECT statement with GROUP BY, HAVING, or ORDER BY clauses
• A subquery in a SELECT, DELETE, or UPDATE statement
e
• The DEFAULT expression in a CREATE TABLE or ALTER TABLE statement
abl
r
For more information, see “Pseudocolumns” and “CREATE SEQUENCE” in Oracle SQLfe
s
n
Reference.
-tra

non
a

has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 10 - 27
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using a Sequence
•

Insert a new department named “Support” in location ID
2500:
INSERT INTO departments(department_id,
department_name, location_id)
VALUES
(dept_deptid_seq.NEXTVAL,
'Support', 2500);
1 row created.

•

e

l
rab
fe

s

View the current value for the DEPT_DEPTID_SEQ -tran
sequence:
non

N

a
as
h
SELECT
dept_deptid_seq.CURRVAL
m) ideฺ
o
FROM
dual;
ilฺc t Gu
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Using a Sequence
IMH in the slide inserts a new department in the DEPARTMENTS table. It uses the
The example
AS
RDEPT_DEPTID_SEQ sequence to generate a new department number as follows.
A
You can view the current value of the sequence:
SELECT dept_deptid_seq.CURRVAL
FROM
dual;

Suppose that you now want to hire employees to staff the new department. The INSERT
statement to be executed for all new employees can include the following code:
INSERT INTO employees (employee_id, department_id, ...)
VALUES (employees_seq.NEXTVAL, dept_deptid_seq .CURRVAL, ...);

Note: The preceding example assumes that a sequence called EMPLOYEE_SEQ has already
been created to generate new employee numbers.

Oracle Database 10g: SQL Fundamentals I 10 - 28
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Caching Sequence Values
•
•

Caching sequence values in memory gives faster access
to those values.
Gaps in sequence values can occur when:
– A rollback occurs
– The system crashes
– A sequence is used in another table

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN liValues
Caching Sequence c
IMH sequences in memory to provide faster access to those sequence values. The
You can cache
AS
Rcache is populated the first time you refer to the sequence. Each request for the next sequence
A
value is retrieved from the cached sequence. After the last sequence value is used, the next
request for the sequence pulls another cache of sequences into memory.
Gaps in the Sequence
Although sequence generators issue sequential numbers without gaps, this action occurs
independent of a commit or rollback. Therefore, if you roll back a statement containing a
sequence, the number is lost.
Another event that can cause gaps in the sequence is a system crash. If the sequence caches
values in memory, those values are lost if the system crashes.
Because sequences are not tied directly to tables, the same sequence can be used for multiple
tables. If you do so, each table can contain gaps in the sequential numbers.

Oracle Database 10g: SQL Fundamentals I 10 - 29
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Modifying a Sequence
Change the increment value, maximum value, minimum value,
cycle option, or cache option:

ALTER SEQUENCE dept_deptid_seq
INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE;
ALTER SEQUENCE dept_deptid_seq succeeded.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Modifying a Sequence
IMH the MAXVALUE limit for your sequence, no additional values from the sequence are
S
If you reach
RA
allocated and you will receive an error indicating that the sequence exceeds the MAXVALUE. To
continue to use the sequence, you can modify it by using the ALTER SEQUENCE statement.
Syntax
ALTER SEQUENCE
sequence
[INCREMENT BY n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

In the syntax, sequence is the name of the sequence generator.
For more information, see “ALTER SEQUENCE” in the Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 30
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Guidelines for Modifying
a Sequence
•
•
•
•
•

You must be the owner or have the ALTER privilege for the
sequence.
Only future sequence numbers are affected.
The sequence must be dropped and
re-created to restart the sequence at a different number.
Some validation is performed.
e
abl
To remove a sequence, use the DROP statement:
fer

s

n
-tra
n

NA

o
an
) ha eฺ
m
ฺco Guid
il
ma ent
g
t@ Stud
c
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C en
ANModifying a Sequence
lic
Guidelines for
H
IM
•
ASYou must be the owner or have the ALTER privilege for the sequence to modify it. You
R
DROP SEQUENCE dept_deptid_seq;
DROP SEQUENCE dept_deptid_seq succeeded.s

must be the owner or have the DROP ANY SEQUENCE privilege to remove it.
• Only future sequence numbers are affected by the ALTER SEQUENCE statement.
• The START WITH option cannot be changed using ALTER SEQUENCE. The sequence
must be dropped and re-created to restart the sequence at a different number.
• Some validation is performed. For example, a new MAXVALUE that is less than the current
sequence number cannot be imposed.
ALTER SEQUENCE dept_deptid_seq
INCREMENT BY 20
MAXVALUE 90
NOCACHE
NOCYCLE;

Oracle Database 10g: SQL Fundamentals I 10 - 31
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Guidelines for Modifying a Sequence (continued)

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 10 - 32
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Indexes

Object

Description

Table

Basic unit of storage; composed of rows

View

Logically represents subsets of data from one or
more tables

Sequence

Generates numeric values

Index

Improves the performance of some queries

Synonym

Gives alternative names to objects

e

l
rab
fe

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H

Indexes
IM
Indexes are database objects that you can create to improve the performance of some queries.
AS
R
NA Indexes can also be created automatically by the server when you create a primary key or unique
constraint.

Oracle Database 10g: SQL Fundamentals I 10 - 33
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Indexes
An index:
• Is a schema object
• Can be used by the Oracle server to speed up the retrieval
of rows by using a pointer
• Can reduce disk I/O by using a rapid path access method
to locate data quickly
e
abl
r
• Is independent of the table that it indexes
sfe
tran
• Is used and maintained automatically by the Oracle-server
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Indexes (continued)
IMHserver index is a schema object that can speed up the retrieval of rows by using a
AS
RAn Oracle
A pointer. Indexes can be created explicitly or automatically. If you do not have an index on the

column, then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to reduce the necessity
of disk I/O by using an indexed path to locate data quickly. The index is used and maintained
automatically by the Oracle server. After an index is created, no direct activity is required by the
user.
Indexes are logically and physically independent of the table that they index. This means that
they can be created or dropped at any time and have no effect on the base tables or other
indexes.
Note: When you drop a table, corresponding indexes are also dropped.
For more information, see “Schema Objects: Indexes” in Database Concepts.

Oracle Database 10g: SQL Fundamentals I 10 - 34
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

How Are Indexes Created?
•

•

Automatically: A unique index is created automatically
when you define a PRIMARY KEY or UNIQUE constraint in
a table definition.

Manually: Users can create nonunique indexes on
columns to speed up access to the rows.

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Types of H
Indexes
IM of indexes can be created.
AS
RTwo types
A

N

e

l
rab
fe

Unique index: The Oracle server automatically creates this index when you define a column in
a table to have a PRIMARY KEY or a UNIQUE key constraint. The name of the index is the
name that is given to the constraint.
Nonunique index: This is an index that a user can create. For example, you can create a
FOREIGN KEY column index for a join in a query to improve retrieval speed.
Note: You can manually create a unique index, but it is recommended that you create a unique
constraint, which implicitly creates a unique index.

Oracle Database 10g: SQL Fundamentals I 10 - 35
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating an Index
•

Create an index on one or more columns:
CREATE INDEX index
ON table (column[, column]...);

•

Improve the speed of query access to the LAST_NAME
column in the EMPLOYEES table:
CREATE INDEX emp_last_name_idx
ON
employees(last_name);
CREATE INDEX succeeded.

In the syntax:
index
table
column

Is the name of the index
Is the name of the table
Is the name of the column in the table to be indexed

For more information, see “CREATE INDEX” in Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 36

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating H Index
an
IM index on one or more columns by issuing the CREATE INDEX statement.
S
Create an
RA

NA

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Index Creation Guidelines
Create an index when:
A column contains a wide range of values
A column contains a large number of null values
One or more columns are frequently used together in a WHERE clause or
a join condition
The table is large and most queries are expected to retrieve less than 2%
to 4% of the rows in the table

Do not create an index when:
The columns are not often used as a condition in the query

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
The table is updated frequently
comGuide
ฺ
ailpart ntan expression
The indexed columns are referenced as
of
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN liBetter
More Is Not Always c
IMH indexes on a table does not produce faster queries. Each DML operation that is
AS
RHaving more a table with indexes means that the indexes must be updated. The more indexes
A committed on
The table is small or most queries are expected to retrieve more than 2%
to 4% of the rows in the table

that you have associated with a table, the more effort the Oracle server must make to update all
the indexes after a DML operation.
When to Create an Index
Therefore, you should create indexes only if:
• The column contains a wide range of values
• The column contains a large number of null values
• One or more columns are frequently used together in a WHERE clause or join condition
• The table is large and most queries are expected to retrieve less than 2% to 4% of the rows
Remember that if you want to enforce uniqueness, you should define a unique constraint in the
table definition. A unique index is then created automatically.

Oracle Database 10g: SQL Fundamentals I 10 - 37
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Removing an Index
•

Remove an index from the data dictionary by using the
DROP INDEX command:
DROP INDEX index;

•

Remove the UPPER_LAST_NAME_IDX index from the data
dictionary:
DROP INDEX emp_last_name_idx;
DROP INDEX emp_last_name_idx succeeded.

•

s

n
-tra
n

o

To drop an index, you must be the owner of the index or
an
s
have the DROP ANY INDEX privilege.) ha ฺ

m
e
ฺco Guid
il t
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Removing an Index
IMH modify indexes. To change an index, you must drop it and then re-create it.
AS
RYou cannot

NA

Remove an index definition from the data dictionary by issuing the DROP INDEX statement. To
drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege.
In the syntax, index is the name of the index.
Note: If you drop a table, indexes and constraints are automatically dropped but views and
sequences remain.

Oracle Database 10g: SQL Fundamentals I 10 - 38

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Synonyms

Object

Description

Table

Basic unit of storage; composed of rows

View

Logically represents subsets of data from one or
more tables

Sequence

Generates numeric values

Index

Improves the performance of some queries

Synonym

Gives alternative names to objects

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Synonyms
IMHare database objects that enable you to call a table by another name. You can create
AS
RSynonyms
synonyms to give an alternative name to a table.

Oracle Database 10g: SQL Fundamentals I 10 - 39
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Synonyms
Simplify access to objects by creating a synonym (another
name for an object). With synonyms, you can:
• Create an easier reference to a table that is owned by
another user
• Shorten lengthy object names

e

CREATE [PUBLIC] SYNONYM synonym
FOR
object;

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN licfor an Object
Creating HSynonym
a
IMto a table that is owned by another user, you need to prefix the table name with the
AS
RTo refer

name of the user who created it, followed by a period. Creating a synonym eliminates the need
to qualify the object name with the schema and provides you with an alternative name for a
table, view, sequence, procedure, or other objects. This method can be especially useful with
lengthy object names, such as views.
In the syntax:
PUBLIC
Creates a synonym that is accessible to all users
synonym
Is the name of the synonym to be created
object
Identifies the object for which the synonym is created

Guidelines
• The object cannot be contained in a package.
• A private synonym name must be distinct from all other objects that are owned by the same
user.
For more information, see “CREATE SYNONYM” in the Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 40
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating and Removing Synonyms
•

Create a shortened name for the DEPT_SUM_VU view:
CREATE SYNONYM d_sum
FOR dept_sum_vu;
CREATE SYNONYM succeeded.

•

Drop a synonym:
DROP SYNONYM d_sum;
DROP SYNONYM succeeded.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Creating HSynonym
a
IM example creates a synonym for the DEPT_SUM_VU view for quicker reference.
S
The slide
RA

The database administrator can create a public synonym that is accessible to all users. The
following example creates a public synonym named DEPT for Alice’s DEPARTMENTS table:
CREATE PUBLIC SYNONYM dept
FOR
alice.departments;
CREATE SYNONYM succeeded.

Removing a Synonym
To remove a synonym, use the DROP SYNONYM statement. Only the database administrator can
drop a public synonym.
DROP PUBLIC SYNONYM dept;
DROP SYNONYM succeeded.

For more information, see “DROP SYNONYM” in the Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I 10 - 41
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Summary
In this lesson, you should have learned how to:
• Create, use, and remove views
• Automatically generate sequence numbers by using a
sequence generator
• Create indexes to improve query retrieval speed
• Use synonyms to provide alternative names for objects

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Summary
IMH you should have learned about database objects such as views, sequences, indexes,
AS
RIn this lesson,
and synonyms.

Oracle Database 10g: SQL Fundamentals I 10 - 42
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 10: Overview of Part 2
This practice covers the following topics:
• Creating sequences
• Using sequences
• Creating nonunique indexes
• Creating synonyms

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen Part 2
Practice 10: Overview of
IMH lesson’s practice provides you with a variety of exercises in creating and using a
Part 2 of
AS
Rsequence,this index, and a synonym.
A
an
Complete questions 7–10 at the end of this lesson.

Oracle Database 10g: SQL Fundamentals I 10 - 43
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Practice 10
Part 1
1. The staff in the HR department want to hide some of the data in the EMPLOYEES table.
They want a view called EMPLOYEES_VU based on the employee numbers, employee
names, and department numbers from the EMPLOYEES table. They want the heading
for the employee name to be EMPLOYEE.
2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view.

e

l
rab
fe

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

3. Using your EMPLOYEES_VU view, write a query for the HR department to display all
employee names and department numbers.

…

Oracle Database 10g: SQL Fundamentals I 10 - 44
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Practice 10 (continued)
4. Department 50 needs access to its employee data. Create a view named DEPT50 that
contains the employee numbers, employee last names, and department numbers for all
employees in department 50. You are asked to label the view columns EMPNO,
EMPLOYEE, and DEPTNO. For security purposes, do not allow an employee to be
reassigned to another department through the view.
5. Display the structure and contents of the DEPT50 view.

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
6. Test your view. Attempt to reassigntMatos to department 80.
@g tude
c
S
han this
m
asi use
r
(na se to
C
AN licen
IMH
S
RA

NA

Oracle Database 10g: SQL Fundamentals I 10 - 45
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Practice 10 (continued)
Part 2
7. You need a sequence that can be used with the primary key column of the DEPT table. The
sequence should start at 200 and have a maximum value of 1,000. Have your sequence
increment by 10. Name the sequence DEPT_ID_SEQ.
8. To test your sequence, write a script to insert two rows in the DEPT table. Name your
script lab_10_08.sql. Be sure to use the sequence that you created for the ID column.
Add two departments: Education and Administration. Confirm your additions. Run the
commands in your script.
9. Create a nonunique index on the NAME column in the DEPT table.
10. Create a synonym for your EMPLOYEES table. Call it EMP.

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 10 - 46
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Managing Objects
with Data Dictionary Views

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

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

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Objectives
IMH you are introduced to the data dictionary views. You learn that the dictionary
AS
RIn this lesson,
views can be used to retrieve metadata and create reports about your schema objects.

Oracle Database 10g: SQL Fundamentals I 11 - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Data Dictionary

Oracle server

Tables containing
business data:
EMPLOYEES
DEPARTMENTS
LOCATIONS
JOB_HISTORY
...

Data dictionary
e
views:
abl
r
DICTIONARY
sfe
n
USER_OBJECTSra
-t
USER_TABLES
non
a
USER_TAB_COLUMNS
as
h
... ฺ

N

)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Data Dictionary
MH
Itables are tables created by the user and contain business data, such as EMPLOYEES. There
User
AS
Ris another collection of tables and views in the Oracle Database known as the data dictionary.
A
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 also 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
Oracle Database 10g: SQL Fundamentals I 11 - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Data Dictionary Structure

Oracle server

Consists of:
– Base tables
– User-accessible views

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Structure
lic
Data Dictionary
H
IM
Underlying base tables store information about the associated database. Only the Oracle server
AS
ARshould write to and read 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.

Oracle Database 10g: SQL Fundamentals I 11 - 4
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Data Dictionary Structure
View naming convention:
View Prefix

Purpose

USER

User’s view (what is in your schema; what you
own)

ALL

Expanded user’s view (what you can access)

DBA

Database administrator’s view (what is in
everyone’s schemas)

V$

Performance-related data

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Structure (continued)
Data Dictionary lic
IMH
The data dictionary consists of sets of views. In
a set consists of three
AS
Rcontaining similar information and distinguishedmany cases,other by their prefixes.views
A
from each
For example,
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 on 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.

Oracle Database 10g: SQL Fundamentals I 11 - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

How to Use the Dictionary Views
Start with DICTIONARY. It contains the names and descriptions
of the dictionary tables and views.
DESCRIBE DICTIONARY

e

SELECT *
FROM
dictionary
WHERE table_name = 'USER_OBJECTS';

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Dictionary Views
lic
How to Use the
H
IM
ToS
A familiarize yourself with the dictionary views, you can use the dictionary view named
ARDICTIONARY. It contains the name and short description of each dictionary view to which you
have access.
You can write queries to search for information on 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';

Note: The names in the data dictionary are uppercase.

Oracle Database 10g: SQL Fundamentals I 11 - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

USER_OBJECTS and ALL_OBJECTS Views
•

Use the USER_OBJECTS view to:
– See all of the objects that are owned by you
– Obtain a listing of all object names and types in your
schema, plus the following information:
—
—
—

•

Date created
Date of last modification
Status (valid or invalid)

Use the ALL_OBJECTS view to see all objects to which ns
a
you have access
n-tr
o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN View en
USER_OBJECTS
lic
H
IM
You can query the USER_OBJECTS view to see the names and types of all the objects in your
AS
R

NA

schema. There are several columns in this view:
• OBJECT_NAME: Name of the object
• OBJECT_ID: Dictionary object number of the object
• OBJECT_TYPE: Type of object (such as TABLE, VIEW, INDEX, SEQUENCE)
• CREATED: Timestamp for the creation of the object
• LAST_DDL_TIME: Timestamp for the last modification of the object resulting from a
DDL command
• STATUS: Status of the object (VALID, INVALID, or N/A)
• GENERATED: Was the name of this object system-generated? (Y|N)

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.

Oracle Database 10g: SQL Fundamentals I 11 - 7

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

USER_OBJECTS View

SELECT object_name, object_type, created, status
FROM
user_objects
ORDER BY object_type;

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
…
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN View (continued)
USER_OBJECTS
lic
H
IM
The example shows the names, types, dates of creation, and status of all objects that are owned
AS
R

by this 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. While 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.

Oracle Database 10g: SQL Fundamentals I 11 - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Table Information
USER_TABLES:
DESCRIBE user_tables

…

e

SELECT table_name
FROM
user_tables;

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
…
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
USER_TABLES View
IMH the USER_TABLES view to obtain the names of all of your tables. The
S
You can use
RA

USER_TABLES view contains information about your tables. In addition to providing the table
name, it contains detailed information on the storage.
The TABS view is a synonym of the USER_TABLES view. You can query it to see a listing of
tables that you own:
SELECT table_name
FROM tabs;

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.

Oracle Database 10g: SQL Fundamentals I 11 - 9
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Column Information
USER_TAB_COLUMNS:
DESCRIBE user_tab_columns

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
…
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Column Information
IMH the USER_TAB_COLUMNS view to find detailed information about the columns
You can query
AS
Rin your tables. While the USER_TABLES view provides information on your table names and
A
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.

Oracle Database 10g: SQL Fundamentals I 11 - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Column Information

SELECT column_name, data_type, data_length,
data_precision, data_scale, nullable
FROM
user_tab_columns
WHERE table_name = 'EMPLOYEES';

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Column Information (continued)
IMH the USER_TAB_COLUMNS table, you can find details about your columns such as
ByS
A querying
Rthe names, data types, data type lengths, null constraints, and default value for a column.
A
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.

Oracle Database 10g: SQL Fundamentals I 11 - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Constraint Information
•
•

USER_CONSTRAINTS describes the constraint definitions
on your tables.
USER_CONS_COLUMNS describes columns that are owned
by you and that are specified in constraints.
DESCRIBE user_constraints

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
…
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Constraint Information
IMH out the names of your constraints, the type of constraint, the table name to which
AS
RYou can find

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.

Oracle Database 10g: SQL Fundamentals I 11 - 12
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Constraint Information

SELECT constraint_name, constraint_type,
search_condition, r_constraint_name,
delete_rule, status
FROM
user_constraints
WHERE table_name = 'EMPLOYEES';

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
USER_CONSTRAINTS: Example
IMH shown, the USER_CONSTRAINTS view is queried to find the names, types,
S
In the example
RA

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

Oracle Database 10g: SQL Fundamentals I 11 - 13
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Constraint Information
DESCRIBE user_cons_columns

e

SELECT constraint_name, column_name
FROM
user_cons_columns
WHERE table_name = 'EMPLOYEES';

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
…
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
QueryingH
USER_CONS_COLUMNS
IM names of the columns to which a constraint applies, query the
ToS the
find
RA

NA

l
rab
fe

USER_CONS_COLUMNS dictionary view. This view tells you the name of the owner of a
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 the USER_CONSTRAINTS and USER_CONS_COLUMNS to
create customized output from both tables.

Oracle Database 10g: SQL Fundamentals I 11 - 14
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

View Information
1

DESCRIBE user_views

2

SELECT DISTINCT view_name FROM user_views;

e

l
rab
fe

s

n
-tra
n

o
an
3
)
ฺ
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
N C licen
AData Dictionary
Views in the
MH
Iyour view is created, you can query the data dictionary view called USER_VIEWS to see
After
AS
Rthe name of the view and the view definition. The text of the SELECT statement that constitutes
NA your view is stored in a LONG column. The LENGTH column is the number of characters in the
SELECT text FROM user_views
s
WHERE view_name = 'EMP_DETAILS_VIEW'; ha

SELECT statement. By default, when you select from a LONG column, only the first 80
characters of the column’s value are displayed. To see more than 80 characters in SQL*Plus, use
the command SET LONG:
SET LONG 1000

In the examples in the slide:
1. The USER_VIEWS columns are displayed. Note that this is a partial listing.
2. The names of your views are retrieved.
3. The SELECT statement for the EMP_DETAILS_VIEW is displayed from the dictionary.
Data Access Using Views
When you access data using a view, the Oracle server performs the following operations:
• It retrieves the view definition from the data dictionary table USER_VIEWS.
• It checks access privileges for the view base table.
• It converts the view query into an equivalent operation on the underlying base table or
tables. In other words, data is retrieved from, or an update is made to, the base tables.
Oracle Database 10g: SQL Fundamentals I 11 - 15
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Sequence Information

DESCRIBE user_sequences

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C e
AN Viewn
USER_SEQUENCES lic
IMH
S
The USER_SEQUENCES view describes all sequences that are owned by you. When you create
RA
the 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 sequence is incremented
• CYCLE_FLAG: Does sequence wrap around on reaching 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.

Oracle Database 10g: SQL Fundamentals I 11 - 16
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Sequence Information
•

Verify your sequence values in the USER_SEQUENCES
data dictionary table.
SELECT
FROM

sequence_name, min_value, max_value,
increment_by, last_number
user_sequences;

e

l
rab
fe

s

•

n
-tra
n

o
The LAST_NUMBER column displays the next available
an
sequence number if NOCACHE is specified. s
ha

NA

)
ฺ
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Confirming Sequences
MH
Icreating your sequence, it is documented in the data dictionary. Because a sequence is a
AS
RAfter
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.

Oracle Database 10g: SQL Fundamentals I 11 - 17
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Synonym Information

DESCRIBE user_synonyms

e

SELECT *
FROM
user_synonyms;

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN Viewen
USER_SYNONYMS lic
IMH
S
The USER_SYNONYMS dictionary view describes private synonyms (synonyms that are owned
RA

by you).
You can query this view to find your synonyms. You can query ALL_SYNONYMS to find out the
name of all of 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)

Oracle Database 10g: SQL Fundamentals I 11 - 18
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Adding Comments to a Table
•

You can add comments to a table or column by using the
COMMENT statement:
COMMENT ON TABLE employees
IS 'Employee Information';
COMMENT ON succeeded.

•

Comments can be viewed through the data dictionary
views:
–
–
–
–

ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN litoen
Adding Comments c a Table
IMH a comment of up to 4,000 bytes about a column, table, view, or snapshot by using
AScan add
RYouCOMMENT statement. The comment is stored in the data dictionary and can be viewed in one
A the
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 ' ';
Oracle Database 10g: SQL Fundamentals I 11 - 19
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Summary
In this lesson, you should have learned how to find information
about your objects by using the following dictionary views:
• DICTIONARY
• USER_OBJECTS
• USER_TABLES
• USER_TAB_COLUMNS
e
abl
r
• USER_CONSTRAINTS
sfe
n
-tra
• USER_CONS_COLUMNS
non
a
• USER_VIEWS
as
h
• USER_SEQUENCES
m) ideฺ
o
ilฺc t Gu
• USER_TAB_SYNONYMS
ma

NA

n
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Summary
IMH you learned about some of the dictionary views that are available to you. You can
AS
RIn this lesson,
use these dictionary views to find information about your tables, constraints, views, sequences,
and synonyms.

Oracle Database 10g: SQL Fundamentals I 11 - 20
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 11: 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
e
abl
r
• Querying the dictionary views for synonym information sfe
n
-tra
• Adding a comment to a table and querying the dictionary
non
views for comment information
sa

) ha eฺ
m
ฺco Guid
il
ma ent
g
t@ Stud
c
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C
AN licen
Practice 11: Overview
IMH you query the dictionary views to find information about the objects in your
AS
RIn this practice,
A schema.

N

Oracle Database 10g: SQL Fundamentals I 11 - 21
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 11
1. For a specified table, create a script that reports the column names, data types, and
lengths of the data types, as well as whether nulls are allowed. Prompt the user to enter
the table name. Give appropriate aliases to the DATA_PRECISION and
DATA_SCALE columns. Save this script in a file named lab_11_01.sql.
For example, if the user enters DEPARTMENTS, the following output results:

e

l
rab
e
2. Create a script that reports the column name, constraint name, constraint type, search
nsf
condition, and status for a specified table. You must join the USER_CONSTRAINTS
tra
n-the user to
and USER_CONS_COLUMNS tables to obtain all this information. Prompt
o
an
enter the table name. Save the script in a file named lab_11_02.sql.
has ฺ
)
For example, if the user enters DEPARTMENTS, the following e
comGuidoutput results:
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n e
C ( toethesDEPARTMENTS table. Then query the
3. Add a comment
AN lic n
USER_TAB_COMMENTS view to verify that the comment is present.
IMH
S
RA

NA

4. Find the names of all synonyms that are in your schema.

Oracle Database 10g: SQL Fundamentals I 11 - 22
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Practice 11 (continued)
5. You need to determine the names and definitions of all the views in your schema.
Create a report that retrieves the view information: the view name and text from the
USER_VIEWS data dictionary view.
Note: Another view already exists. The EMP_DETAILS_VIEW was created as part of
your schema. Also, if you completed practice 10, you see the DEPT50 view.
Note: 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.

e
6. Find the names of your sequences. Write a query in a script to display the following
abl
information about your sequences: sequence name, maximum value, increment size, r
sfe
nscript.
and last number. Name the script lab_11_06.sql. Run the statement intyour
ra
-

non
a

has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I 11 - 23
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

________________
A
Practice Solutions
________________
e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
SQL Star International Limited

Practice 1: Solutions
Part 1

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Test your knowledge:
1. The following SELECT statement executes successfully:
SELECT last_name, job_id, salary AS Sal
FROM
employees;

True/False
2. The following SELECT statement executes successfully:
SELECT *
FROM
job_grades;

e

l
rab
fe

s

n
-tra
n

o
an
s
3. There are four coding errors in this statement. Can you identifyha
them?
)
ฺ
SELECT
employee_id, last_name
comGuide
sal x 12 ANNUAL SALARY
ailฺ nt
m e
FROM
employees;
@ag tudcalled sal. The column is called
t
• The EMPLOYEES table does not contain column
anc this S
h
SALARY.
imis *,se x, as shown in line 2.
s
• The multiplication operator u not
araaliaso
n
t cannot include spaces. The alias should read
• The ANNUAL SALARY
C ( eor se be enclosed in double quotation marks.
ANNUAL_SALARY n should
N lic
HA
• A comma is missing after the LAST_NAME column.
IM
AS
True/False

R

NA

Part 2
Note the following location for the lab files:
homeoraclelabsSQL1labs
If you are asked to save any lab files, save them at this location.
To start Oracle SQL Developer, double-click the SQL Developer desktop icon.
Before you begin with the practices, you need a database connection to be able to connect to the
database and issue SQL queries.

Oracle Database 10g: SQL Fundamentals I A - 2
SQL Star International Limited
Practice 1: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

4. To create a new database connection in the Connections Navigator, right-click Connections.
Select New Connection from the menu. The New/Select Database Connection dialog box
appears.

5. Create a database connection using the following information:
a. Connection Name: myconnection
b. Username: ora1
c. Password: ora1
d. Hostname: localhost
e. Port: 1521
f. SID: ORCL
g. Ensure that you select the Save Password check box.

s

NA

Oracle Database 10g: SQL Fundamentals I A - 3

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

e

l
rab
fe
SQL Star International Limited

Practice 1: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

You have been hired as a SQL programmer for Acme Corporation. Your first task is to create
some reports based on data from the Human Resources tables.
6. Your first task is to determine the structure of the DEPARTMENTS table and its contents.
DESCRIBE departments
SELECT *
FROM
departments;

7. You need to determine the structure of the EMPLOYEES table.

e

l
rab
fe

DESCRIBE employees

s

The HR department wants a query to display the last name, job code, hire date, and employee
number for each employee, with the employee number appearing first. Provide an alias
STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named
lab_01_07.sql so that you can dispatch this file to the HR department.

n
-tra
n

o
an
has ฺ
)
SELECT employee_id, last_name, job_id, hire_date StartDate
comGuide
FROM
employees;
ailฺ nt
m
8. Test your query in the lab_01_07.sql file to ensure that it runs correctly.
@g tude
t
S
anc job_id, hire_date StartDate
SELECT employee_id, last_name, his
h
t
m
FROM
employees;
asi use
r
o
(naneeds atquery to display all unique job codes from the EMPLOYEES
9. The HR department se
C en
table. AN
lic
H
IM
SELECT DISTINCT job_id
AS
FROM
employees;

R

NA

Part 3
If you have time, complete the following exercises:
10. The HR department wants more descriptive column headings for its report on employees.
Copy the statement from lab_01_07.sql to the SQL Developer text box. Name the
column headings Emp #, Employee, Job, and Hire Date, respectively. Then run your
query again.
SELECT employee_id "Emp #", last_name "Employee",
job_id "Job", hire_date "Hire Date"
FROM
employees;

Oracle Database 10g: SQL Fundamentals I A - 4
SQL Star International Limited
Practice 1: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

11. The HR department has requested a report of all employees and their job IDs. Display the
last name concatenated with the job ID (separated by a comma and space) and name the
column Employee and Title.
SELECT last_name||', '||job_id "Employee and Title"
FROM
employees;

If you want an extra challenge, complete the following exercise:
12. To familiarize yourself with the data in the EMPLOYEES table, create a query to display all
the data from the EMPLOYEES table. Separate each column output with a comma. Name the
column THE_OUTPUT.

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I A - 5

s

n
-tra
n

SELECT employee_id || ',' || first_name || ',' || last_name
|| ',' || email || ',' || phone_number || ','|| job_id
|| ',' || manager_id || ',' || hire_date || ','
|| salary || ',' || commission_pct || ',' || department_id
THE_OUTPUT
FROM
employees;

e

l
rab
fe
SQL Star International Limited

Practice 2: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

The HR department needs your assistance with creating some queries.
1. Because of budget issues, the HR department needs a report that displays the last name and
salary of employees earning more than $12,000. Place your SQL statement in a text file
named lab_02_01.sql. Run your query.
SELECT
FROM
WHERE

last_name, salary
employees
salary > 12000;

2. Create a report that displays the last name and department number for employee number 176.
SELECT
FROM
WHERE

last_name, department_id
employees
employee_id = 176;

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
SELECT last_name, salary
@g tude
FROM
employees
ct
S
WHERE
salary NOT BETWEEN an
5000 AND 12000;
h
his
im se t
asthe last name, job ID, and start date for the employees whose last
4. Create a report to display
u
ar
( and se to
names are Matosn Taylor. Order the query in ascending order by start date.
C en
SELECT AN
last_name, job_id, hire_date
lic
FROM H employees
SIM

3. The HR departments needs to find high-salary and low-salary employees. Modify
lab_02_01.sql to display the last name and salary for all employees whose salary is not
in the $5,000–$12,000 range. Place your SQL statement in a text file named
lab_02_03.sql.

N

RAWHERE
A ORDER

last_name IN ('Matos', 'Taylor')
BY hire_date;

5. Display the last name and department number of all employees in departments 20 or 50 in
ascending alphabetical order by name.
SELECT
FROM
WHERE
ORDER BY

last_name, department_id
employees
department_id IN (20, 50)
last_name ASC;

Oracle Database 10g: SQL Fundamentals I A - 6

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 2: Solutions (continued)
6. Modify lab_02_03.sql to list the last name and salary of employees who earn between
$5,000 and $12,000, and are in department 20 or 50. Label the columns Employee and
Monthly Salary, respectively. Resave lab_02_03.sql as lab_02_06.sql. Run
the statement in lab_02_06.sql.
SELECT
FROM
WHERE
AND

last_name "Employee", salary "Monthly Salary"
employees
salary BETWEEN 5000 AND 12000
department_id IN (20, 50);

7. The HR department needs a report that displays the last name and hire date for all employees
who were hired in 1994.
SELECT
FROM
WHERE

last_name, hire_date
employees
hire_date LIKE '%94';

s

n
-tra
n

o
an
has ฺ
)
SELECT
last_name, job_id
FROM
employees
comGuide
ailฺ nt
WHERE
manager_id IS NULL;
m e
@g forudemployees who earn commissions. Sort
9. Display the last name, salary, and commissionSt all
nct is
aand commissions.
data in descending order of salary
imh se th
s u
SELECT
last_name,a
ar salary, commission_pct
(n se to
FROM
employees
C en
WHERE
commission_pct IS NOT NULL
AN licDESC, commission_pct DESC;
ORDERH salary
BY
IM
AS
8. Create a report to display the last name and job title of all employees who do not have a
manager.

R

NA

10. Members of the HR department want to have more flexibility with the queries that you are
writing. They would like a report that displays the last name and salary of employees who
earn more than an amount that the user specifies after a prompt. (You can use the query
created in practice exercise 1 and modify it.) Save this query to a file named
lab_02_10.sql.
SELECT
FROM
WHERE

last_name, salary
employees
salary > &sal_amt;

Oracle Database 10g: SQL Fundamentals I A - 7

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 2: Solutions (continued)
11. The HR department wants to run reports based on a manager. Create a query that prompts the
user for a manager ID and generates the employee ID, last name, salary, and department for
that manager’s employees. The HR department wants the ability to sort the report on a
selected column. You can test the data with the following values:
manager ID = 103, sorted by employee last name
manager ID = 201, sorted by salary
manager ID = 124, sorted by employee ID
SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE manager_id = &mgr_num
ORDER BY &order_col;

s

n
-tra
n

o
an
has is a.
)
12. Display all employee last names in which the third letter of the name ฺ
comGuide
SELECT
last_name
ailฺ nt
FROM
employees
gm de
WHERE
last_name LIKE '__a%';t@
tu
anc this S
13. Display the last names of all employees who have both an a and an e in their last names.
imh se
s
ara to u
SELECT
last_name
n
FROM
employees se
C ( en
WHERE AN
last_name LIKE '%a%'
lic
AND H last_name LIKE '%e%';
IM
AS
If you have time, complete the following exercises:

R

NA

e

l
rab
fe

If you want an extra challenge, complete the following exercises:

14. Display the last name, job, and salary for all employees whose job is either that of a sales
representative or a stock clerk, and whose salary is not equal to $2,500, $3,500, or $7,000.
SELECT
FROM
WHERE
AND

last_name, job_id, salary
employees
job_id IN ('SA_REP', 'ST_CLERK')
salary NOT IN (2500, 3500, 7000);

15. Modify lab_02_06.sql to display the last name, salary, and commission for all
employees whose commission amount is 20%. Resave lab_02_06.sql as
lab_02_15.sql. Rerun the statement in lab_02_15.sql.
SELECT
FROM
WHERE

last_name "Employee", salary "Monthly Salary",
commission_pct
employees
commission_pct = .20;

Oracle Database 10g: SQL Fundamentals I A - 8
SQL Star International Limited

Practice 3: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

1. Write a query to display the current date. Label the column Date.
SELECT
FROM

sysdate "Date"
dual;

2. The HR department needs a report to display the employee number, last name, salary, and
salary increased by 15.5% (expressed as a whole number) for each employee. Label the
column New Salary. Place your SQL statement in a text file named lab_03_02.sql.
SELECT
FROM

employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary"
employees;

3. Run your query in the lab_03_02.sql file.
SELECT

s

n
-tra
n

o
an
FROM
has ฺ
)
e
4. Modify your lab_03_02.sql query to add a columnom subtracts the old salary from the
c thatGuidfile as
new salary. Label the column Increase. Save ailฺ
the contents of the
lab_03_04.sql. Run the revised query. gm
ent
d
@
nct is Stu
SELECT employee_id, last_name, salary,
a t "New Salary",
ROUND(salary *imh
1.155, 0)h
s 0)
ROUND(salary s 1.155,e - salary "Increase"
a*
FROM
employees;
nar e to u
C ( ens
N ic
5. WriteAquery that displays the last name (with the first letter uppercase and all other letters
H a andlthe length of the last name for all employees whose name starts with the
IM
lowercase)
AS letters J, A, or M. Give each column an appropriate label. Sort the results by the employees’

R

NA

employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary"
employees;

e

l
rab
fe

last names.
SELECT

INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM
employees
WHERE
last_name LIKE 'J%'
OR
last_name LIKE 'M%'
OR
last_name LIKE 'A%'
ORDER BY last_name ;

Oracle Database 10g: SQL Fundamentals I A - 9
SQL Star International Limited

Practice 3: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Rewrite the query so that the user is prompted to enter a letter that starts the last name. For
example, if the user enters H when prompted for a letter, the output should show all
employees whose last name starts with the letter H.
SELECT

INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM
employees
WHERE
last_name LIKE '&start_letter%'
ORDER BY last_name;

6. The HR department wants to find the duration of employment for each employee. For each
employee, display the last name and calculate the number of months between today and the
date on which the employee was hired. Label the column MONTHS_WORKED. Order your
results by the number of months employed. Round the number of months up to the closest
whole number.

s

n
-tra
n

o
an
has ฺ
SELECT last_name, ROUND(MONTHS_BETWEEN(
)
e
SYSDATE, hire_date)) MONTHS_WORKED com
ilฺ t Guid
FROM
employees
a
ORDER BY months_worked;
gm den
@
nct is Stu employee:
7. Create a report that produces thea
following for each
h
imh s <salary> monthly but wants <3 times
<employee last name> earnse
s u t
a
salary>.
nar e to
C ( ens
LabelAN
li
H the columncDream Salaries.
IM last_name || ' earns '
SELECT
AS
Note: Your results will differ.

R

NA

FROM

|| TO_CHAR(salary, 'fm$99,999.00')
|| ' monthly but wants '
|| TO_CHAR(salary * 3, 'fm$99,999.00')
|| '.' "Dream Salaries"
employees;

If you have time, complete the following exercises:
8. Create a query to display the last name and salary for all employees. Format the salary to be
15 characters long, left-padded with the “$” symbol. Label the column SALARY.
SELECT last_name,
LPAD(salary, 15, '$') SALARY
FROM
employees;

Oracle Database 10g: SQL Fundamentals I A - 10

e

l
rab
fe
SQL Star International Limited

Practice 3: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

9. Display each employee’s last name, hire date, and salary review date, which is the first
Monday after six months of service. Label the column REVIEW. Format the dates to appear
in the format similar to “Monday, the Thirty-First of July, 2000.”
SELECT last_name, hire_date,
TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date, 6),'MONDAY'),
'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW
FROM
employees;

10. Display the last name, hire date, and day of the week on which the employee started. Label
the column DAY. Order the results by the day of the week, starting with Monday.
SELECT last_name, hire_date,
TO_CHAR(hire_date, 'DAY') DAY
FROM
employees
ORDER BY TO_CHAR(hire_date - 1, 'd');

o
an
If you want an extra challenge, complete the following exercises: as
h
m) ideฺ amounts. If an
11. Create a query that displays the employees’ last names and commission
o
ilฺc t Gu the column COMM.
employee does not earn commission, show “No Commission.” Label
a
gm den
SELECT last_name,
@
nct is Stu
NVL(TO_CHAR(commission_pct), 'No Commission') COMM
a
FROM
employees;
mh se th
i
ras to u
12. Create a query that displays the first eight characters of the employees’ last names and
(na se
indicates the amounts of their salaries with asterisks. Each asterisk signifies a thousand
N C ce in
ASort thelidatan descending order of salary. Label the column
dollars.
IMH
AS EMPLOYEES_AND_THEIR_SALARIES.

R

NA

s

n
-tra
n

SELECT rpad(last_name, 8)||' '||
rpad(' ', salary/1000+1, '*')
EMPLOYEES_AND_THEIR_SALARIES
FROM employees
ORDER BY salary DESC;

Oracle Database 10g: SQL Fundamentals I A - 11

e

l
rab
fe
SQL Star International Limited

Practice 3: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

13. Using the DECODE function, write a query that displays the grade of all employees based on
the value of the column JOB_ID, using the following data:
Job

Grade

AD_PRES

A

ST_MAN

B

IT_PROG

C

SA_REP

D

ST_CLERK

E

None of the above

0

SELECT job_id, decode (job_id,
'ST_CLERK',
'SA_REP',
'IT_PROG',
'ST_MAN',
'AD_PRES',
'0')GRADE
FROM employees;

'E',
'D',
'C',
'B',
'A',

s

FROM employees;

Oracle Database 10g: SQL Fundamentals I A - 12

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
d
@g using e CASE syntax.
14. Rewrite the statement in the precedingtexercise tu the
nc is S
a
SELECT job_id, CASE job_id
mh se th
si u
WHENa
r 'ST_CLERK' THEN 'E'
na 'SA_REP' THEN 'D'
(WHEN se to
C WHEN 'IT_PROG' THEN 'C'
AN licen 'ST_MAN' THEN 'B'
WHEN
H
WHEN 'AD_PRES' THEN 'A'
IM
ELSE '0' END GRADE
AS

R

NA

e

l
rab
fe
SQL Star International Limited

Practice 4: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Determine the validity of the following three statements. Circle either True or False.
1. Group functions work across many rows to produce one result per group.
True/False
2. Group functions include nulls in calculations.
True/False
3. The WHERE clause restricts rows before inclusion in a group calculation.
True/False

e

l
rab
fe

The HR department needs the following reports:

s

n
-tra
n

4. Find the highest, lowest, sum, and average salary of all employees. Label the columns
Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest
whole number. Place your SQL statement in a text file named lab_04_04.sql.

NA

R

o
an
SELECT ROUND(MAX(salary),0) "Maximum",
has ฺ
)
ROUND(MIN(salary),0) "Minimum",
comGuide
ROUND(SUM(salary),0) "Sum",
ilฺ t
ROUND(AVG(salary),0) "Average" a
m
n
FROM
employees;
@g tude
t
anc this S the minimum, maximum, sum, and
5. Modify the query in lab_04_04.sql to display
imh Resave lab_04_04.sql as lab_04_05.sql. Run the
s
average salary for each job type.use
ara to
n
statement in lab_04_05.sql.
C ( ense
SELECT AN
ROUND(MAX(salary),0) "Maximum",
H job_id,lic
ROUND(MIN(salary),0) "Minimum",
SIM
ROUND(SUM(salary),0) "Sum",
A
ROUND(AVG(salary),0) "Average"
FROM
employees
GROUP BY job_id;

6. Write a query to display the number of people with the same job.
SELECT job_id, COUNT(*)
FROM
employees
GROUP BY job_id;

Generalize the query so that the user in the HR department is prompted for a job title. Save
the script to a file named lab_04_06.sql.
SELECT job_id, COUNT(*)
FROM
employees
WHERE job_id = '&job_title'
GROUP BY job_id;

Oracle Database 10g: SQL Fundamentals I A - 13
SQL Star International Limited

Practice 4: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

7. Determine the number of managers without listing them. Label the column Number of
Managers. Hint: Use the MANAGER_ID column to determine the number of managers.
SELECT COUNT(DISTINCT manager_id) "Number of Managers"
FROM
employees;

8. Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
SELECT
FROM

MAX(salary) - MIN(salary) DIFFERENCE
employees;

e

l
rab
fe

If you have time, complete the following exercises:

s

n
-tra
n

9. Create a report to display the manager number and the salary of the lowest-paid employee for
that manager. Exclude anyone whose manager is not known. Exclude any groups where the
minimum salary is $6,000 or less. Sort the output in descending order of salary.

o
an
has ฺ
SELECT
manager_id, MIN(salary)
)
FROM
employees
comGuide
WHERE
manager_id IS NOT NULL
ailฺ nt
m
GROUP BY manager_id
HAVING
MIN(salary) > 6000
@g tude
t
S
ORDER BY MIN(salary) DESC; anc
h
his
t
m
asi use
If you want an extra challenge, complete the following exercises:
r
(na se to
10. Create aN C that displays the total number of employees and, of that total, the number of
query
n
A
employees hiredic 1995, 1996, 1997, and 1998. Create appropriate column headings.
l ine
IMH COUNT(*) total,
SELECT
AS

R

NA

FROM

SUM(DECODE(TO_CHAR(hire_date,
SUM(DECODE(TO_CHAR(hire_date,
SUM(DECODE(TO_CHAR(hire_date,
SUM(DECODE(TO_CHAR(hire_date,
employees;

'YYYY'),1995,1,0))"1995",
'YYYY'),1996,1,0))"1996",
'YYYY'),1997,1,0))"1997",
'YYYY'),1998,1,0))"1998"

Oracle Database 10g: SQL Fundamentals I A - 14
SQL Star International Limited

Practice 4: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

11. Create a matrix query to display the job, the salary for that job based on the department
number, and the total salary for that job, for departments 20, 50, 80, and 90, giving each
column an appropriate heading.
SELECT

job_id "Job",
SUM(DECODE(department_id
SUM(DECODE(department_id
SUM(DECODE(department_id
SUM(DECODE(department_id
SUM(salary) "Total"
FROM
employees
GROUP BY job_id;

,
,
,
,

20,
50,
80,
90,

salary))
salary))
salary))
salary))

"Dept
"Dept
"Dept
"Dept

20",
50",
80",
90",

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I A - 15
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 5: Solutions
1. Write a query for the HR department to produce the addresses of all the departments. Use
the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or
province, and country in the output. Use a NATURAL JOIN to produce the results.
SELECT location_id, street_address, city, state_province, country_name
FROM
locations
NATURAL JOIN countries;

2. The HR department needs a report of all employees. Write a query to display the last name,
department number, and department name for all employees.
SELECT last_name, department_id, department_name
FROM
employees
JOIN
departments
USING (department_id);

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
SELECT e.last_name, e.job_id, e.department_id, d.department_name
comGuide
FROM
employees e JOIN departments d
ailฺ
ON
(e.department_id = d.department_id) nt
m
JOIN
locations l
@g tude
t
ON
(d.location_id = l.location_id)
anc this S
WHERE LOWER(l.city) = 'toronto';
imh se
s
ara theo uname and employee number of employees along with their
4. Create a report ton
display t last
C ( e ande
manager’s last name ns manager number. Label the columns Employee, Emp#,
N Mgr#, respectively. Place your SQL statement in a text file named
Manager, andlic
HA
IM
AS lab_05_04.sql.
3. The HR department needs a report of employees in Toronto. Display the last name, job,
department number, and department name for all employees who work in Toronto.

R

NA

SELECT w.last_name "Employee", w.employee_id "EMP#",
m.last_name "Manager", m.employee_id "Mgr#"
FROM
employees w join employees m
ON
(w.manager_id = m.employee_id);

5. Modify lab_05_04.sql to display all employees, including King, who has no manager.
Order the results by the employee number. Place your SQL statement in a text file named
lab_05_05.sql. Run the query in lab_05_05.sql.
SELECT w.last_name "Employee", w.employee_id "EMP#",
m.last_name "Manager", m.employee_id "Mgr#"
FROM
employees w
LEFT
OUTER JOIN employees m
ON
(w.manager_id = m.employee_id);

Oracle Database 10g: SQL Fundamentals I A - 16
SQL Star International Limited

Practice 5: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

6. Create a report for the HR department that displays employee last names, department
numbers, and all the employees who work in the same department as a given employee. Give
each column an appropriate label. Save the script to a file named lab_05_06.sql.
SELECT e.department_id department, e.last_name employee,
c.last_name colleague
FROM
employees e JOIN employees c
ON
(e.department_id = c.department_id)
WHERE e.employee_id <> c.employee_id
ORDER BY e.department_id, e.last_name, c.last_name;

7. The HR department needs a report on job grades and salaries. To familiarize yourself with
the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then create a
query that displays the name, job, department name, salary, and grade for all employees.

s

n
-tra
n

DESC JOB_GRADES

o
an
SELECT e.last_name, e.job_id, d.department_name,
has ฺ
e.salary, j.grade_level
)
FROM
employees e JOIN departments d
comGuide
ON
(e.department_id = d.department_id)
ailฺ nt
JOIN
job_grades j
m e
ON
(e.salary BETWEEN j.lowest_sal AND d
@g tu j.highest_sal);
t
anc this S
h
If you want an extra challenge,m
i complete the following exercises:
ras to use
8. The HR department wants to determine the names of all employees who were hired after
(na se
Davies. N C a query to display the name and hire date of any employee hired after
ACreate licen
employee Davies.
IMH e.last_name, e.hire_date
SELECT
AS

R

NA

FROM
ON
WHERE

employees e JOIN employees davies
(davies.last_name = 'Davies')
davies.hire_date < e.hire_date;

9. The HR department needs to find the names and hire dates for all employees who were hired
before their managers, along with their managers’ names and hire dates. Save the script to a
file named lab_05_09.sql.
SELECT w.last_name, w.hire_date, m.last_name, m.hire_date
FROM
employees w JOIN employees m
ON
(w.manager_id = m.employee_id)
WHERE
w.hire_date < m.hire_date;

Oracle Database 10g: SQL Fundamentals I A - 17

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 6: Solutions
1. The HR department needs a query that prompts the user for an employee last name. The
query then displays the last name and hire date of any employee in the same department as
the employee whose name the user supplies (excluding that employee). For example, if the
user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey).
UNDEFINE Enter_name
SELECT last_name, hire_date
FROM
employees
WHERE department_id = (SELECT department_id
FROM
employees
WHERE last_name = '&&Enter_name')
AND
last_name <> '&Enter_name';

e

l
rab
fe

s

n
-tra
n

2. Create a report that displays the employee number, last name, and salary of all employees
who earn more than the average salary. Sort the results in ascending order by salary.

NA

R

o
an
SELECT employee_id, last_name, salary
has ฺ
FROM
employees
)
WHERE salary > (SELECT AVG(salary)
comGuide
FROM
employees)
ailฺ nt
ORDER BY salary;
m
@g tude
t
3. Write a query that displays the employee number and last name of all employees who work
anc this S
in a department with any employee whose last name contains a u. Place your SQL statement
imh se
s u
in a text file namedara
lab_06_03.sql. Run your query.
(n se to
C
SELECT employee_id, last_name
FROM
employees
AN licen
WHEREH department_id IN (SELECT department_id
IM
FROM
employees
AS
WHERE

last_name like '%u%');

4. The HR department needs a report that displays the last name, department number, and job
ID of all employees whose department location ID is 1700.
SELECT last_name, department_id, job_id
FROM
employees
WHERE department_id IN (SELECT department_id
FROM
departments
WHERE location_id = 1700);

Modify the query so that the user is prompted for a location ID. Save this to a file named
lab_06_04.sql.
SELECT last_name, department_id, job_id
FROM
employees
WHERE department_id IN (SELECT department_id
FROM
departments
WHERE location_id = &Enter_location);
Oracle Database 10g: SQL Fundamentals I A - 18
SQL Star International Limited

Practice 6: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

5. Create a report for the HR department that displays the last name and salary of every
employee who reports to King.
SELECT last_name, salary
FROM
employees
WHERE manager_id = (SELECT employee_id
FROM
employees
WHERE last_name = 'King');

6. Create a report for the HR department that displays the department number, last name, and
job ID for every employee in the Executive department.
SELECT department_id, last_name, job_id
FROM
employees
WHERE department_id IN (SELECT department_id
FROM
departments
WHERE department_name = 'Executive');

e

s

n
-tra
n

o
an
If you have time, complete the following exercise:
has ฺ
)
om uide
cemployee number, last name, and
7. Modify the query in lab_06_03.sql to display ithe
a lฺ nt Gand who work in a department
salary of all employees who earn more thangm
the average salary
@ a u.tResave lab_06_03.sql to
ude
with any employee whose last name ct
contains
S
lab_06_07.sql. Run the statement in lab_06_07.sql.
han this
im se
SELECT employee_id,as
last_name, salary
r
u
FROM
employees a
(n se to
C
WHERE department_id IN (SELECT department_id
FROM
employees
AN licen
H
WHERE last_name like '%u%')
IM salary > (SELECT AVG(salary)
AND
AS

R

NA

l
rab
fe

FROM

employees);

Oracle Database 10g: SQL Fundamentals I A - 19
SQL Star International Limited

Practice 7: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

1. The HR department needs a list of department IDs for departments that do not contain the job
ID ST_CLERK. Use set operators to create this report.
SELECT
FROM
MINUS
SELECT
FROM
WHERE

department_id
departments
department_id
employees
job_id = 'ST_CLERK';

2. The HR department needs a list of countries that have no departments located in them.
Display the country ID and the name of the countries. Use set operators to create this report.
SELECT country_id, country_name
FROM
countries
MINUS
SELECT country_id, country_name
FROM
countries
NATURAL JOIN locations
NATURAL JOIN departments;

o
an
has ฺ
)
comGuide
ailฺin nt order. Display the job ID and
3. Produce a list of jobs for departments 10, 50, m 20, that
and
department ID using set operators.
@g tude
t
anc this S
COLUMN dummy NOPRINT
imh se
SELECT job_id, department_id, 'x' dummy
s
FROM
employees r
a a to u
n
WHERE department_id se10
C ( en =
UNION
N lic
HA
SELECT job_id, department_id, 'y' dummy
IM employees
FROM
AS

R

NA

s

n
-tra
n

WHERE department_id = 50
UNION
SELECT job_id, department_id, 'z' dummy
FROM
employees
WHERE department_id = 20
ORDER BY dummy;
COLUMN dummy PRINT

4. Create a report that lists the employee ID and job ID of those employees who currently have
a job title that is the same as their job title when they were initially hired by the company
(that is, they changed jobs but have now gone back to doing their original job).
SELECT
employee_id,job_id
FROM
employees
INTERSECT
SELECT
employee_id,job_id
FROM
job_history;

Oracle Database 10g: SQL Fundamentals I A - 20

e

l
rab
fe
SQL Star International Limited

Practice 7: Solutions (continued)
5. The HR department needs a report with the following specifications:

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

•

Last name and department ID of all the employees from the EMPLOYEES table,
regardless of whether or not they belong to a department

•

Department ID and department name of all the departments from the DEPARTMENTS
table, regardless of whether or not they have employees working in them

Write a compound query to accomplish this.
SELECT last_name,department_id,TO_CHAR(null)
FROM
employees
UNION
SELECT TO_CHAR(null),department_id,department_name
FROM departments;

e

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I A - 21

l
rab
fe
SQL Star International Limited

Practice 8: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

The HR department wants you to create SQL statements to insert, update, and delete employee
data. As a prototype, you use the MY_EMPLOYEE table, before giving the statements to the HR
department.
Insert data into the MY_EMPLOYEE table.
1. Run the statement in the lab_08_01.sql script to build the MY_EMPLOYEE table to be
used for the lab.
CREATE TABLE my_employee
(id NUMBER(4) CONSTRAINT my_employee_id_nn NOT NULL,
last_name VARCHAR2(25),
first_name VARCHAR2(25),
userid VARCHAR2(8),
salary NUMBER(9,2));

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
DESCRIBE my_employee
)
comGuide
lฺ
3. Create an INSERT statement to add the first rowai data to the MY_EMPLOYEE table from
of
gm dent
the following sample data. Do not list the columns in the INSERT clause.
@
nct is Stu
a th
ID
LAST_NAME
SALARY
mh seFIRST_NAME USERID
asi u
ar
(nPatel to
e
1
Ralph
rpatel
895
N C licens
HA
2
Dancs
Betty
bdancs
860
IM
AS
2. Describe the structure of the MY_EMPLOYEE table to identify the column names.

R

NA

3

Biri

Ben

bbiri

4

Newman

Chad

cnewman

5

Ropeburn

Audrey

aropebur

INSERT INTO my_employee
VALUES (1, 'Patel', 'Ralph', 'rpatel', 895);

Oracle Database 10g: SQL Fundamentals I A - 22

1100
750
1550
SQL Star International Limited

Practice 8: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

4. Populate the MY_EMPLOYEE table with the second row of sample data from the preceding
list. This time, list the columns explicitly in the INSERT clause.
INSERT INTO my_employee (id, last_name, first_name,
userid, salary)
VALUES (2, 'Dancs', 'Betty', 'bdancs', 860);

5. Confirm your addition to the table.
SELECT
FROM

*
my_employee;

s

n
-tra
n

NA

R

o
an
SET ECHO OFF
has ฺ
SET VERIFY OFF
)
INSERT INTO my_employee
comGuide
VALUES (&p_id, '&&p_last_name', '&&p_first_name',
ailฺ nt
lower(substr('&p_first_name', 1, 1) ||
gm &p_salary);
e
substr('&p_last_name', t@
1, 7)), tud
c
S
SET VERIFY ON
han this
SET ECHO ON
m
UNDEFINE p_first_name
asi use
r
UNDEFINE p_last_name
(na se to
C en
AN table with the next two rows of sample data listed in step 3 by running the
7. Populate the lic
IMH statement in the script that you created.
INSERT
AS
SET ECHO OFF
SET VERIFY OFF
INSERT INTO my_employee
VALUES (&p_id, '&&p_last_name', '&&p_first_name',
lower(substr('&p_first_name', 1, 1) ||
substr('&p_last_name', 1, 7)), &p_salary);
SET VERIFY ON
SET ECHO ON
UNDEFINE p_first_name
UNDEFINE p_last_name

8. Confirm your additions to the table.
SELECT
*
FROM my_employee;

9. Make the data additions permanent.
COMMIT;

Oracle Database 10g: SQL Fundamentals I A - 23

e

l
rab
fe

6. Write an INSERT statement in a dynamic reusable script file named loademp.sql to load
rows into the MY_EMPLOYEE table. Concatenate the first letter of the first name and the first
seven characters of the last name to produce the user ID. Save this script to a file named
lab_08_06.sql.
SQL Star International Limited

Practice 8: Solutions (continued)
Update and delete data in the MY_EMPLOYEE table.

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

10. Change the last name of employee 3 to Drexler.
UPDATE
SET
WHERE

my_employee
last_name = 'Drexler'
id = 3;

11. Change the salary to $1,000 for all employees with a salary less than $900.
UPDATE
SET
WHERE

my_employee
salary = 1000
salary < 900;

e

s

n
-tra
n

12. Verify your changes to the table.

R

NA

o

an
has ฺ
)
13. Delete Betty Dancs from the MY_EMPLOYEE table.
comGuide
DELETE
ailฺ nt
m
FROM my_employee
@g tude
t
WHERE last_name = 'Dancs';
anc this S
h
14. Confirm your changes tosim
the table. e
s
a
nar e to u
SELECT *
C ( ens
FROM
my_employee;
N lic
HA
I Commit all pending changes.
15. M
AS
SELECT
FROM

last_name, salary
my_employee;

l
rab
fe

COMMIT;

Control data transaction to the MY_EMPLOYEE table.
16. Populate the table with the last row of sample data listed in step 3 by using the statements in
the script that you created in step 6. Run the statements in the script.
SET ECHO OFF
SET VERIFY OFF
INSERT INTO my_employee
VALUES (&p_id, '&&p_last_name', '&&p_first_name',
lower(substr('&p_first_name', 1, 1) ||
substr('&p_last_name', 1, 7)), &p_salary);
SET VERIFY ON
SET ECHO ON
UNDEFINE p_first_name
UNDEFINE p_last_name

Oracle Database 10g: SQL Fundamentals I A - 24
SQL Star International Limited

Practice 8: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

17. Confirm your addition to the table.
SELECT
FROM

*
my_employee;

18. Mark an intermediate point in the processing of the transaction.
SAVEPOINT step_18;

19. Empty the entire table.
DELETE
FROM my_employee;

20. Confirm that the table is empty.

s

n
-tra
n

o
an
s
haearlier INSERT operation.
)
21. Discard the most recent DELETE operation without discarding the
ฺ
comGuide
ROLLBACK TO step_18;
ailฺ nt
m
@g tude
t
22. Confirm that the new row is still intact.
anc this S
SELECT *
imh se
FROM
my_employee;as
r
u
(na se to
C
23. Make the data addition permanent.
AN licen
COMMIT;
IMH
AS
SELECT *
FROM
my_employee;

R

NA

e

l
rab
fe

Oracle Database 10g: SQL Fundamentals I A - 25
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 9: Solutions
1. Create the DEPT table based on the following table instance chart. Place the
syntax in a script called lab_09_01.sql, and then execute the statement in the script to
create the table. Confirm that the table is created.
CREATE TABLE dept
(id
NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY,
name VARCHAR2(25));
DESCRIBE dept

2. Populate the DEPT table with data from the DEPARTMENTS table. Include only columns that
you need.
INSERT INTO dept
SELECT department_id, department_name
FROM
departments;

no
athe syntax in
3. Create the EMP table based on the following table instance chart. as
h Placeฺ script to create the
)
a script called lab_09_03.sql, and then execute the statement in the
comGuide
table. Confirm that the table is created.
ailฺ nt
m
CREATE TABLE emp
@g tude
(id
NUMBER(7),
t
last_name
VARCHAR2(25),
anc this S
first_name
VARCHAR2(25),
imh se
s
dept_id
NUMBER(7)
ara to u REFERENCES dept (id)
CONSTRAINT n
emp_dept_id_FK
C ( ense
);
N
HA emp lic
DESCRIBE
IM
AS

R

NA

s

n
-tra
n

4. 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.
CREATE TABLE employees2 AS
SELECT employee_id id, first_name, last_name, salary,
department_id dept_id
FROM
employees;

5. Drop the EMP table.
DROP TABLE emp;

Oracle Database 10g: SQL Fundamentals I A - 26

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 10: Solutions
Part 1
1. The staff in the HR department wants to hide some of the data in the EMPLOYEES table.
They want a view called EMPLOYEES_VU based on the employee numbers, employee last
names, and department numbers from the EMPLOYEES table. They want the heading for the
employee name to be EMPLOYEE.
CREATE OR REPLACE VIEW employees_vu AS
SELECT employee_id, last_name employee, department_id
FROM employees;

2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view.
SELECT
FROM

*
employees_vu;

s

n
-tra
n

o
an
has ฺ
SELECT
employee, department_id
)
FROM
employees_vu;
comGuide
ailฺ nt
gm d
4. Department 50 needs access to its employee data. Create a view named DEPT50 that
@last names,e department numbers for all
t
contains the employee numbers, employee Stu and
anc this that you label the view columns
employees in department 50. They have requested
imh se security purposes, do not allow an employee to be
EMPNO, EMPLOYEE,rand DEPTNO. For
as u
a department through the view.
reassigned to another
(n se to
C e AS
CREATE AN dept50n
VIEW
lic
H
SELECT
employee_id empno, last_name employee,
IM
department_id deptno
AS
3. Using your EMPLOYEES_VU view, write a query for the HR department to display all
employee names and department numbers.

R

NA

e

l
rab
fe

FROM
employees
WHERE
department_id = 50
WITH CHECK OPTION CONSTRAINT emp_dept_50;

5. Display the structure and contents of the DEPT50 view.
DESCRIBE dept50
SELECT
FROM

*
dept50;

6. Test your view. Attempt to reassign Matos to department 80.
UPDATE
SET
WHERE

dept50
deptno = 80
employee = 'Matos';

The error is due to the fact that the view “DEPT50” is created with CHECK OPTION
CONSTRAINT. This ensures that the deptno column in the view is protected from being
changed.
Oracle Database 10g: SQL Fundamentals I A - 27
SQL Star International Limited

Practice 10: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

You cannot make modifications to the deptno column that will result in the row being removed
from the view.
Part 2
7. You need a sequence that can be used with the primary key column of the DEPT table. The
sequence should start at 200 and have a maximum value of 1000. Have your sequence
increment by 10. Name the sequence DEPT_ID_SEQ.
CREATE SEQUENCE dept_id_seq
START WITH 200
INCREMENT BY 10
MAXVALUE 1000;

s
tran
8. To test your sequence, write a script to insert two rows in the DEPT table. Name your script
non Add two
lab_10_08.sql. Be sure to use the sequence that you created for the ID column.
a
departments: Education and Administration. Confirm your additions. Run the commands in
as
h
your script.
m) ideฺ
o
ilฺc t Gu
INSERT INTO dept
a
VALUES (dept_id_seq.nextval, 'Education');en
gm d
@
nct is Stu
INSERT INTO dept
a
VALUES (dept_id_seq.nextval, 'Administration');
mh se th
i
ras to u
(na se
9. Create a nonunique index on the NAME column in the DEPT table.
C n
CREATE AN dept_name_idx ON dept (name);
INDEX lice
IMH
AS Create a synonym for your EMPLOYEES table. Call it EMP.
10.

R

NA

CREATE SYNONYM emp FOR EMPLOYEES;

Oracle Database 10g: SQL Fundamentals I A - 28

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice 11: Solutions
1. For a specified table, create a script that reports the column names, data types, and lengths of
data types, as well as whether nulls are allowed. Prompt the user to enter the table name.
Give appropriate aliases to the columns DATA_PRECISION and DATA_SCALE. Save this
script in a file named lab_11_01.sql.
SELECT column_name, data_type, data_length,
data_precision PRECISION, data_scale SCALE, nullable
FROM
user_tab_columns
WHERE table_name = UPPER('&tab_name');

2. 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 of this information. Prompt the user to enter the
table name. Save the script in a file named lab_11_02.sql.

e

l
rab
fe

s
tran
SELECT ucc.column_name, uc.constraint_name, uc.constraint_type,
non
uc.search_condition, uc.status
a
FROM
user_constraints uc JOIN user_cons_columns ucc
as
h
ON
uc.table_name = ucc.table_name
m) ideฺ
o
AND
uc.constraint_name = ucc.constraint_name u
ilฺc t G
a
AND
uc.table_name = UPPER('&tab_name');
gm den
@
3. Add a comment to the DEPARTMENTS table. Then query the USER_TAB_COMMENTS view
nct is Stu
a
to verify that the comment is present. th
mh se
si u
COMMENT ON TABLE ara
departments IS
(n s to
'Company departmenteinformation including name, code, and location.';
C
AN licen
SELECT COMMENTS
IMH user_tab_comments
FROM
AS
WHERE table_name = 'DEPARTMENTS';

R

NA

4. Find the names of all synonyms that are in your schema.
SELECT *
FROM
user_synonyms;

Oracle Database 10g: SQL Fundamentals I A - 29
SQL Star International Limited

Practice 11: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

5. You need to determine the names and definitions of all the views in your schema. Create a
report that retrieves view information (the view name and text) from the USER_VIEWS data
dictionary view.
Note: Another view already exists. The EMP_DETAILS_VIEW was created as part of your
schema. Also, if you completed practice 10, you see the DEPT50 view.
Note: 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.
SET LONG 600
SELECT
FROM

e

view_name, text
user_views;

s

n
-tra
n

o
an
has ฺ
)
comGuide
SELECT
sequence_name, max_value, increment_by, last_number
ailฺ nt
FROM
user_sequences;
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
IM
AS

l
rab
fe

6. 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_11_06.sql. Run the statement in your script.

R

NA

Oracle Database 10g: SQL Fundamentals I A - 30
SQL Star International Limited

Practice C: Solutions

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

1. Write a query for the HR department to produce the addresses of all the departments. Use the
LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or
province, and country in the output.
SELECT location_id, street_address, city, state_province, country_name
FROM
locations, countries
WHERE locations.country_id = countries.country_id;

2. The HR department needs a report of all employees. Write a query to display the last name,
department number, and department name for all employees.
SELECT e.last_name, e.department_id, d.department_name
FROM
employees e, departments d
WHERE e.department_id = d.department_id;

s
tran
3. The HR department needs a report of employees in Toronto. Display the last name, job,
non
department number, and department name for all employees who work in Toronto.
a
as
SELECT e.last_name, e.job_id, e.department_id, d.department_name
h
FROM
employees e, departments d , locations l
m) ideฺ
o u
WHERE e.department_id = d.department_idilฺc
AND
d.location_id = l.location_idma
nt G
g
e
AND
LOWER(l.city) = 'toronto';
ct@ Stud
han his
4. Create a report to display the employeetlast name and employee number along with the last
im se
amanager and the manager number. Label the columns Employee,
name of the employee’s s
r
u
Emp#, Manager, and Mgr#, respectively. Place your SQL statement in a text file named
(na se to
C
lab_c_04.sql. en
AN lic
SELECT w.last_name "Employee", w.employee_id "EMP#",
IMH m.last_name "Manager", m.employee_id "Mgr#"
AS

R

NA

FROM
WHERE

employees w, employees m
w.manager_id = m.employee_id;

5. Modify lab_c_04.sql to display all employees, including King, who has no manager.
Order the results by the employee number. Place your SQL statement in a text file named
lab_c_05.sql. Run the query in lab_c_05.sql.
SELECT w.last_name "Employee", w.employee_id "EMP#",
m.last_name "Manager", m.employee_id "Mgr#"
FROM
employees w, employees m
WHERE w.manager_id = m.employee_id (+);

Oracle Database 10g: SQL Fundamentals I A - 31

e

l
rab
fe
SQL Star International Limited

Practice C: Solutions (continued)

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

6. Create a report for the HR department that displays employee last names, department
numbers, and all the employees who work in the same department as a given employee. Give
each column an appropriate label. Save the script to a file named lab_c_06.sql.
SELECT e.department_id department, e.last_name employee,
c.last_name colleague
FROM
employees e, employees c
WHERE e.department_id = c.department_id
AND
e.employee_id <> c.employee_id
ORDER BY e.department_id, e.last_name, c.last_name;

7. The HR department needs a report on job grades and salaries. To familiarize yourself with
the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then create a
query that displays the name, job, department name, salary, and grade for all employees.

s

n
-tra
n

DESC JOB_GRADES

o
an
SELECT e.last_name, e.job_id, d.department_name,
has ฺ
e.salary, j.grade_level
)
FROM
employees e, departments d, job_grades j
comGuide
WHERE e.department_id = d.department_idilฺ
a j.highest_sal;
AND
e.salary BETWEEN j.lowest_salm
g AND dent
@ tu
nct following exercises:
If you want an extra challenge, complete the is S
a
mh se th
i
8. The HR department wants to determine the names of all employees hired after Davies. Create
ras to u
(na se
a query to display the name and hire date of any employee hired after employee Davies.
C en
SELECT AN
e.last_name, e.hire_date
lic
FROM H employees e , employees davies
IM
WHERE davies.last_name = 'Davies'
AS

R

NA

AND

davies.hire_date < e.hire_date;

9. The HR department needs to find the names and hire dates for all employees who were hired
before their managers, along with their manager’s names and hire dates. Label the columns
Employee, Emp Hired, Manager, and Mgr Hired, respectively. Save the script to a file
named lab_c_09.sql.
SELECT
FROM
WHERE
AND

w.last_name, w.hire_date, m.last_name, m.hire_date
employees w , employees m
w.manager_id = m.employee_id
w.hire_date < m.hire_date;

Oracle Database 10g: SQL Fundamentals I A - 32

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

B
Table Descriptions and Data

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Human Resources (HR)
Data Set
e

l
rab
fe

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

JOB_GRADES
GRADE_LEVEL
LOWEST_SAL
HIGHEST_SAL

Oracle Database 10g: SQL Fundamentals I B - 2
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Human Resources (HR) Data Set
The Human Resources (HR) schema is part of the Oracle Common Schema that can be
installed in an Oracle Database. The practices in this course use the data from the HR
schema.
Table Descriptions
REGIONS contains rows representing a region (such as Americas, Asia, and so on).
COUNTRIES contains rows for countries, each of which are associated with a region.
LOCATIONS contains the addresses of specific offices, warehouses, and/or production sites
of a company in a particular country.
DEPARTMENTS shows details of the departments in which employees work. Each
department can have a relationship representing the department manager in the EMPLOYEES
table.
EMPLOYEES contains details about each employee who works for a department. Some
employees may not be assigned to any department.
JOBS contains the job types that can be held by each employee.
JOB_HISTORY contains the job history of the employees. If an employee changes
departments within the job or changes jobs within the department, a new row is inserted in
this table with the old job information of the employee.
JOB_GRADES identifies a salary range per job grade. The salary ranges do not overlap.

s

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 3

e

l
rab
fe
SQL Star International Limited

COUNTRIES Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE countries

SELECT * FROM countries;

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 4
SQL Star International Limited

DEPARTMENTS Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE departments

SELECT * FROM departments;

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 5
SQL Star International Limited

EMPLOYEES Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE employees

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
SELECT * FROM employees;
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
IM
AS
R

NA

Oracle Database 10g: SQL Fundamentals I B - 6
SQL Star International Limited

JOBS Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE jobs

e

SELECT * FROM jobs;

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 7

l
rab
fe
SQL Star International Limited

JOB_GRADES Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE job_grades

SELECT * FROM job_grades;

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 8
SQL Star International Limited

JOB_HISTORY Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE job_history

e

SELECT * FROM job_history;

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 9

l
rab
fe
SQL Star International Limited

LOCATIONS Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE locations

e

s

n
-tra
n

SELECT * FROM locations;

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 10

l
rab
fe
SQL Star International Limited

REGIONS Table

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DESCRIBE regions

SELECT * FROM regions;

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I B - 11
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Oracle Join Syntax

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Objectives
After completing this lesson, you should be able to do the
following:
• Write SELECT statements to access data from more than
one table using equijoins and nonequijoins
• Use outer joins to view data that generally does not meet a
join condition
e
abl
• Join a table to itself by using a self-join
fer

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Objectives
IMHexplains how to obtain data from more than one table. A join is used to view information
S
This lesson
RA multiple tables. Therefore, you can join tables together to view information from more than one
NA from
table.
Note: Information on joins is found in “SQL Queries and Subqueries: Joins” in
Oracle SQL Reference.

Oracle Database 10g: SQL Fundamentals I C - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Obtaining Data from Multiple Tables

EMPLOYEES

DEPARTMENTS

…

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
…
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Tables
Data from H
Multiple lic
IM
Sometimes you need to use data from more than one table. In the slide example, the report displays
AS
R
NA data from two separate tables:

• Employee IDs exist in the EMPLOYEES table.
• Department IDs exist in both the EMPLOYEES and DEPARTMENTS tables.
• Department names exist in the DEPARTMENTS table.
To produce the report, you need to link the EMPLOYEES and DEPARTMENTS tables and access data
from both of them.

Oracle Database 10g: SQL Fundamentals I C - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Cartesian Products
•

A Cartesian product is formed when:
– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all rows in the second
table

•

To avoid a Cartesian product, always include a valid join
condition in a WHERE clause.

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Cartesian H
Products
IaM condition is invalid or omitted completely, the result is a Cartesian product, in which all
S
When join
RA
NA combinations of rows are displayed. All rows in the first table are joined to all rows in the second
table.
A Cartesian product tends to generate a large number of rows, and the result is rarely useful. You
should always include a valid join condition unless you have a specific need to combine all rows
from all tables.
Cartesian products are useful for some tests when you need to generate a large number of rows to
simulate a reasonable amount of data.

Oracle Database 10g: SQL Fundamentals I C - 4
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Generating a Cartesian Product
EMPLOYEES (20 rows)

DEPARTMENTS (8 rows)

…

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
…
)
Cartesian product:
comGuide
20 x 8 = 160 rows
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN l(continued)
Cartesian H
Products ic
IM
A Cartesian product is generated if a join condition is omitted. The example in the slide displays
AS last name and department name from the EMPLOYEES and DEPARTMENTS tables.
R
NA employee

Because no join condition has been specified, all rows (20 rows) from the EMPLOYEES table are
joined with all rows (8 rows) in the DEPARTMENTS table, thereby generating 160 rows in the output.
SELECT last_name, department_name dept_name
FROM
employees, departments;

…

Oracle Database 10g: SQL Fundamentals I C - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Types of Joins

Oracle-proprietary joins
(8i and earlier releases)

SQL:1999–compliant joins

•
•
•
•

•
•
•
•

Equijoin
Nonequijoin
Outer join
Self-join

•

Cross join
Natural join
Using clause
e
abl
r
Full (or two-sided) nsfe
a
outer join
n-tr
o
Arbitrary join condition
an
has ฺ
for outer join
)

N

m
e
ฺco Guid
il t
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Types of Joins
IMH
S
Before the release of Oracle9i Database, the join syntax was proprietary.
RA The SQL:1999–compliant join syntax does not offer any performance benefits over the OracleA Note:
proprietary join syntax that existed in prior releases. For detailed information about the SQL:1999–
compliant join syntax, see Lesson 5.

Oracle Database 10g: SQL Fundamentals I C - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Joining Tables Using Oracle Syntax
Use a join to query data from more than one table:
SELECT
FROM
WHERE

table1.column, table2.column
table1, table2
table1.column1 = table2.column2;

Write the join condition in the WHERE clause.

e

•

l
rab
fe

•

Prefix the column name with the table name when the ns
a
same column name appears in more than one table.tr
no

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Defining Joins
MH
Idata from more than one table in the database is required, a join condition is used. Rows in one
S
When
RA can be joined to rows in another table according to common values that exist in corresponding
NA table
columns (that is, usually primary and foreign key columns).
To display data from two or more related tables, write a simple join condition in the WHERE clause.

In the syntax:
table1.column
table1.column1 =
table2.column2

denotes the table and column from which data is retrieved
is the condition that joins (or relates) the tables together

Guidelines
• When writing a SELECT statement that joins tables, precede the column name with the table
name for clarity and to enhance database access.
• If the same column name appears in more than one table, the column name must be prefixed
with the table name.
• To join n tables together, you need a minimum of n-1 join conditions. For example, to join four
tables, a minimum of three joins is required. This rule may not apply if your table has a
concatenated primary key, in which case more than one column is required to uniquely identify
each row.
Oracle Database 10g: SQL Fundamentals I C - 7
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Equijoins
EMPLOYEES

DEPARTMENTS

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
Foreign key nc
Primary key
a this S
h
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C
AN licen
Equijoins H
IM
To determine an employee’s department name, you compare the value in the DEPARTMENT_ID
AS in the EMPLOYEES table with the DEPARTMENT_ID values in the DEPARTMENTS table.
R
NA column

The relationship between the EMPLOYEES and DEPARTMENTS tables is an equijoin—that is, values
in the DEPARTMENT_ID column in both tables must be equal. Frequently, this type of join involves
primary and foreign key complements.
Note: Equijoins are also called simple joins or inner joins.

Oracle Database 10g: SQL Fundamentals I C - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Retrieving Records
with Equijoins
SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
departments.location_id
FROM
employees, departments
WHERE employees.department_id = departments.department_id;

e

l
rab
fe

s

…

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C e
AN lwith n
RetrievingH
Records ic Equijoins
IM
In the slide example:
AS SELECT clause specifies the column names to retrieve:
R
NA • The

- Employee last name, employee number, and department number, which are columns in the
EMPLOYEES table
- Department number, department name, and location ID, which are columns in the
DEPARTMENTS table
• The FROM clause specifies the two tables that the database must access:
- EMPLOYEES table
- DEPARTMENTS table
• The WHERE clause specifies how the tables are to be joined:
EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID

Because the DEPARTMENT_ID column is common to both tables, it must be prefixed by the table
name to avoid ambiguity.

Oracle Database 10g: SQL Fundamentals I C - 9
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Additional Search Conditions
Using the AND Operator
EMPLOYEES

DEPARTMENTS

e

l
rab
fe

s

n
-tra
n

o
an
…
…
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Conditions
AdditionalH
Search lic
IM
In addition to the join, you may have criteria for your WHERE clause to restrict the rows under
AS
R
NA consideration for one or more tables in the join. For example, to display employee Matos’s

department number and department name, you need an additional condition in the WHERE clause.
SELECT last_name, employees.department_id,
department_name
FROM
employees, departments
WHERE employees.department_id = departments.department_id
AND
last_name = 'Matos';

Oracle Database 10g: SQL Fundamentals I C - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Qualifying Ambiguous Column Names
•
•
•

Use table prefixes to qualify column names that are in
multiple tables.
Use table prefixes to improve performance.
Use column aliases to distinguish columns that have
identical names but reside in different tables.

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
QualifyingH
Ambiguous Column Names
IM to qualify the names of the columns in the WHERE clause with the table name to avoid
S
You need
RA
ambiguity. Without the table prefixes, the DEPARTMENT_ID column could be from either the
NA

DEPARTMENTS table or the EMPLOYEES table. It is necessary to add the table prefix to execute
your query.
If there are no common column names between the two tables, there is no need to qualify the
columns. However, using the table prefix improves performance, because you tell the Oracle server
exactly where to find the columns.
The requirement to qualify ambiguous column names is also applicable to columns that may be
ambiguous in other clauses, such as the SELECT clause or the ORDER BY clause.

Oracle Database 10g: SQL Fundamentals I C - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using Table Aliases
•
•

Use table aliases to simplify queries.
Use table prefixes to improve performance.

SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM
employees e , departments d
WHERE e.department_id = d.department_id;

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Using Table Aliases
IMH
S
Qualifying column names with table names can be very time consuming, particularly if table names
RA lengthy. You can use table aliases instead of table names. Just as a column alias gives a column
NA are

another name, a table alias gives a table another name. Table aliases help to keep SQL code smaller,
therefore using less memory.
Notice how table aliases are identified in the FROM clause in the example. The table name is
specified in full, followed by a space and then the table alias. The EMPLOYEES table has been given
an alias of e, and the DEPARTMENTS table has an alias of d.
Guidelines
• Table aliases can be up to 30 characters in length, but shorter aliases are better than longer ones.
• If a table alias is used for a particular table name in the FROM clause, then that table alias must
be substituted for the table name throughout the SELECT statement.
• Table aliases should be meaningful.
• The table alias is valid for only the current SELECT statement.

Oracle Database 10g: SQL Fundamentals I C - 12
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Joining More Than Two Tables

EMPLOYEES

DEPARTMENTS

LOCATIONS

e

l
rab
fe

s

n
-tra
n

N

o
an
…
has ฺ
)
o
ca mGuide n–1
To join n tables together, you need minimum of
ailฺ nt
m
join conditions. For example, tode three tables, a
@gjoinsuisjoin
minimum ct two St
of
required.
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C en
AN Conditions
AdditionalH
Search lic
IM
Sometimes you may need to join more than two tables. For example, to display the last name, the
AS
department name, and the city for each employee, you have to join the EMPLOYEES,
AR
DEPARTMENTS, and LOCATIONS tables.
SELECT
FROM
WHERE
AND

e.last_name, d.department_name, l.city
employees e, departments d, locations l
e.department_id = d.department_id
d.location_id = l.location_id;

…
Oracle Database 10g: SQL Fundamentals I C - 13
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Nonequijoins

EMPLOYEES

JOB_GRADES

e

l
rab
fe

s

n
-tra
n

…

o
Salary in the EMPLOYEES
an
table must bes
between
ha and highest
)
lowest salary eฺ
comGuid
salary
ailฺ ntin the JOB_GRADES
gm table.
e

d
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
Nonequijoins
IMH is a join condition containing something other than an equality operator.
S
A nonequijoin
RA relationship between the EMPLOYEES table and the JOB_GRADES table is an example of a
NA The

nonequijoin. A relationship between the two tables is that the SALARY column in the EMPLOYEES
table must be between the values in the LOWEST_SALARY and HIGHEST_SALARY columns of the
JOB_GRADES table. The relationship is obtained using an operator other than equality (=).

Oracle Database 10g: SQL Fundamentals I C - 14
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Retrieving Records
with Nonequijoins
SELECT e.last_name, e.salary, j.grade_level
FROM
employees e, job_grades j
WHERE e.salary
BETWEEN j.lowest_sal AND j.highest_sal;

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
…
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
N C licen
A(continued)
Nonequijoins
MH
TheSI example creates a nonequijoin to evaluate an employee’s salary grade. The salary must be
slide
A
between any pair of the low and high salary ranges.
AR
N

It is important to note that all employees appear exactly once when this query is executed. No
employee is repeated in the list. There are two reasons for this:
• None of the rows in the job grade table contain grades that overlap. That is, the salary value for
an employee can lie only between the low salary and high salary values of one of the rows in the
salary grade table.
• All of the employees’ salaries lie within the limits that are provided by the job grade table. That
is, no employee earns less than the lowest value contained in the LOWEST_SAL column or more
than the highest value contained in the HIGHEST_SAL column.
Note: Other conditions (such as <= and >=) can be used, but BETWEEN is the simplest. Remember
to specify the low value first and the high value last when using BETWEEN.
Table aliases have been specified in the slide example for performance reasons, not because of
possible ambiguity.

Oracle Database 10g: SQL Fundamentals I C - 15
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Outer Joins

DEPARTMENTS

EMPLOYEES

e

l
rab
fe

s

n
-tra
n

o
an
…
has ฺ
)
comGuide
ailฺ nt
There are no employees in
m e
d
@g department 190.
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C e
AN with n Direct Match with Outer Joins
ReturningH
Records lic No
IM
If a S does not satisfy a join condition, the row does not appear in the query result. For example, in
row
A equijoin condition of the EMPLOYEES and DEPARTMENTS tables, employee Grant does not
R
NA the
appear because there is no department ID recorded for her in the EMPLOYEES table. Instead of
seeing 20 employees in the result set, you see 19 records.
SELECT e.last_name, e.department_id, d.department_name
FROM
employees e, departments d
WHERE e.department_id = d.department_id;

…

Oracle Database 10g: SQL Fundamentals I C - 16
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Outer Joins Syntax
•
•

You use an outer join to see rows that do not meet the join
condition.
The outer join operator is the plus sign (+).

SELECT table1.column, table2.column
FROM
table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
a
as
h
FROM
table1, table2
m) ideฺ
o u
WHERE table1.column = table2.column(+);
ilฺc

e

l
rab
fe

s

n
-tra
n

no

G
a
gm dent
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN toicen Records with No Direct Match
Using Outer Joins l Return
IMH rows can be returned if an outer join operator is used in the join condition. The operator
TheS
missing
RA plus sign enclosed in parentheses (+), and it is placed on the “side” of the join that is deficient in
NA is a
information. This operator has the effect of creating one or more null rows, to which one or more
rows from the nondeficient table can be joined.
In the syntax:
table1.column =
is the condition that joins (or relates) the tables together
table2.column (+) is the outer join symbol, which can be placed on either side of the
WHERE clause condition, but not on both sides. (Place the outer join symbol following the name of
the column in the table without the matching rows.)

Oracle Database 10g: SQL Fundamentals I C - 17
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using Outer Joins

SELECT e.last_name, e.department_id, d.department_name
FROM
employees e, departments d
WHERE

e.department_id(+) = d.department_id ;

e

l
rab
fe

s

…

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN toicen Records with No Direct Match (continued)
Using Outer Joins l Return
H
IMexample displays employee last names, department IDs, and department names. The
TheS
slide
RA
NA Contracting department does not have any employees. The empty value is shown in the output.

Outer Join Restrictions
• The outer join operator can appear on only one side of the expression - the side that has
information missing. It returns those rows from one table that have no direct match in the other
table.
• A condition involving an outer join cannot use the IN operator or be linked to another condition
by the OR operator.

Oracle Database 10g: SQL Fundamentals I C - 18
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Self-Joins

EMPLOYEES (WORKER)

EMPLOYEES (MANAGER)

e

l
rab
fe

s

n
-tra
n

o
an
…
…
has ฺ
)
comGuide
ailฺ nt
m e
MANAGER_ID in @gWORKER table is equal to
the
ud
nct i in the
EMPLOYEE_IDs St MANAGER table.
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C e
ANto Itself n
Joining a Table
lic
H
IM
Sometimes you need to join a table to itself. To find the name of each employee’s manager, you need
AS the EMPLOYEES table to itself; this type of join is called a self-join.
R
NA to join
For example, to find the name of Lorentz’s manager, you need to do the following:
• Find Lorentz in the EMPLOYEES table by looking at the LAST_NAME column.
• Find the manager number for Lorentz by looking at the MANAGER_ID column.
Lorentz’s manager number is 103.
• Find the name of the manager who has EMPLOYEE_ID 103 by looking at the LAST_NAME
column. Hunold’s employee number is 103, so Hunold is Lorentz’s manager.
In this process, you look in the table twice. The first time you look in the table to find Lorentz in the
LAST_NAME column and the MANAGER_ID value of 103. The second time you look in the
EMPLOYEE_ID column to find 103 and the LAST_NAME column to find Hunold.

Oracle Database 10g: SQL Fundamentals I C - 19
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Joining a Table to Itself

SELECT worker.last_name || ' works for '
|| manager.last_name
FROM
employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
…
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
ANto Itself (continued)
Joining a Table
lic
H
M
TheSI example joins the EMPLOYEES table to itself. To simulate two tables in the FROM clause,
A slidetwo aliases, namely w and m, for the same table, EMPLOYEES.
R
NA there are

In this example, the WHERE clause contains the join that means “where a worker’s manager number
matches the employee number for the manager.”

Oracle Database 10g: SQL Fundamentals I C - 20
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Summary
In this appendix, you should have learned how to use joins to
display data from multiple tables by using Oracle-proprietary
syntax for versions 8i and earlier.

e

l
rab
fe

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Summary H
IM
There are multiple ways to join tables.
AS
R
NA Types of Joins

• Cartesian products
• Equijoins
• Nonequijoins
• Outer joins
• Self-joins
Cartesian Products
A Cartesian product results in a display of all combinations of rows. This is done by omitting the
WHERE clause.
Table Aliases
• Table aliases speed up database access.
• Table aliases can help to keep SQL code smaller by conserving memory.

Oracle Database 10g: SQL Fundamentals I C - 21
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C: Overview
This practice covers writing queries to join tables using Oracle
syntax.

e

l
rab
fe

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Practice C: Overview
IMH is designed to give you a variety of exercises that join tables using the Oracle syntax
S
This practice
RA was covered in this appendix.
NA that

Oracle Database 10g: SQL Fundamentals I C - 22
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C
1. Write a query for the HR department to produce the addresses of all the departments. Use the
LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or
province, and country in the output.

2. The HR department needs a report of all employees. Write a query to display the last name,
department number, and department name for all employees.

s

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I C - 23

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C (continued)
3. The HR department needs a report of employees in Toronto. Display the last name, job,
department number, and department name for all employees who work in Toronto.

4. Create a report to display the employee last name and employee number along with the
employee’s manager’s last name and manager number. Label the columns Employee, Emp#,
Manager, and Mgr#, respectively. Place your SQL statement in a text file named
lab_c_04.sql.

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I C - 24
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C (continued)
5. Modify lab_c_04.sql to display all employees including King, who has no manager. Order
the results by the employee number. Place your SQL statement in a text file named
lab_c_05.sql. Run the query in lab_c_05.sql.

…

e

l
rab
fe

s

n
-tra
n

no

6. Create a report for the HR department that displays employee lasts a department numbers,
names,
a employee. Give each
and all the employees who work in the same department as ) given
ah
ฺ
m lab_c_06.sql.
column an appropriate label. Save the script to a file named
o
ide

c
ailฺ nt Gu
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM
AS …
R

NA

Oracle Database 10g: SQL Fundamentals I C - 25
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C (continued)
7. The HR department needs a report on job grades and salaries. To familiarize yourself with the
JOB_GRADES table, first show the structure of the JOB_GRADES table. Second, create a query
that displays the last name, job, department name, salary, and grade for all employees.

e

s

l
rab
fe

o

n
-tra
n

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I C - 26
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Practice C (continued)
If you want an extra challenge, complete the following exercises:
8. The HR department wants to determine the names of all employees hired after Davies. Create a
query to display the name and hire date of any employee hired after employee Davies.

e

l
rab
fe

s

n
-tra
n

9. The HR department needs to find the name and hire date for all employees who were hired
no
a Label the columns
before their managers, along with their manager’s name and hire date.
Employee, Emp Hired, Manager, and Mgr Hired, respectively. Save the script to a file
has ฺ
)
named lab_c_09.sql.
om ide

c
ailฺ nt Gu
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA

IM

S
RA

NA

Oracle Database 10g: SQL Fundamentals I C - 27
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Using SQL*Plus

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Objectives
After completing this appendix, you should be able to do the
following:
• Log in to SQL*Plus
• Edit SQL commands
• Format output using SQL*Plus commands
• Interact with script files

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Objectives
IMHwant to create SELECT statements that can be used again and again. This appendix
S
You might
RA

also covers the use 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.

Oracle Database 10g: SQL Fundamentals I D - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL and SQL*Plus Interaction

SQL statements
Server
SQL*Plus

e

l
rab
fe

Query results

s

Buffer

n
-tra
n

N

o
an
has ฺ
)
comGuide
SQL ailฺ
gm dent
scripts
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C
AN licen
SQL and H
M SQL*Plus
Iis a command language for communication with the Oracle9i Server from any tool or
AS
RSQL
A application. Oracle SQL contains many extensions. When you enter a SQL statement, it is stored
in a 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
Oracle Database 10g: SQL Fundamentals I D - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Statements Versus
SQL*Plus Commands
SQL
• A language
• ANSI-standard
• Keywords cannot be
abbreviated
• Statements manipulate
data and table
definitions in the
database

SQL*Plus
• An environment
• Oracle-proprietary
• Keywords can be
abbreviated
• Commands do not allow
le
manipulation of values in erab
f
the database
ans

tr

non

N

a
as
h
m) ideฺ
o
SQL
SQL
SQL*Plus u
SQL*Plus
ilฺc t G
a n
statements
buffer
commands
buffer
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN li(continued)
SQL and H
SQL*Plus c
IM
The following table compares SQL and SQL*Plus:
AS
AR
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

Oracle Database 10g: SQL Fundamentals I D - 4
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

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
e
abl
r
Execute saved files
sfe
n
-tra
Load commands from file to buffer to edit
on

NA

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
SQL*Plus
IMHis an environment in which you can do the following:
AS
RSQL*Plus

• 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
Environment
Format
File manipulation
Execution
Edit
Interaction
Miscellaneous

Purpose
Affect the general behavior of SQL statements for the session
Format query results
Save, load, and run script files
Send SQL statements from the SQL buffer to the Oracle server
Modify SQL statements in the buffer
Create and pass variables to SQL statements, print variable values, and
print messages to the screen
Connect to the database, manipulate the SQL*Plus environment, and
display column definitions

Oracle Database 10g: SQL Fundamentals I D - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Logging In to SQL*Plus
•
•

From a Linux desktop icon
From a Linux terminal

sqlplus [username[/password
[@database]]]

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Logging In to SQL*Plus
M
IyouH
How
AS invoke SQL*Plus depends on which type of operating system or environment you are
ARrunning.
To log in using a desktop icon:
1. Double-click the sqlplus desktop icon.
2. Enter the username, password, and database name.
To log in from a Linux terminal:
1. Log on to your machine and open a terminal.
2. Enter the SQL*Plus 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.

Oracle Database 10g: SQL Fundamentals I D - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Displaying Table Structure
Use the SQL*Plus DESCRIBE command to display the structure
of a table:

DESC[RIBE] tablename

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Structure
Displaying Table lic
IMH you can display the structure of a table using the DESCRIBE command. The result
S
In SQL*Plus,
RA
of the command is a display of column names and data types as well as an indication if a column
must contain data.
In the syntax:
tablename The name of any existing table, view, or synonym that is accessible to
the user
To describe the JOB_GRADES table, use this command:
SQL> DESCRIBE job_grades
Name
---------------------------------GRADE_LEVEL
LOWEST_SAL
HIGHEST_SAL

Null?
--------

Type
----------VARCHAR2(3)
NUMBER
NUMBER

Oracle Database 10g: SQL Fundamentals I D - 7
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Displaying Table Structure

SQL> DESCRIBE departments

Name
----------------------DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID

Null?
Type
-------- -----------NOT NULL NUMBER(4)
NOT NULL VARCHAR2(30)
NUMBER(6)
NUMBER(4)

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Structure (continued)
Displaying Table lic
IMH in the slide displays the information about the structure of the DEPARTMENTS
S
The example
RA
table.

In the result:
Null?
Type

Specifies whether a column must contain data (NOT NULL indicates
that a column must contain data.)
Displays the data type for a column

The following table describes the data types:
Data Type
NUMBER(p,s)
VARCHAR2(s)
DATE
CHAR(s)

Description
Number value that has a maximum number of digits p, which
is the number of digits to the right of the decimal point s
Variable-length character value of maximum size s
Date and time value between January 1, 4712 B.C., and
December 31, 9999 A.D.
Fixed-length character value of size s

Oracle Database 10g: SQL Fundamentals I D - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL*Plus Editing Commands
•
•
•
•
•
•
•

A[PPEND] text
C[HANGE] / old / new
C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Commands
SQL*Plus Editing lic
IMHcommands are entered one line at a time and are not stored in the SQL buffer.
AS
RSQL*Plus
Command
A[PPEND] text
C[HANGE] / old / new

Description
Adds text to the end of the current line
Changes old text to new in the current line

C[HANGE] / text /
CL[EAR] BUFF[ER]
DEL
DEL n
DEL m n

Deletes
Deletes
Deletes
Deletes
Deletes

text from the current line
all lines from the SQL buffer
current line
line n
lines m to n inclusive

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.

Oracle Database 10g: SQL Fundamentals I D - 9
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL*Plus Editing Commands
•
•
•
•
•
•
•
•
•

I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text

e

s

I[NPUT]
I[NPUT] text
L[IST]
L[IST] n
L[IST] m n
R[UN]
n
n text
0 text

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Commands (continued)
SQL*Plus Editing lic
IMH
S
Description
RA Command

NA

l
rab
fe

Inserts an indefinite number of lines
Inserts a line consisting of text
Lists all lines in the SQL buffer
Lists one line (specified by n)
Lists a range of lines (m to n) inclusive
Displays and runs the current SQL statement in the buffer
Specifies the line to make the current line
Replaces line n with text
Inserts a line before line 1

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

Oracle Database 10g: SQL Fundamentals I D - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using LIST, n, and APPEND

SQL> LIST
1 SELECT last_name
2* FROM
employees
SQL> 1

e

l
rab
fe

1* SELECT last_name
SQL> A , job_id

s

n
-tra
n

N

o
an
has ฺ
)
SQL> L
comGuide
ailฺ nt
1 SELECT last_name, job_id
gm de
2* FROM
employees ct@
tu
an this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
N C cen
An, andliAPPEND
Using LIST,
IMH L[IST] command to display the contents of the SQL buffer. The asterisk (*)
•SUse the
RA beside line 2 in the buffer indicates that line 2 is the current line. Any edits that you made
A
1* SELECT last_name, job_id

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.

Oracle Database 10g: SQL Fundamentals I D - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the CHANGE Command

SQL> L
1* SELECT * from employees
SQL> c/employees/departments

e

l
rab
fe

1* SELECT * from departments

s

SQL> L

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Command
Using the CHANGE lic
IMH
•SUse L[IST] to display the contents of the buffer.
RA Use the C[HANGE] command to alter the contents of the current line in the SQL buffer. In
A •
1* SELECT * from departments

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.

Oracle Database 10g: SQL Fundamentals I D - 12
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL*Plus File Commands
•
•
•
•
•
•
•

SAVE filename
GET filename
START filename
@ filename
EDIT filename
SPOOL filename
EXIT

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
SQL*Plus File Commands
MH
Istatements communicate with the Oracle server. SQL*Plus commands control the
AS
RSQL

environment, format query results, and manage files. You can use the commands described in
the following table:
Command

Description

SAV[E] filename [.ext]
[REP[LACE]APP[END]]

Saves current contents of SQL buffer to a file. Use APPEND
to add to an existing file; use REPLACE to overwrite an
existing file. The default extension is .sql.

GET filename [.ext]
STA[RT] filename [.ext]

Writes the contents of a previously saved file to the SQL
buffer. The default extension for the file name is .sql.
Runs a previously saved command file

@ filename

Runs a previously saved command file (same as START)

ED[IT]

Invokes the editor and saves the buffer contents to a file
named afiedt.buf

ED[IT] [filename[.ext]]
SPO[OL]
[filename[.ext]|
OFF|OUT]
EXIT

Invokes the editor to edit the contents of a saved file
Stores query results in a file. OFF closes the spool file. OUT
closes the spool file and sends the file results to the printer.
Quits SQL*Plus

Oracle Database 10g: SQL Fundamentals I D - 13
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using the SAVE and START Commands

SQL>
1
2*
SQL>

L
SELECT last_name, manager_id, department_id
FROM
employees
SAVE my_query

Created file my_query
SQL> START my_query

e

l
rab
fe

ns

a
LAST_NAME
MANAGER_ID DEPARTMENT_ID
n-tr
o
------------------------- ---------- ------------an
King
90
has ฺ
Kochhar
100
90
)
om uide
...
c
ailฺ nt G
20 rows selected.
m

g
t@ Stude
c
han this
m
asiCopyrightse Oracle. All rights reserved.
r
u
(na se to © 2009,
C
AN licen
H

SAVE
IM
Use the SAVE command to store the current contents of the buffer in a file. In this way, you can
AS
R
NA store frequently used scripts for use in the future.
START
Use the START command to run a script in SQL*Plus.
EDIT
Use the 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.

Oracle Database 10g: SQL Fundamentals I D - 14
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

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 output
• Interact with script files

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Summary
IMHis an execution environment that you can use to send SQL commands to the database
AS
RSQL*Plus

NA

server and to edit and save SQL commands. You can execute commands from the SQL prompt
or from a script file.

Oracle Database 10g: SQL Fundamentals I D - 15

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Using SQL Developer

e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
H
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

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
• Identify menu items of Oracle SQL Developer
• Create a database connection
e
abl
r
• Manage database objects
sfe
n
-tra
• Use SQL Worksheet
non
• Execute SQL statements and SQL scripts s a
) ha eฺ
• Create and save reports
om d

NA

i
c
ailฺ nt Gu
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Objectives
IMH
AS
RIn this appendix, you are introduced to the graphical tool SQL Developer. You learn how to use
SQL Developer for your database development tasks. You learn how to use SQL Worksheet to
execute SQL statements and SQL scripts.

Oracle Database 10g: SQL Fundamentals I E - 2
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

What Is Oracle SQL Developer?
•

•

Oracle SQL Developer is a free graphical tool that
enhances productivity and simplifies database
development tasks.
You can connect to any target Oracle Database schema
using standard Oracle Database authentication.

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
ANSQLicen
l Developer?
What Is Oracle
IMH Developer is a free graphical tool designed to improve your productivity and
Oracle SQL
AS
Rsimplify the development of everyday database tasks. With just a few clicks, you can easily
A
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 using standard Oracle Database
authentication. When connected, you can perform operations on objects in the database.

Oracle Database 10g: SQL Fundamentals I E - 3
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Key Features
•
•
•
•
•
•

Developed in Java
Supports Windows, Linux, and Mac OS X platforms
Default connectivity by using the JDBC Thin driver
Does not require an installer
Connects to any Oracle Database version 9.2.0.1 and later
Bundled with JRE 1.5

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN SQL Developer
Key Features of lic
IMH Developer is developed in Java, leveraging the Oracle JDeveloper IDE. The tool
AS
ROracle SQLWindows, Linux, and Mac OS X platforms. You can install SQL Developer on the
A runs on the

N

Database Server and connect remotely from your desktop, thus avoiding client server network
traffic.
Default connectivity to the database is through the JDBC Thin driver; so, no Oracle Home is
required. SQL Developer does not require an installer and you need to just unzip the
downloaded file.
With SQL Developer, users can connect to Oracle Database 9.2.0.1 and later versions, and all
Oracle Database editions including Express Edition. SQL Developer is bundled with JRE 1.5,
with an additional tools.jar to support Windows clients. Non-Windows clients need only
JDK 1.5.

Oracle Database 10g: SQL Fundamentals I E - 4

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Installing SQL Developer
Download the Oracle SQL Developer kit and unzip it into any
directory on your machine.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
ANDeveloper
lic
InstallingH
SQL
IM
Oracle SQL Developer does not require an installer. To install SQL Developer, you need an
AS
R
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/software/products/sql/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.

Oracle Database 10g: SQL Fundamentals I E - 5
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Menus for SQL Developer

4

2
1

3

6

7

5

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Developer
lic
Menus for SQL
H
IM
SQL Developer has two main navigation tabs.
AS
AR • Connections Navigator: By using this tab, you can browse database objects and users to
which you have access.
• Reporting Tab: By using this tab, you can run predefined reports or create and add your
own reports.
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 menus at the top contain standard
entries, plus entries for features specific to SQL Developer.
1. View: Contains options that affect what is displayed in the SQL Developer interface
2. Navigate: Contains options for navigating to panes and for the execution of subprograms
3. Run: Contains the Run File and Execution Profile options that are relevant when a function
or procedure is selected
4. Source: Contains options for use when editing functions and procedures
5. Versioning: Enables you to work with the files placed under source code control
6. Migration: Enables you to migrate from another database, such as Microsoft SQL Server
and Microsoft Access, to an Oracle Database
7. Tools: Invokes SQL Worksheet, Preferences, and any added External Tools
Oracle Database 10g: SQL Fundamentals I E - 6
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Database Connection
•
•

You must have at least one database connection to use
SQL Developer.
You can create and test connections:
– For multiple databases
– For multiple schemas

•
•
•

SQL Developer automatically imports any connections
defined in the tnsnames.ora file on your system.

e

l
rab
fe

s

n
You can export connections to an XML file.
-tra
non
Each additional database connection created is listed in
a
as
the connections navigator hierarchy. ) h

NA

ฺ
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN licConnection
Creating HDatabase
a
IM is a SQL Developer object that specifies the necessary information for connecting
AS
RA connection

to a specific database as a specific user of that database. To use SQL Developer, you must have
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 systems, 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 to connect to the same database but as different users, or
to connect to different databases. Each database connection is listed in the Connections
navigator hierarchy.

Oracle Database 10g: SQL Fundamentals I E - 7
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Database Connection

e

l
rab
fe

s

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN licConnection (continued)
Creating HDatabase
a
IM a database connection, perform the following steps:
AS
RTo create

NA

n
-tra
n

1. Double-click <your_path>sqldevelopersqldeveloper.exe.
2. On the Connections tabbed page, right-click Connections and select New Connection.
3. Enter the connection name, username, password, host name, port number, and SID for the
database you want to connect.
4. Click Test to make sure that the connection has been set correctly.
5. Click Connect.
Note: If you select the Save Password check box, the password is saved to an XML file. So,
after you close the SQL Developer connection and open it again, you will not be prompted for
the password.

Oracle Database 10g: SQL Fundamentals I E - 8
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Browsing Database Objects
Use the Database Navigator to:
• Browse through many objects in a database schema
• Do a quick review of the definitions of objects

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Browsing Database Objects
M
IyouH a database connection, you can use the Database Navigator to browse through
After
AS create
R
many objects in a database schema including Tables, Views, Indexes, Packages, Procedures,
Triggers, Types, and so on.
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 more are all displayed in an easy-to-read tabbed page.
If you want to see the definition of the EMPLOYEES table as shown on the slide, perform the
following steps:
1. Expand the connection node in the Connections Navigator.
2. Expand Tables.
3. Double-click EMPLOYEES.
Using the Data tab, you can enter new rows, update data, and commit these changes to the
database.
Oracle Database 10g: SQL Fundamentals I E - 9
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a Schema Object
•

SQL Developer supports the creation of any schema
object by:
– Executing a SQL statement in SQL Worksheet
– Using the context menu

•
•

Edit the objects by using an edit dialog box or one of many
context-sensitive menus.
e
abl
r
View the DDL for adjustments, such
sfe
n
as creating a new object or editing
-tra
an existing schema object.
non

NA

a
as
h
m) ideฺ
o
ilฺc t Gu
a
gm den
@
nct is Stu
a
mh se th
i
ras Copyright © 2009, Oracle. All rights reserved.
u
(na se to
C en
AN liObject
Creating HSchema c
Ma
IDeveloper supports the creation of any schema object by executing a SQL statement in
AS
RSQL

SQL Worksheet. Alternatively, you can create objects using the context menus. Once created,
you can edit the objects using an edit dialog or one of 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 creating 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 for creating and editing
database objects have multiple tabs, each reflecting a logical grouping of properties for that type
of object.

Oracle Database 10g: SQL Fundamentals I E - 10
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a New Table: Example

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C n
AN Table:eExample
lic
Creating HNew
a
IM
In the Create Table dialog box, if you do not select the Advanced check box, you can create a
AS
R
table quickly by specifying columns and some frequently used features.

If you select the Advanced check box, the Create Table dialog box changes to one with multiple
tabs, in which you can specify an extended set of features while creating the table.
The example in the slide shows creating the DEPENDENT 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 New 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 selecting Primary Key in
the dialog box. Sometimes, you may want to edit the table that you have created. To edit a table,
right-click the table in the Connections Navigator and select Edit.

Oracle Database 10g: SQL Fundamentals I E - 11
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using SQL Worksheet
•
•

Use SQL Worksheet to enter and execute SQL, PL/SQL,
and SQL *Plus statements.
Specify any actions that can be processed by the database
connection associated with the worksheet.

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Using SQL Worksheet
IMHconnect to a database, a SQL Worksheet window for that connection is automatically
AS
RWhen you can use SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus
A opened. You
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 any 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 any of the following two options:
• Select Tools > SQL Worksheet.
• Click the Open SQL Worksheet icon.

Oracle Database 10g: SQL Fundamentals I E - 12
SQL Star International Limited

Using SQL Worksheet
4

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

2

1
3

6

5

7

8

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C n
AN lice(continued)
Using SQL Worksheet
IMH to use shortcut keys or icons to perform certain tasks such as executing a SQL
You may
AS
Rstatement,want a script, and viewing the history of SQL statements that you have executed.
A
running
You can use the SQL Worksheet toolbar that contains icons to perform the following tasks:
1. Execute Statement: Executes the statement at the cursor 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. Execute Explain Plan: Generates the execution plan, which you can see by clicking the
Explain tab
7. Autotrace: Generates trace information for the statement, which you can see by clicking
the Autotrace tab
8. Clear: Erases the statement or statements in the Enter SQL Statement box

Oracle Database 10g: SQL Fundamentals I E - 13
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Executing SQL Statements
Use the Enter SQL Statement box to enter single or multiple
SQL statements.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Statements
lic
Executing SQL
H
IM
In SQL Worksheet, you can use the Enter SQL Statement box to enter a single or multiple SQL
AS
R
statements. For a single statement, the semicolon at the end is optional.

When you type in 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, as 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.

Oracle Database 10g: SQL Fundamentals I E - 14
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Viewing the Execution Plan

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C n
AN licePlan
Viewing the Execution
IMH
You can execute a SQL script
AS
Rperform the following steps: and view the execution plan. To execute a SQL script file,
A
1. From the File menu, Select Open.
2. In the Open dialog box, double-click the .sql file.
3. Click the Run Script icon.
When you double-click the .sql file, the SQL statements are loaded into the Enter SQL
Statement box. You can execute the script or each line individually. The results are displayed in
the Script Output area.
The example in the slide shows the execution plan. The Execute Explain Plan icon generates the
execution plan. An execution plan is the sequence of operations that are performed to execute
the statement. You can see the execution plan by clicking the Explain tab.

Oracle Database 10g: SQL Fundamentals I E - 15
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Formatting the SQL Code

Before
Formatting

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
After
ailฺ nt
m
Formatting
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
ANSQLicen
l Code
Formatting the
IMH to beautify the indentation, spacing, capitalization, and line separation of the
AS
RYou may want
SQL code. SQL Developer has the feature of formatting the SQL code.

To format the SQL code, right-click in the statement area, and select Format.
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.

Oracle Database 10g: SQL Fundamentals I E - 16
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using Snippets
Snippets are code fragments that may be just syntax or
examples.

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Using Snippets
IMH to use certain code fragments when you are using the SQL Worksheet or creating
AS
RYou may want
A or editing 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 and drop snippets into the editor window.
To display Snippets, select View > Snippets.
The Snippets window is displayed on the right. 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.

Oracle Database 10g: SQL Fundamentals I E - 17
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using Snippets: Example

Inserting a
snippet

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C en
AN Example
Using Snippets: lic
IMHsnippet into your code in SQL Worksheet or in a PL/SQL function or procedure, drag
ToS
A
Rthe insert a from the Snippets window to the desired place in your code. Then, you can edit the
A
snippet
Editing the
snippet

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 such as in the following:
SELECT CONCAT(first_name, last_name)
FROM employees;

Oracle Database 10g: SQL Fundamentals I E - 18
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Using SQL*Plus
•
•

SQL Worksheet does not support all SQL*Plus statements.
SQL*Plus statements that are not supported by SQL
Worksheet are:
–
–
–
–
–
–

append
archive
attribute
break
change
clear

e

l
rab
fe

s

n
-tra
n

N

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Using SQL*Plus
MH
IWorksheet supports some SQL*Plus statements. SQL*Plus statements must be interpreted
AS
RSQL SQL Worksheet before being passed to the database; any SQL*Plus statements that are
A by the
not supported by the SQL Worksheet are ignored and not passed to the database. For example,
some of the SQL*Plus statements that are not supported by SQL Worksheet are listed in the
slide. For the complete list of SQL*Plus statements that are supported and not supported by SQL
Worksheet, refer to SQL Developer online Help.

Oracle Database 10g: SQL Fundamentals I E - 19
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Database Reporting
•
•
•

SQL Developer provides you with a number of predefined
reports about your database and objects.
The Reports are organized into categories.
You can create your own customized reports too.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
DatabaseH
M Reporting
IDeveloper provides many reports about the database and its objects. These reports are
AS
RSQL

grouped into the following categories:
• About Your Database reports
• Object reports
• Application Express reports
• Charts
• Database Administration reports
• Data Dictionary reports
• Jobs reports
• PL/SQL reports
• Security reports
• Streams reports
• Table reports
• XML reports
To display a report, click the Reports tabbed page and then select the report type. You can also
create your own user-defined reports.

Oracle Database 10g: SQL Fundamentals I E - 20
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

Creating a User-Defined Report
Create and save user-defined reports for repeated use.

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licenReport
Creating HUser-Defined
a
IM reports are any reports that are created by SQL Developer users. To create a userAS
RUser-defined

defined report, 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.

Oracle Database 10g: SQL Fundamentals I E - 21
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

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

e

l
rab
fe

s

n
-tra
n

NA

o
an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s u
ara Copyright © 2009, Oracle. All rights reserved.
(n se to
C
AN licen
Summary
MH
IDeveloper is a free graphical tool to simplify database development tasks. Using SQL
AS
RSQL

Developer, you can browse, create, and edit database objects. You can use SQL Worksheet to
run SQL statements and scripts. SQL Developer enables you to create and save your own special
set of reports for repeated use.

Oracle Database 10g: SQL Fundamentals I E - 22
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

Index
e

s

l
rab
fe

o

n
-tra
n

NA

S
RA

IM

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
HA
SQL Star International Limited

Note: A bolded number or letter refers to an entire lesson or appendix.

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

A
Adding Data Through a View 10-15
ADD_MONTHS Function 3-22, 3-23, 3-46, 3-60
Advanced Features of the SELECT Statement 6-2
Alias 1-4, 1-8, 1-14, 1-15, 1-16, 1-17, 1-25, 1-37, 1-40, 2-7,
2-20, 2-21, 2-31, 3-46, 4-12, 5-8, 5-11, 5-12, 5-20, 5-29, 7-17,
7-21, 9-33, 10-7, 10-9, 10-11, 11-22, C-11, C-12, C-15, C-20, C-21
ALL Operator 6-16, 7-11, 7-12, 7-18, 7-22
ALL_COL_COMMENTS Dictionary View 11-19
ALL_OBJECTS Dictionary View 11-5, 11-7
ALL_TAB_COMMENTS Dictionary View 11-19
ALTER SEQUENCE Statement 10-30, 10-31
ALTER TABLE Statement 9-34, 10-27

AS Keyword 1-14, 1-15, 1-16
AS Subquery 9-32, 10-7
Attributes i-18, i-19, i-20
AUTOCOMMIT Command 8-29
AVG Function 4-13
B
BETWEEN Range Condition 2-9

Oracle Database 10g: SQL Fundamentals I Index -2

s

n
-tra
n

o
an
has ฺ
)
comGuide
American National Standards Institute (ANSI) i-12, i-25,ti-28, i-30, 3-26, 3-54,
ailฺ n
m
5-4, 8-27, D-4
@g tude
ct
S
Ampersand Substitution 2-2, 2-24,n
a 2-25, 2-28, 2-31, 2-32, 3-11
h
his
t
m
Double-ampersand (&&) 2-23, 2-28
asi use
r
ANY Operator 6-15 a
(n se to
C
Arguments Function 3-3, 3-5, 3-15, 3-50
AN licen
Arithmetic Expressions 1-9, 1-13, 1-16, 2-4
IMH
AS
Arithmetic Operators 1-9, 1-10, 3-20, 3-21, 3-60

R

NA

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

C
Calculations 1-9, 1-14, 1-38, 3-3, 3-14, 3-20, 3-25, 3-60, 3-61, 4-26, D-5
Cardinality i-20
Cartesian Product 5-2, 5-5, 5-26, 5-27, 5-28, 5-29, C-4, C-5, C-21
CASE Expression 3-51, 3-54, 3-55, 3-56, 3-57, 3-60
Case-manipulation Functions 3-7, 3-9, 3-10
CAT View 11-8
Character strings 1-16, 1-17, 1-18, 2-6, 2-15, 3-9, 3-11, 3-35, 3-38
Character-manipulation Functions 3-7, 3-11, 3-12
CHECK Constraint 8-7, 9-28, 10-21, 11-12, 11-13
COALESCE Function 3-52, 3-53, 4-5
Column Alias 1-8, 1-14, 1-15, 1-17, 1-37, 2-21, 3-46, 4-12, 5-11,

R

11-20, 11-22, E-9
Conversion Functions 3-2, 3-6, 3-9, 3-26, 3-31, 3-60, 7-19
COUNT Function 4-8
CREATE INDEX Statement 10-36
CREATE PUBLIC SYNONYM Statement 10-41
CREATE SEQUENCE Statement 10-24
CREATE SYNONYM Statement 10-39, 10-40, 10-41
CREATE TABLE Statement 8-11, 9-5, 9-32, 9-36, 9-37

Creating a Database Connection 1-24, 1-25, 1-26, E-7, E-8
Creating a User-Defined Report E-21
Cross Joins 5-4, 5-28, 5-29
CURRVAL 9-7, 9-28, 10-26, 10-27, 10-28
CYCLE Option (with Sequences) 10-25, 10-30

Oracle Database 10g: SQL Fundamentals I Index -3

s

n
-tra
n

o
an
has ฺ
)
comGuide
ailฺ nt
m
Composite Unique Key 9-22, 9-23
@g 3-38,de 3-60-61, 8-41, C-7, E-18
t
CONCAT Function 1-16, 1-18, 1-42, 3-11-12, Stu 3-46,
anc this
Concatenation Operator 1-16 h
m
asi use
r t
Conditional Processing 3-54 o
(na9-19, 11-13
CONSTRAINT_TYPE se
C en
AN i-9, i-30, 1-12, 1-27, 8-7, 8-17, 8-21, 9-2, 9-10,
CONSTRAINTS lic
H
IM9-17-23, 9-26, 9-28, 9-30-32, 9-35, 9-36, 10-16, 10-38, 11-11-14,
AS
5-12, 9-33, 10-9, 10-11, C-11, C-12
COMMENT Statement 11-19
COMMENTS Column 11-6, 11-19
COMMIT Statement 8-29, 8-32, 8-33

NA

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

D
Data from More Than One Table 5-2, 5-3, 5-5, C-2, C-3, C-7
Data Structures i-9, i-14, i-17, 9-3
Data Types i-6, i-9, 1-9, 1-35, 1-36, 3-3, 3-25, 3-26, 3-48,
3-50, 3-60, 3-61, 4-5, 4-7, 5-6, 5-8, 7-8, 7-13, 7-15, 8-7,
8-11, 9-2, 9-9-12, 9-14, 9-36, 11-10-12, D-7, D-8
Data Warehouse Applications i-9
Database I, 1-2, 1-3, 1-22-29, 1-34, 1-37, 1-39, 2-2, 2-6, 3-10, 3-17-20, 3-26,
4-13, 4-16, 5-29, 6-7, 8-3, 8-13, 8-18, 8-24, 8-25, 8-29, 8-31, 8-32,
8-37, 8-38, 8-39, 9-2-6, 9-13, 9-18, 9-33-37, 10-3, 10-16, 10-20, 10-22,
10-23, 10-33, 10-34, 10-39, 10-41, 10-42, 11-3-12, 11-17-19, B-3,
C-6, C-7, C-9, C-21, D-3-6, D-15, E

o

A

R
NA

DDL Statement 8-11, 8-24, 8-25, 8-29, 8-36, 9-1, 9-5, 9-8, 9-35
DECODE Function 3-54, 3-56, 3-57, 3-58, 3-59, 3-60, 3-67
Default Date Display 2-6, 3-17
DEFAULT Option 9-7, 10-24, 10-25
Default Sort Order 2-21, 4-16
DELETE Statement 8-18, 8-19, 8-20, 8-21, 8-37, 8-39
DESC Keyword 2-21
DESCRIBE Command 1-35, 1-36, 8-7, 9-8, 9-33, 10-8, 10-12, 11-11, D-7
Dictionary Views i-3, 11-1, 11-2, 11-3, 11-6, 11-19, 11-20, 11-21

Oracle Database 10g: SQL Fundamentals I Index -4

s

n
-tra
n

Database Structures 9-5
Date i-3, i-9, i-13, i-14, i-18, i-28, 1-8, 1-9, 1-17, 1-27, 1-40, 1-42, 2-6, 2-7, 2-10,
2-11, 2-20, 2-21, 2-23, 2-26, 2-33, 2-34, 3-2-6, 3-14-27, 3-32-37, 3-41-48,
3-60-65, 4-5, 4-7, 4-24, 5-35, 6-21, 7-4, 7-6, 7-19, 8-2, 8-3, 8-6, 8-8, 8-9,
8-12-16, 8-22, 8-23, 8-27, 8-28, 8-33, 8-37-42, 9-7-17, 9-23, 9-26-30, 9-33,
10-6, 10-7, 10-16, 10-17, 10-27, 10-37, 11-4, 11-7, 11-8, 11-15, C-27, E-9
DATE Data Type 3-6, 3-18, 3-22, 3-25, 3-61, 4-7, 7-19, 9-12

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
Datetime Data Typeara 9-12, u
9-11, o 9-14
n
t
DBA_OBJECTS 11-5 se
C ( en
N lic
DBMS i-2, i-13, i-14, i-21, i-23, i-26, i-27, i-30
HA
SIMStatement 8-25, 8-29, 9-5
DCL

e

l
rab
fe
SQL Star International Limited

D

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

DISTINCT Keyword 1-20, 4-9, 7-11, 10-13, 10-14, 10-15, 10-27
DML Operations on Data Through a View 10-13
Double-ampersand 2-23, 2-28
DROP ANY INDEX Privilege 10-38
DROP ANY VIEW Privilege 10-20
DROP INDEX Statement 10-38
DROP SYNONYM Statement 10-41
DROP TABLE Statement 9-35
DROP VIEW Statement 10-20
DUAL Table 3-14, 3-19

e

s

n
-tra
n

Duplicate Rows i-23, 1-20, 4-8, 7-8, 7-11, 7-12, 7-18, 7-22

o

an
E
has ฺ
)
Entity Relationship i-17, i-19, i-20
comGuide
Equijoins 5-2, 5-9, 5-19, 5-20, 5-29, C-2, C-8, C-9, C-14, C-15, C-21
ailฺ nt
m
ESCAPE Option 2-12
@g tude
ct D-15,
Execute SQL 1-2, 1-28, 1-37, D-2,n
a D-5,his SE-2, E-12, E-22
imh se t
Execution Plan 1-29, E-13, E-15
s u
ara to3-26, 3-29, 3-30, 3-31
Explicit Data Typen
Conversion
C ( ense
N lic
HA
F IM
AS

R

NA

Foreign Key i-21, i-22, i-24, 5-9, 8-7, 9-17, 9-25, 9-26, 9-27,
9-31, 10-35, 11-12, 11-13, C-7, C-8
Format Model 3-22, 3-24, 3-32, 3-33, 3-35, 3-37, 3-40, 3-41
FROM Clause 1-4, 1-9, 2-4, 3-14, 4-13, 4-16, 5-12, 6-4, C-9, C-12, C-20
FULL OUTER Join 5-5, 5-22, 5-25
Functions i-3, i-7, i-10, 1-23, 2-4, 2-6, 3-1-15, 3-22-26, 3-29, 3-31, 3-41, 3-42,
3-45, 3-46, 3-47, 3-60, 3-61, 4-1-7, 4-10-13, 4-17, 4-18, 4-20, 4-23-26,
6-10, 6-19, 7-19, 8-8, 9-7, 9-28, 10-6, 10-12-15, 11-3, 11-8, E-6, E-17, E-18
fx Modifier 3-41, 3-42

Oracle Database 10g: SQL Fundamentals I Index -5

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

G
Generate Unique Numbers 10-3, 10-23
GROUP BY Clause 4-2, 4-11, 4-12, 4-13, 4-14, 4-16, 4-17, 4-20,
4-21, 4-24, 6-12, 10-13, 10-14, 10-15
GROUP BY Column 4-14, 4-16
Group Functions 3-4, 4-1-13, 4-17, 4-18, 4-20, 4-23-26, 6-10, 6-19, 10-12-15
Group Functions in a Subquery 6-10

H

e

l
rab
fe

HAVING Clause 4-2, 4-18-25, 6-4, 6-11, 6-19

s

I

R

NA

o

an
has ฺ
)
comGuide
ailฺ nt
5-26, 5-27, 10-37, C-2, C-4-7, C-13, C-14, C-16, C-17
m
@g 10-3, de 10-34-38,
Index 1-27, 9-3, 9-6, 9-23, 9-24, 9-35,t10-2, tu 10-33,
anc this S
h11-7, 11-8, E-5, E-9
10-42, 10-43, 10-46, 11-3,
m
asi use
INSERT Statement 8-5, 8-11, 8-22, 8-23, 8-41, 9-8, 9-19, 10-27, 10-28
ar
(ni-30,s8-7,to 9-17, 9-19, 9-22, 9-30,
e 8-21,
Integrity Constraint
N C l10-16, 11-3
en
9-31, 9-32, ic
HA
IM
International Standards Organization (ISO) i-28
AS
IF-THEN-ELSE Logic 3-54, 3-55, 3-57, 3-60
Implicit Data Type Conversion 3-26, 3-27, 3-28
IN Condition 2-7, 2-10, 5-2, 5-4, 5-13, 5-18, 5-19, 5-21, 5-22,

INTERSECT Operator 7-3, 7-13, 7-14, 7-22
INTERVAL YEAR TO MONTH 9-11, 9-14, 9-15
IS NOT NULL Condition 2-13
IS NULL Condition 2-13

J
Java i-4, i-7, i-10, i-27, E-4
Joining Tables 5-5, 5-22, 5-30, C-7

K
Keywords 1-4, 1-7, 1-31, 1-32, 5-6, 9-26, 9-27, D-4, E-14, E-16

Oracle Database 10g: SQL Fundamentals I Index -6

n
-tra
n
SQL Star International Limited

L

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

LEFT OUTER Join 5-23
LIKE Condition 2-11, 2-12
Literal 1-17, 1-18, 1-19, 2-4, 2-11, 2-12, 3-11, 3-35, 3-51,
3-55, 7-20, 9-7
Logical Condition 2-14
Logical Subsets 10-4

M
MAX Function 4-6, 4-7
MIN Function 4-7
MINUS Operator 7-15, 7-16, 7-17, 7-22, 7-23
MOD Function 3-16

s

Nested SELECT 6-4, 6-20
NEXTVAL 9-7, 9-28, 10-26, 10-27, 10-28
NEXTVAL and CURRVAL Pseudocolumns 10-26, 10-27

Nonunique Index 10-35, 10-43, 10-46
NOT NULL Constraint 1-35, 9-19, 9-21, 9-22, 9-32, 11-10
NOT Operator 2-17, 2-31, 6-16
NULL Conditions 2-13, 2-31
Null Value i-24, 1-12, 1-13, 1-16, 2-13, 2-21, 3-47-51, 3-57, 4-5, 4-8-10,
6-13, 6-17, 7-8, 7-13, 8-7, 9-7, 9-21, 9-24, 10-37
NULLIF Function 3-51
NUMBER Data Type 3-38, 7-19, 8-6
Number Functions 3-6, 3-13
NVL Function 3-48, 3-49, 3-52, 3-60, 4-10
NVL2 Function 3-50
Oracle Database 10g: SQL Fundamentals I Index -7

n
-tra
n

o

an
Modifier 3-41, 3-42
has ฺ
)
MONTHS_BETWEEN Function 3-6
comGuide
Multiple-column Subqueries 6-7
ailฺ nt
m
Multiple-row Functions 3-4
@g tude
t
Multiple-row Subqueries 6-2, 6-6, 6-7, 6-14, 6-15, 6-16
anc this S
imh se
s
ara to u
n
N
C ( ense
NamingAN 9-4,c
H 1-33, li 9-18, 11-5
IM
Nested Functions 3-45, 3-61
AS

R

NA

e

l
rab
fe
Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

SQL Star International Limited

O
Object Relational i-2, i-9, i-13, i-30
Object Relational Database Management System i-2, i-30
Object-oriented Programming i-9
OLTP i-9
ON clause 5-5, 5-13-18, 5-22, 7-12, 10-16, 10-17
ON DELETE CASCADE 9-27
ON DELETE SET NULL 9-27
Online Transaction Processing i-9
OR REPLACE Option 10-8, 10-11

e

Oracle Application Server 10g i-5, i-7, i-30
Oracle Database 10g i-3, i-5, i-6, i-27, i-30, 6-7, 9-34
Oracle Enterprise Manager 10g Grid Control i-5, i-8, i-30
Oracle Instance i-27
ORDBMS i-2
Order i-18, i-23, 1-6, 1-11, 2-2, 2-18, 2-20, 2-21, 2-23, 2-27,
2-28, 2-31-34, 3-5, 3-46, 3-53, 3-63, 3-65, 3-66,
4-5, 4-12, 4-14, 4-16, 4-20, 4-22, 4-24, 4-27, 5-33, 6-6, 6-21,
7-2, 7-3, 7-8, 7-10, 7-12, 7-13, 7-17, 7-18, 7-21, 7-22, 7-24,
8-6, 9-10, 9-13, 10-11, 10-27, 11-8, 11-16, C-11, C-25
ORDER BY Clause 2-20, 2-21, 2-23, 2-31, 2-32, 3-5, 4-14, 4-24,

Order of Rows i-23, 2-20, 7-2, 7-21
Outer Query 6-3, 6-4, 6-5, 6-9, 6-10, 6-12, 6-13, 6-20

P
PRIMARY KEY Constraint 9-20, 9-24
Projection 1-3

Oracle Database 10g: SQL Fundamentals I Index -8

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
imh se
s
ara to u
n
C ( ense
N lic
6-6, 7-17, 7-21, 7-22, 9-10, 10-27, C-11
HA
SIM of Precedence 1-11, 2-18
Order

A

R
NA

s

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

R
RDBMS i-2, i-14, i-21, i-23, i-26, i-27, i-30
Read Consistency 8-31, 8-37, 8-38
READ ONLY Option 10-18
Read-only Constraint 10-19
REFERENCES 1-23, 1-27, 1-34, 8-29, 9-25-29, 11-13, E-6, E-9
Referential Integrity Constraint 8-21
Relational Database i
Relational Database Management System i-2, i-14, i-27, i-30
Restrict the Rows 1-3, 2-2, 2-4, 4-19, C-10
Retrieve Data from a View 10-10
Return a Value 3-3, 3-6, 3-14, 3-22
RIGHT OUTER Join 5-24
ROLLBACK Statement 8-2, 8-25-27, 8-29, 8-31, 8-34, 8-36, 8-39
ROUND and TRUNC Functions 3-24
ROUND Function 3-14, 3-15

e

s

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
RR Date Format 3-43, 3-44
@g tude
t
Rules of Precedence 1-10, 1-11, 2-18, 2-19 S
anc this
imh se
s
ara to u
n
S
C ( ense
SAVEPOINT Statement 8-28
N lic
HA
Schema 1-22-27, 9-2, 9-5, 9-6, 9-19, 9-29, 9-36, 10-1, 10-34, 10-40,
SIM11-2-4, 11-7, 11-21-23, B-3, E-3, E-7, E-9, E-10
RA

NA

SELECT Statement i-3, 1-1-6, 1-17, 1-18, 1-37, 1-39, 2-5, 2-8, 2-9, 2-11,
2-19, 2-20, 2-23, 2-27, 2-29, 2-31, 2-32, 3-2, 3-10, 4-8, 4-13-18,
5-2, 5-12, 6-2-9, 6-19, 6-20, 7-8, 7-13-20, 8-19, 8-31, 8-37, 8-38, 9-32,
10-4, 10-7, 10-12, 10-27, 11-6, 11-15, C-2, C-7, C-12, D-2
Selection 1-3, 2-3
Sequences 2-21, 9-6, 10-2, 10-3, 10-22, 10-23, 10-29, 10-38, 10-42,
10-43, 11-3, 11-16, 11-17, 11-20, 11-23
Set operators 7-1, 7-2, 7-3, 7-17, 7-18, 7-23, 7-24
SET VERIFY ON 2-30
Sets of Rows 4-3
SGA i-27

Oracle Database 10g: SQL Fundamentals I Index -9

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

S
Single-row Functions 2-6, 3-1, 3-4, 3-5, 3-6, 3-45, 3-60, 4-3
Single-row Operator 6-4, 6-6, 6-8, 6-12, 6-14, 6-19
Single-row Subqueries 6-2, 6-6, 6-7, 6-8, 6-9
SOME Operator 6-15
Sorted i-3, 2-35, 7-8, 7-10, 7-11, 7-18, 7-21, 7-22
Sorting 2-1, 2-21, 2-31, 2-32
SQL Developer i-2, 1-2, 1-7, 1-8, 1-14, 1-20, 1-21, 1-22,
1-23, 1-24, 1-25, 1-27, 1-28, 1-32, 1-34, 1-35, 1-37, 1-38, 1-39,
1-42, 2-22-30, 8-25, 8-29, 8-30, E
Statement-level Rollback 8-36
Structured Query Language i-25, i-26, 1-2
Sub-SELECT 6-4
Subqueries in UPDATE statements 8-16

System Development Life Cycle i-11, i-12, i-17
System Failure 8-24, 8-29, 8-30
System Global Area i-27

Oracle Database 10g: SQL Fundamentals I Index -10

s

n
-tra
n

o
an
has ฺ
)
Subqueries to Delete Rows 8-20
om 9-32, e
c9-10,Guid9-33, 9-36,
Subquery 6-3-19, 8-11, 8-13, 8-15, 8-20, 8-22, 8-23,
ailฺ nt
m e
10-7, 10-8, 10-9, 10-11, 10-27
d
@g 2-30-32, 8-10, E-13
Substitution Variables 2-22, 2-23, nct 2-27, tu
2-26,
S
a
s
SUM Function 4-6, 4-16
mh se thi
i
ras t 4-16
Summary Results for Groupso u
(na se 9-3, 9-6, 9-35, 10-2, 10-3, 10-39, 10-40-43,
Synonym i-19, i-20, 1-35, 6-15,
C
AN11-3,icen 11-9, 11-18, 11-20, 11-21, 11-22, D-7
l 11-8,
10-46,
IMH Function 3-18, 3-19, 8-8
SYSDATE
AS

R

NA

e

l
rab
fe
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

T
Table Alias 5-12, 5-20, 5-29, C-12, C-15, C-21
Table Prefixes 5-11, C-11, C-12
Three-way Join 5-18
TO_CHAR Function 3-32, 3-37, 3-38, 3-39, 3-40
TO_NUMBER or TO_DATE Functions 3-41
Transactions 8-2, 8-24, 8-25, 8-27, 8-36, 8-40, 9-35
TRUNC Function 3-15, 3-24
Tuple i-23
Types of Indexes 10-35

e

s

l
rab
fe

U

R

NA

o

an
has ฺ
)
comGuide
ailฺ nt
m
Unique Identifier i-19, i-20
@g tude
ct
S
Unique Index 9-23, 9-24, 10-35, an
10-37, 10-43, 10-46
h
his
t
m
UNIQUE Key Integrity Constraint se
asi u 9-22
r
UPDATE Statement 8-13, 8-14, 8-15, 8-16, 10-27
(na se to
C
UPPER Function 3-10 n
AN lice
USER_CONS_COLUMNS Dictionary View 11-14
IMH
AS
USER_SYNONYMS Dictionary View 11-18
UNION ALL Operator 7-11, 7-12, 7-18, 7-22
UNION Clause 7-12
UNION Operator 7-8, 7-9, 7-10, 7-19, 7-20, 7-21, 7-22, 7-23
UNIQUE Constraint 9-22, 9-23, 10-33, 10-35, 10-37, 11-13

USING Clause 5-4, 5-8, 5-9, 5-10, 5-11, C-6
Using Snippets E-17, E-18
Using SQL Worksheet E-12, E-13

Oracle Database 10g: SQL Fundamentals I Index -11

n
-tra
n
SQL Star International Limited

Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates.

V
VALUES Clause 8-5, 8-7, 8-11, 8-22, 10-27
VARIANCE 4-4, 4-7, 4-24
VERIFY Command 2-30
Views i-3, i-8, 1-27, 9-6, 9-35, 10-2, 10-3, 10-4, 10-5, 10-6,
10-13, 10-16, 10-20, 10-21, 10-38, 10-40, 10-42, 11-1, 11-2, 11-3, 11-4,
11-5, 11-6, 11-7, 11-8, 11-15, 11-19, 11-20, 11-21, 11-23, E-9
W
When to Create an Index 10-37
WHERE Clause 2-3, 2-4, 2-5, 2-6, 2-7, 2-8, 2-10, 2-14, 2-22,
2-23, 2-26, 2-27, 2-31, 2-32, 3-10, 4-8, 4-12, 4-13, 4-18, 4-19,
4-24, 4-26, 5-7, 5-8, 5-13, 5-17, 5-29, 6-2, 6-4, 6-11, 6-12,
6-13, 6-18, 7-17, 8-14, 8-19, 10-37, 11-4, C-4, C-7, C-9, C-10,
C-11, C-17, C-20, C-21
Wildcard Search 2-11
WITH CHECK OPTION 10-7, 10-8, 10-16, 10-17, 11-13

e

s

Oracle Database 10g: SQL Fundamentals I Index -12

n
-tra
n

o

an
has ฺ
)
comGuide
ailฺ nt
m
@g tude
t
anc this S
X
imh se E-20, E-21
XML i-4, i-6, i-27, 1-24,as E-7, E-8,
ar 1-25,o u
n
t
C ( ense
N lic
HA
IM
AS
R

NA

l
rab
fe

More Related Content

PPT
Intro to SQL
PDF
Pl sql student guide v 4
PDF
Pl sql student guide v 3
PDF
Plsql 9i vol2
PDF
Pl lab solution
PPT
Les05 (Displaying Data from Multiple Table)
PDF
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
PPT
The Smartpath Information Systems | BASIC RDBMS CONCEPTS
Intro to SQL
Pl sql student guide v 4
Pl sql student guide v 3
Plsql 9i vol2
Pl lab solution
Les05 (Displaying Data from Multiple Table)
SQL – The Natural Language for Analysis - Oracle - Whitepaper - 2431343
The Smartpath Information Systems | BASIC RDBMS CONCEPTS

Similar to sql training (20)

PDF
Sql1 vol2
PDF
SQL.pdf
PDF
PDF
Oracle database 12c sql worshop 1 student guide vol 2
PDF
Introduction to oracle 9i pl sql - part 2
PDF
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
PDF
Pl sql student guide v 1
PDF
Oracle database 12c sql worshop 2 student guide vol 1
PDF
D80194GC20_sg1.pdf
PDF
Oracle database 12c sql worshop 2 student guide vol 2
PPT
PPT
PDF
Oracle Weblogic 11g admin guide 2
DOC
Oracle 11g
PPT
Toc Sg
PDF
Oracle_Database_11g_SQL_Fundamentals_I_(Vol2)_Oracle_SQL.pdf
PDF
Sql scripting sorcerypaper
PDF
Oracle forms developer 10g vol1
PPT
Oracle Training Tutorial for Beginners
PDF
Oracle Sqlplus Pocket Reference 3rd Ed Jonathan Gennick
Sql1 vol2
SQL.pdf
Oracle database 12c sql worshop 1 student guide vol 2
Introduction to oracle 9i pl sql - part 2
48742447 11g-sql-fundamentals-ii-additional-practices-and-solutions
Pl sql student guide v 1
Oracle database 12c sql worshop 2 student guide vol 1
D80194GC20_sg1.pdf
Oracle database 12c sql worshop 2 student guide vol 2
Oracle Weblogic 11g admin guide 2
Oracle 11g
Toc Sg
Oracle_Database_11g_SQL_Fundamentals_I_(Vol2)_Oracle_SQL.pdf
Sql scripting sorcerypaper
Oracle forms developer 10g vol1
Oracle Training Tutorial for Beginners
Oracle Sqlplus Pocket Reference 3rd Ed Jonathan Gennick
Ad

Recently uploaded (20)

PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PPTX
Introduction to pro and eukaryotes and differences.pptx
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
Empowerment Technology for Senior High School Guide
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
Computer Architecture Input Output Memory.pptx
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
HVAC Specification 2024 according to central public works department
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
Introduction to pro and eukaryotes and differences.pptx
Virtual and Augmented Reality in Current Scenario
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
Paper A Mock Exam 9_ Attempt review.pdf.
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
Empowerment Technology for Senior High School Guide
TNA_Presentation-1-Final(SAVE)) (1).pptx
Computer Architecture Input Output Memory.pptx
Unit 4 Computer Architecture Multicore Processor.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
Share_Module_2_Power_conflict_and_negotiation.pptx
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
Practical Manual AGRO-233 Principles and Practices of Natural Farming
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
HVAC Specification 2024 according to central public works department
Ad

sql training

  • 1. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe n -tra n o an has 10g: SQL Oracle Database ฺ ) comGuide Fundamentals I ailฺ nt gm de @Student Guide • Volume 2 t tu anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA D17108GC30 Edition 3.0 January 2009 D57871
  • 2. SQL Star International Limited Copyright © 2009, Oracle. All rights reserved. Salome Clement Chaitanya Koratamaddi Nancy Greenberg Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Authors Disclaimer Technical Contributors and Reviewers Wayne Abbott Christian Bauwens Claire Bennett Perry Benson Brian Boxx Zarko Cesljas Dairy Chan Laszlo Czinkoczki Joel Goodman Matthew Gregory Sushma Jagannath Yash Jain Angelika Krupp Isabelle Marchand Malika Marghadi Valli Pataballa Narayanan Radhakrishnan Bryan Roberts Helen Robertson Lata Shivaprasad John Soltani James Spiller Priya Vennapusa 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 s Arijit Ghosh Raj Kumar Graphic Designer Rajiv Chandrabhanu Publisher Giri Venugopal n -tra n U.S. GOVERNMENT RIGHTS The U.S. Government’s 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. o Trademark Notice Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. e l rab fe 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: an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM ASEditors R NA This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way. Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display, perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization of Oracle.
  • 3. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Contents Preface I Introduction Lesson Objectives I-2 Goals of the Course I-3 Oracle10g I-4 Oracle Database 10g I-6 Oracle Application Server 10g I-7 Oracle Enterprise Manager 10g Grid Control I-8 Relational and Object Relational Database Management Systems I-9 Oracle Internet Platform I-10 System Development Life Cycle I-11 Data Storage on Different Media I-13 Relational Database Concept I-14 Definition of a Relational Database I-15 Data Models I-16 Entity Relationship Model I-17 Entity Relationship Modeling Conventions I-19 Relating Multiple Tables I-21 Relational Database Terminology I-23 Relational Database Properties I-25 Communicating with an RDBMS Using SQL I-26 Oracle’s Relational Database Management System I-27 SQL Statements I-28 Tables Used in the Course I-29 Summary I-30 IM S RA NA 1 Retrieving Data Using the SQL SELECT Statement Objectives 1-2 Capabilities of SQL SELECT Statements 1-3 Basic SELECT Statement 1-4 Selecting All Columns 1-5 Selecting Specific Columns 1-6 Writing SQL Statements 1-7 Column Heading Defaults 1-8 iii s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA e l rab fe
  • 4. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited 2 e Restricting and Sorting Data Objectives 2-2 Limiting Rows Using a Selection 2-3 Limiting the Rows That Are Selected 2-4 Using the WHERE Clause 2-5 Character Strings and Dates 2-6 Comparison Conditions 2-7 Using Comparison Conditions 2-8 Using the BETWEEN Condition 2-9 Using the IN Condition 2-10 Using the LIKE Condition 2-11 Using the NULL Conditions 2-13 Logical Conditions 2-14 iv l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Arithmetic Expressions 1-9 Using Arithmetic Operators 1-10 Operator Precedence 1-11 Defining a Null Value 1-12 Null Values in Arithmetic Expressions 1-13 Defining a Column Alias 1-14 Using Column Aliases 1-15 Concatenation Operator 1-16 Literal Character Strings 1-17 Using Literal Character Strings 1-18 Alternative Quote (q) Operator 1-19 Duplicate Rows 1-20 Development Environments for SQL 1-21 What Is Oracle SQL Developer? 1-22 Oracle SQL Developer Interface 1-23 Creating a Database Connection 1-24 Browsing Database Objects 1-27 Using the SQL Worksheet 1-28 Executing SQL Statements 1-31 Formatting the SQL Code 1-32 Saving SQL Statements 1-33 Running Script Files 1-34 Displaying the Table Structure 1-35 Using the DESCRIBE Command 1-36 Summary 1-37 Practice 1: Overview 1-38
  • 5. SQL Star International Limited Using the AND Operator 2-15 Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the OR Operator 2-16 Using the NOT Operator 2-17 Rules of Precedence 2-18 Using the ORDER BY Clause 2-20 Sorting 2-21 Substitution Variables 2-22 Using the & Substitution Variable 2-24 Character and Date Values with Substitution Variables 2-26 Specifying Column Names, Expressions, and Text 2-27 Using the && Substitution Variable 2-28 e Using the DEFINE Command 2-29 s Using the VERIFY Command 2-30 Summary 2-31 Practice 2: Overview 2-32 N n -tra n o an has ฺ ) e 3 Using Single-Row Functions to Customizecom Output ilฺ t Guid a Objectives 3-2 gm den SQL Functions 3-3 @ n t is Stu Two Types of SQL Functionsc 3-4 a Single-Row Functions 3-5 mh se th i ras to u Character Functions 3-7 (na se Case-Manipulation Functions 3-9 N C licen AUsing Case-Manipulation Functions 3-10 IMH Character-Manipulation Functions 3-11 S A AR l rab fe Using the Character-Manipulation Functions 3-12 Number Functions 3-13 Using the ROUND Function 3-14 Using the TRUNC Function 3-15 Using the MOD Function 3-16 Working with Dates 3-17 Arithmetic with Dates 3-20 Using Arithmetic Operators with Dates 3-21 Date Functions 3-22 Using Date Functions 3-23 Practice 3: Overview of Part 1 3-25 Conversion Functions 3-26 Implicit Data Type Conversion 3-27 Explicit Data Type Conversion 3-29 Using the TO_CHAR Function with Dates 3-32 v
  • 6. SQL Star International Limited Elements of the Date Format Model 3-33 Using the TO_CHAR Function with Dates 3-37 Using the TO_CHAR Function with Numbers 3-38 Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the TO_NUMBER and TO_DATE Functions 3-41 RR Date Format 3-43 RR Date Format: Example 3-44 Nesting Functions 3-45 General Functions 3-47 NVL Function 3-48 Using the NVL Function 3-49 e l rab fe Using the NVL2 Function 3-50 Using the NULLIF Function 3-51 s Using the COALESCE Function 3-52 Conditional Expressions 3-54 CASE Expression 3-55 an has ฺ Using the CASE Expression 3-56 ) DECODE Function 3-57 comGuide ailฺ nt Using the DECODE Function 3-58 m @g tude Summary 3-60 t anc this S Practice 3: Overview of Part 2 h3-61 m asi use r 4 Reporting Aggregated Data Using the Group Functions (na se to Objectives C 4-2 ANGroupicen l Functions? 4-3 What Are IMH of Group Functions 4-4 S Types A R NA o n -tra n Group Functions: Syntax 4-5 Using the AVG and SUM Functions 4-6 Using the MIN and MAX Functions 4-7 Using the COUNT Function 4-8 Using the DISTINCT Keyword 4-9 Group Functions and Null Values 4-10 Creating Groups of Data 4-11 Creating Groups of Data: GROUP BY Clause Syntax 4-12 Using the GROUP BY Clause 4-13 Grouping by More Than One Column 4-15 Using the GROUP BY Clause on Multiple Columns 4-16 Illegal Queries Using Group Functions 4-17 Restricting Group Results 4-19 Restricting Group Results with the HAVING Clause 4-20 vi
  • 7. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the HAVING Clause 4-21 Nesting Group Functions 4-23 Summary 4-24 Practice 4: Overview 4-25 5 Displaying Data from Multiple Tables Objectives 5-2 Obtaining Data from Multiple Tables 5-3 Types of Joins 5-4 Joining Tables Using SQL:1999 Syntax 5-5 Creating Natural Joins 5-6 Retrieving Records with Natural Joins 5-7 Creating Joins with the USING Clause 5-8 Joining Column Names 5-9 Retrieving Records with the USING Clause 5-10 Qualifying Ambiguous Column Names 5-11 Using Table Aliases 5-12 Creating Joins with the ON Clause 5-13 e s NA RA Outer Joins 5-21 INNER Versus OUTER Joins 5-22 LEFT OUTER JOIN 5-23 RIGHT OUTER JOIN 5-24 FULL OUTER JOIN 5-25 Cartesian Products 5-26 Generating a Cartesian Product 5-27 Creating Cross Joins 5-28 Summary 5-29 Practice 5: Overview 5-30 6 Using Subqueries to Solve Queries Objectives 6-2 Using a Subquery to Solve a Problem 6-3 Subquery Syntax 6-4 Using a Subquery 6-5 vii n -tra n o an has ฺ ) comGuide ailฺ nt m Retrieving Records with the ON Clause 5-14 e @g tud t Self-Joins Using the ON Clause 5-15 S anc tohais 5-17 Applying Additional mh Conditions t Join asi Joinsse the ON Clause 5-18 r Creating Three-Way u with (na 5-19 to Nonequijoins se N C licen ARetrieving Records with Nonequijoins 5-20 IMH S l rab fe
  • 8. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Guidelines for Using Subqueries 6-6 Types of Subqueries 6-7 Single-Row Subqueries 6-8 Executing Single-Row Subqueries 6-9 Using Group Functions in a Subquery 6-10 The HAVING Clause with Subqueries 6-11 What Is Wrong with This Statement? 6-12 Will This Statement Return Rows? 6-13 Multiple-Row Subqueries 6-14 Using the ANY Operator in Multiple-Row Subqueries 6-15 Using the ALL Operator in Multiple-Row Subqueries 6-16 Null Values in a Subquery 6-17 Summary 6-19 Practice 6: Overview 6-20 s MINUS Operator 7-15 Set Operator Guidelines 7-17 The Oracle Server and Set Operators 7-18 Matching the SELECT Statements 7-19 Matching the SELECT Statement: Example 7-20 Controlling the Order of Rows 7-21 Summary 7-22 Practice 7: Overview 7-23 8 Manipulating Data Objectives 8-2 Data Manipulation Language 8-3 Adding a New Row to a Table 8-4 INSERT Statement Syntax 8-5 Inserting New Rows 8-6 viii n -tra n o an 7 Using the Set Operators has ฺ ) Objectives 7-2 comGuide Set Operators 7-3 ailฺ nt m Tables Used in This Lesson 7-4 @g tude t UNION Operator 7-8 anc this S Using the UNION Operator mh 7-9 si use UNION ALL Operator a ar 7-11to nALL Operator 7-12 Using the UNION C ( ense N lic INTERSECT Operator 7-13 HA INTERSECT Operator 7-14 Using SIM the A R NA e l rab fe
  • 9. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Inserting Rows with Null Values 8-7 Inserting Special Values 8-8 Inserting Specific Date Values 8-9 Creating a Script 8-10 Copying Rows from Another Table 8-11 Changing Data in a Table 8-12 UPDATE Statement Syntax 8-13 Updating Rows in a Table 8-14 Updating Two Columns with a Subquery 8-15 Updating Rows Based on Another Table 8-16 Removing a Row from a Table 8-17 DELETE Statement 8-18 Deleting Rows from a Table 8-19 Deleting Rows Based on Another Table 8-20 e s IMH S A R NA 9 State of the Data After ROLLBACK 8-34 Statement-Level Rollback 8-36 Read Consistency 8-37 Implementation of Read Consistency 8-38 Summary 8-39 Practice 8: Overview 8-40 Using DDL Statements to Create and Manage Tables Objectives 9-2 Database Objects 9-3 Naming Rules 9-4 CREATE TABLE Statement 9-5 Referencing Another User’s Tables 9-6 DEFAULT Option 9-7 Creating Tables 9-8 Data Types 9-9 ix n -tra n o an Using a Subquery in an INSERT Statement 8-22 has ฺ ) Database Transactions 8-24 comGuide Advantages of COMMIT and ROLLBACK Statements 8-26 ailฺ nt m Controlling Transactions 8-27 @g tude Rolling Back Changes to a nct Marker 8-28 S ha this Implicit Transactionm Processing 8-29 i COMMIT State of the Datas ra Beforeuse or ROLLBACK 8-31 a After o State of (n Data e t COMMIT 8-32 the s N C lic Data ACommittingen 8-33 TRUNCATE Statement 8-21 l rab fe
  • 10. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Datetime Data Types 9-11 Including Constraints 9-17 Constraint Guidelines 9-18 Defining Constraints 9-19 NOT NULL Constraint 9-21 UNIQUE Constraint 9-22 PRIMARY KEY Constraint 9-24 FOREIGN KEY Constraint 9-25 FOREIGN KEY Constraint: Keywords 9-27 CHECK Constraint 9-28 CREATE TABLE: Example 9-29 Violating Constraints 9-30 Creating a Table by Using a Subquery 9-32 ALTER TABLE Statement 9-34 Dropping a Table 9-35 Summary 9-36 Practice 9: Overview 9-37 s Retrieving Data from a View 10-10 Modifying a View 10-11 Creating a Complex View 10-12 Rules for Performing DML Operations on a View 10-13 Using the WITH CHECK OPTION Clause 10-16 Denying DML Operations 10-18 Removing a View 10-20 Practice 10: Overview of Part 1 10-21 Sequences 10-22 CREATE SEQUENCE Statement: Syntax 10-24 Creating a Sequence 10-25 NEXTVAL and CURRVAL Pseudocolumns 10-26 Using a Sequence 10-28 Caching Sequence Values 10-29 Modifying a Sequence 10-30 x n -tra n o an has ฺ ) comGuide ailฺ nt m 10 Creating Other Schema Objects @g tude t Objectives 10-2 anc this S h Database Objects 10-3 im ras to use What Is a View? 10-4 na 10-5 AdvantagesC Views se of ( n Simple Views and e AN lic Complex Views 10-6 IMH a View 10-7 S Creating A R NA e l rab fe
  • 11. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Guidelines for Modifying a Sequence 10-31 Indexes 10-33 How Are Indexes Created? 10-35 Creating an Index 10-36 Index Creation Guidelines 10-37 Removing an Index 10-38 Synonyms 10-39 Creating and Removing Synonyms 10-41 Summary 10-42 Practice 10: Overview of Part 2 10-43 11 Managing Objects with Data Dictionary Views Objectives 11-2 The Data Dictionary 11-3 Data Dictionary Structure 11-4 How to Use the Dictionary Views 11-6 USER_OBJECTS and ALL_OBJECTS Views 11-7 e s A R NA A Adding Comments to a Table 11-19 Summary 11-20 Practice 11: Overview 11-21 Practice Solutions B Table Descriptions and Data C Oracle Join Syntax D Using SQL*Plus E Using SQL Developer Index xi n -tra n o an has ฺ ) comGuide USER_OBJECTS View 11-8 ailฺ nt m Table Information 11-9 @g tude Column Information 11-10 ct S n Constraint Information ha 11-12 this m View Informations11-15use a i r Sequence Information 11-16 (na se to N C li Information 11-18 ASynonymcen IMH S l rab fe
  • 12. SQL Star International Limited Additional Practices Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Additional Practices: Table Descriptions and Data Additional Practices: Solutions e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA xii
  • 13. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Using DDL Statements to Create and Manage Tables e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 14. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Objectives After completing this lesson, you should be able to do the following: • Categorize the main database objects • Review the table structure • List the data types that are available for columns • Create a simple table e abl r • Explain how constraints are created at the time of table sfe n creation -tra non • Describe how schema objects work sa NA ) ha eฺ m ฺco Guid il ma ent g t@ Stud c han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C AN licen Objectives IMH you are introduced to the data definition language (DDL) statements. You are AS RIn this lesson, taught the basics of how to create simple tables, alter them, and remove them. The data types available in DDL are shown, and schema concepts are introduced. Constraints are tied into this lesson. Exception messages that are generated from violating constraints during DML are shown and explained. Oracle Database 10g: SQL Fundamentals I 9 - 2
  • 15. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Database Objects Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries Synonym Gives alternative names to objects e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen DatabaseH Objects IM Database can contain multiple data structures. Each structure should be outlined in AS RAn Oracle the database design so that it can be created during the build stage of database development. • Table: Stores data • View: Subset of data from one or more tables • Sequence: Generates numeric values • Index: Improves the performance of some queries • Synonym: Gives alternative names to objects Oracle Table Structures • Tables can be created at any time, even while users are using the database. • You do not need to specify the size of a table. The size is ultimately defined by the amount of space allocated to the database as a whole. It is important, however, to estimate how much space a table will use over time. • Table structure can be modified online. Note: More database objects are available but are not covered in this course. Oracle Database 10g: SQL Fundamentals I 9 - 3
  • 16. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Naming Rules Table names and column names: • Must begin with a letter • Must be 1–30 characters long • Must contain only A–Z, a–z, 0–9, _, $, and # • Must not duplicate the name of another object owned by the same user e abl r • Must not be an Oracle server–reserved word sfe n a n-tr o N an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Naming Rules IMHdatabase tables and columns according to the standard rules for naming any Oracle AS RYou nameobject: A Database • Table names and column names must begin with a letter and be 1–30 characters long. • Names must contain only the characters A–Z, a–z, 0–9, _ (underscore), $, and # (legal characters, but their use is discouraged). • Names must not duplicate the name of another object owned by the same Oracle server user. • Names must not be an Oracle server–reserved word. Naming Guidelines Use descriptive names for tables and other database objects. Note: Names are case-insensitive. For example, EMPLOYEES is treated as the same name as eMPloyees or eMpLOYEES. For more information, see “Object Names and Qualifiers” in the Oracle Database SQL Reference. Oracle Database 10g: SQL Fundamentals I 9 - 4
  • 17. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. CREATE TABLE Statement • You must have: – The CREATE TABLE privilege – A storage area CREATE TABLE [schema.]table (column datatype [DEFAULT expr][, ...]); • You specify the: – Table name – Column name, column data type, and column size e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Statement CREATE TABLE lic H IM You create tables to store data by executing the SQL CREATE TABLE statement. This AS ARstatement is one of the DDL statements, which are a subset of SQL statements used to create, modify, or remove Oracle Database structures. These statements have an immediate effect on the database, and they also record information in the data dictionary. To create a table, a user must have the CREATE TABLE privilege and a storage area in which to create objects. The database administrator uses data control language statements to grant privileges to users (DCL statements are covered in a later lesson). In the syntax: schema Is the same as the owner’s name table is the name of the table DEFAULT expr Specifies a default value if a value is omitted in the INSERT statement column Is the name of the column datatype Is the column’s data type and length Oracle Database 10g: SQL Fundamentals I 9 - 5
  • 18. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Referencing Another User’s Tables • • Tables belonging to other users are not in the user’s schema. You should use the owner’s name as a prefix to those tables. e l rab fe s n -tra n NA o an has ฺ USERA USERB ) comGuide SELECT * SELECT * ailฺ userA.employees; FROM userB.employees; gmFROMent d @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to N C licUser’s AAnother en Tables Referencing IMH a collection of objects. Schema objects are the logical structures that directly refer AS RA schema is to the data in a database. Schema objects include tables, views, synonyms, sequences, stored procedures, indexes, clusters, and database links. If a table does not belong to the user, the owner’s name must be prefixed to the table. For example, if there are schemas named USERA and USERB, and both have an EMPLOYEES table, then if USERA wants to access the EMPLOYEES table that belongs to USERB, he or she must prefix the table name with the schema name: SELECT * FROM userb.employees; If USERB wants to access the EMPLOYEES table that is owned by USERA, he must prefix the table name with the schema name: SELECT * FROM usera.employees; Oracle Database 10g: SQL Fundamentals I 9 - 6
  • 19. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DEFAULT Option • Specify a default value for a column during an insert. ... hire_date DATE DEFAULT SYSDATE, ... • • • Literal values, expressions, or SQL functions are legal values. Another column’s name or a pseudocolumn are illegal e abl r values. sfe n The default data type must match the column data type. -tra n N o an CREATE TABLE hire_dates has ฺ (id NUMBER(8), ) om uide hire_date DATE DEFAULT cSYSDATE); ailฺ nt G CREATE TABLE succeeded. m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen DEFAULT H Option IM define a table, you can specify that a column be given a default value by using the When you AS RDEFAULT option. This option prevents null values from entering the columns if a row is A inserted without a value for the column. The default value can be a literal, an expression, or a SQL function (such as SYSDATE or USER), but the value cannot be the name of another column or a pseudocolumn (such as NEXTVAL or CURRVAL). The default expression must match the data type of the column. Note: CURRVAL and NEXTVAL are explained later in this lesson. Oracle Database 10g: SQL Fundamentals I 9 - 7
  • 20. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating Tables • Create the table. CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE); CREATE TABLE succeeded. • Confirm table creation. DESCRIBE dept e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating H Tables IM in the slide creates the DEPT table, with four columns: DEPTNO, DNAME, LOC, S The example RA and CREATE_DATE. The CREATE_DATE column has a default value. If a value is not provided for an INSERT statement, the system date is automatically inserted. It further confirms the creation of the table by issuing the DESCRIBE command. Because creating a table is a DDL statement, an automatic commit takes place when this statement is executed. Oracle Database 10g: SQL Fundamentals I 9 - 8
  • 21. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Data Types Data Type Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data (up to 2 GB) CLOB Character data (up to 4 GB) RAW and LONG RAW Raw binary data e l rab fe s n -tra n o an BLOB Binary data (up to 4 GB) has ฺ ) BFILE Binary data stored in an external file (up e 4 GB) comGuid to ailฺ representing the unique ROWID A base-64 number m g system ent d address of atrow in its table @ nc is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Data Types IMHidentify a column for a table, you need to provide a data type for the column. There When you AS Rare several data types available: A N Data Type Description VARCHAR2(size) Variable-length character data (A maximum size must be specified: minimum size is 1; maximum size is 4,000.) Fixed-length character data of length size bytes (Default and minimum size is 1; maximum size is 2,000.) CHAR [(size)] NUMBER [(p,s)] Number having precision p and scale s (The precision is the total number of decimal digits, and the scale is the number of digits to the right of the decimal point; the precision can range from 1 to 38, and the scale can range from –84 to 127.) DATE Date and time values to the nearest second between January 1, 4712 B.C., and December 31, 9999 A.D. LONG Variable-length character data (up to 2 GB) CLOB Character data (up to 4 GB) Oracle Database 10g: SQL Fundamentals I 9 - 9
  • 22. SQL Star International Limited Data Types (continued) D escription RAW(size) R aw binary data of length size (A m axim um size m ust be specified: m axim um size is 2,000.) LONG RAW Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. D ata T ype R aw binary data of variable length (up to 2 G B ) BLOB B inary data (up to 4 G B ) BFILE B inary data stored in an external file (up to 4 G B ) ROWID A base-64 num ber system representing the unique address of a row in its table Guidelines • A LONG column is not copied when a table is created using a subquery. • A LONG column cannot be included in a GROUP BY or an ORDER BY clause. e abl r • Only one LONG column can be used per table. sfe n • No constraints can be defined on a LONG column. -tra • You might want to use a CLOB column rather than a LONG column. on an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 9 - 10
  • 23. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Datetime Data Types You can use several datetime data types: Data Type Description TIMESTAMP Date with fractional seconds INTERVAL YEAR TO MONTH Stored as an interval of years and months INTERVAL DAY TO SECOND Stored as an interval of days, hours, minutes, and seconds e s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN DatacTypes li Other Datetime IMH S Description RA Data Type A N l rab fe TIMESTAMP Enables the time to be stored as a date with fractional seconds. There are several variations of this data type. INTERVAL YEAR TO MONTH Enables time to be stored as an interval of years and months. Used to represent the difference between two datetime values in which the only significant portions are the year and month. Enables time to be stored as an interval of days, hours, minutes, and seconds. Used to represent the precise difference between two datetime values. INTERVAL DAY TO SECOND Note: These datetime data types are available with Oracle9i and later releases. For detailed information about the datetime data types, see the topics “TIMESTAMP Datatype,” “INTERVAL YEAR TO MONTH Datatype,” and “INTERVAL DAY TO SECOND Datatype” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 9 - 11
  • 24. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Datetime Data Types • • • The TIMESTAMP data type is an extension of the DATE data type. It stores the year, month, and day of the DATE data type plus hour, minute, and second values as well as the fractional second value. You can optionally specify the time zone. s n -tra n TIMESTAMP[(fractional_seconds_precision)] TIMESTAMP[(fractional_seconds_precision)] a WITH TIME ZONE has e l rab fe no N ) ฺ comGuide TIMESTAMP[(fractional_seconds_precision)] ailฺ nt m WITH LOCAL TIME ZONE @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C e AN Type n TIMESTAMP Data lic IMH The TIMESTAMP data type is an extension of the DATE data type. It stores the year, month, and AS Rday of the DATE data type plus hour, minute, and second values. This data type is used for A storing precise time values. The fractional_seconds_precision optionally specifies the number of digits in the fractional part of the SECOND datetime field and can be a number in the range 0 to 9. The default is 6. Example In this example, a table is created named NEW_EMPLOYEES, with a column START_DATE that has a data type of TIMESTAMP: CREATE TABLE new_employees (employee_id NUMBER, first_name VARCHAR2(15), last_name VARCHAR2(15), ... start_date TIMESTAMP(7), ...); Suppose that two rows are inserted in the NEW_EMPLOYEES table. The displayed output shows the differences. (A DATE data type defaults to display the DD-MON-RR format.): Oracle Database 10g: SQL Fundamentals I 9 - 12
  • 25. SQL Star International Limited TIMESTAMP Data Type (continued) SELECT start_date FROM new_employees; Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 17-JUN-03 12.00.00.000000 AM 21-SEP-03 12.00.00.000000 AM TIMESTAMP WITH TIME ZONE Data Type TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time-zone displacement in its value. The time-zone displacement is the difference (in hours and minutes) between local time and UTC (Universal Time Coordinate, formerly known as Greenwich Mean Time). This data type is used for collecting and evaluating date information across geographic regions. For example, TIMESTAMP '2003-04-15 8:00:00 -8:00' is the same as s n -tra n N o a n Standard Time. That is, 8:00 a.m. Pacific Standard Time is the same as 11:00 a.m.s Eastern ha ฺ This can also be specified as follows: ) TIMESTAMP '2003-04-15 8:00:00 US/Pacific' comGuide ailฺ nt m e TIMESTAMP WITH LOCAL TIME ZONE Data Type d @gis another variant of TIMESTAMP that TIMESTAMP WITH LOCAL TIME ct n ZONE Stu a s includes a time-zone displacement in its thi It differs from TIMESTAMP WITH TIME mh se value. i ZONE in that data stored as database is normalized to the database time zone, and the r in theo u (na se time-zone displacement is nottstored as part of the column data. When users retrieve the C en data, it is AN returned in the users' local session time zone. The time-zone displacement is the lic H difference (in hours and minutes) between local time and UTC. SIM AUnlike TIMESTAMP WITH TIME ZONE, you can specify columns of type TIMESTAMP AR TIMESTAMP '2003-04-15 11:00:00 -5:00' WITH LOCAL TIME ZONE as part of a primary or unique key, as in the following example: CREATE TABLE time_example (order_date TIMESTAMP WITH LOCAL TIME ZONE); INSERT INTO time_example VALUES('15-JAN-04 09:34:28 AM'); SELECT * FROM time_example; ORDER_DATE ---------------------------15-JAN-04 09.34.28.000000 AM The TIMESTAMP WITH LOCAL TIME ZONE type is appropriate for two-tier applications in which you want to display dates and times using the time zone of the client system. Oracle Database 10g: SQL Fundamentals I 9 - 13 e l rab fe
  • 26. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Datetime Data Types • The INTERVAL YEAR TO MONTH data type stores a period of time using the YEAR and MONTH datetime fields: INTERVAL YEAR [(year_precision)] TO MONTH • The INTERVAL DAY TO SECOND data type stores a period of time in terms of days, hours, minutes, and seconds: INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)] e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN TOcen Data Type INTERVAL YEAR li MONTH IMH YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime S INTERVAL RA fields. Use INTERVAL YEAR TO MONTH to represent the difference between two datetime values, where the only significant portions are the year and month. For example, you might use this value to set a reminder for a date that is 120 months in the future, or check whether 6 months have elapsed since a particular date. In the syntax: year_precision is the number of digits in the YEAR datetime field. The default value of year_precision is 2. Examples • INTERVAL '123-2' YEAR(3) TO MONTH • INTERVAL '123' YEAR(3) Indicates an interval of 123 years, 2 months Indicates an interval of 123 years 0 months • INTERVAL '300' MONTH(3) • INTERVAL '123' YEAR Indicates an interval of 300 months Returns an error because the default precision is 2, and 123 has 3 digits Oracle Database 10g: SQL Fundamentals I 9 - 14
  • 27. SQL Star International Limited INTERVAL YEAR TO MONTH Data Type (continued) CREATE TABLE time_example2 (loan_duration INTERVAL YEAR (3) TO MONTH); Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. INSERT INTO time_example2 (loan_duration) VALUES (INTERVAL '120' MONTH(3)); SELECT TO_CHAR(sysdate+loan_duration, 'dd-mon-yyyy') FROM time_example2; --today’s date is 11-11-2008 INTERVAL DAY TO SECOND Data Type e l rab INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes,e and nsf seconds. a n-tr datetime o Use INTERVAL DAY TO SECOND to represent the precise difference between two a n is 36 hours in the values. For example, you might use this value to set a reminder for a time that s harepresent long spans of time, ) future, or to record the time between the start and end of a race. To ฺ ide coamGuvalue for the days portion. including multiple years, with high precision, you canlฺ use large ai nt m In the syntax: @g Isude t day_precision t the number of digits in the DAY datetime anc this Sfield. Accepted values are 0 to 9. The default imh se s is 2. ara to u fractional_seconds_precision Is the number of digits in the fractional part of n C ( ense the SECOND datetime field. Accepted values AN lic are 0 to 9. The default is 6. IMH AS RExamples A • INTERVAL '4 5:12:10.222' DAY TO SECOND(3) N Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second. • INTERVAL '180' DAY(3) Indicates 180 days. • INTERVAL '4 5:12:10.222' DAY TO SECOND(3) Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second • INTERVAL '4 5:12' DAY TO MINUTE Indicates 4 days, 5 hours, and 12 minutes • INTERVAL '400 5' DAY(3) TO HOUR Indicates 400 days and 5 hours. • INTERVAL '11:12:10.2222222' HOUR TO SECOND(7) Indicates 11 hours, 12 minutes, and 10.2222222 seconds. Oracle Database 10g: SQL Fundamentals I 9 - 15
  • 28. SQL Star International Limited INTERVAL DAY TO SECOND Data Type (continued) Example Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. CREATE TABLE time_example3 (day_duration INTERVAL DAY (3) TO SECOND); INSERT INTO time_example3 (day_duration) VALUES (INTERVAL '180' DAY(3)); SELECT sysdate + day_duration "Half Year" FROM time_example3; --today’s date is 11-11-2008 e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 9 - 16
  • 29. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Including Constraints • • • Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid: – – – – – NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK e s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Constraints IMH server uses constraints to prevent invalid data entry into tables. AS RThe Oracle NA l rab fe You can use constraints to do the following: • Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to succeed. • Prevent the deletion of a table if there are dependencies from other tables • Provide rules for Oracle tools, such as Oracle Developer Data Integrity Constraints Constraint Description NOT NULL Specifies that the column cannot contain a null value UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table PRIMARY KEY Uniquely identifies each row of the table FOREIGN KEY Establishes and enforces a foreign key relationship between the column and a column of the referenced table CHECK Specifies a condition that must be true Oracle Database 10g: SQL Fundamentals I 9 - 17
  • 30. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Constraint Guidelines • You can name a constraint, or the Oracle server generates a name with the SYS_Cn format. • Create a constraint at either of the following times: – At the same time as the table is created – After the table has been created • • Define a constraint at the column or table level. View a constraint in the data dictionary. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Constraint Guidelines IMH are stored in the data dictionary. Constraints are easy to reference if you give AS RAll constraints them a meaningful name. Constraint names must follow the standard object-naming rules. If you do not name your constraint, the Oracle server generates a name with the format SYS_Cn, where n is an integer so that the constraint name is unique. Constraints can be defined at the time of table creation or after the table has been created. For more information, see “Constraints” in Oracle Database SQL Reference. Oracle Database 10g: SQL Fundamentals I 9 - 18
  • 31. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Defining Constraints • Syntax: CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); • e l rab fe Column-level constraint: column [CONSTRAINT constraint_name] constraint_type, s • Table-level constraint: n a n-tr o N an column,... has ฺ ) [CONSTRAINT constraint_name] constraint_type comGuide (column, ...), ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Defining Constraints IMH the syntax for defining constraints when creating a table. You can create the AS RThe slide gives the column level or table level. Constraints defined at the column level are A constraints at either included when the column is defined. Table-level constraints are defined at the end of the table definition and must refer to the column or columns on which the constraint pertains in a set of parentheses. NOT NULL constraints must be defined at the column level. Constraints that apply to more than one column must be defined at the table level. In the syntax: schema Is the same as the owner’s name table Is the name of the table DEFAULT expr Specifies a default value to use if a value is omitted in the INSERT statement column Is the name of the column datatype Is the column’s data type and length column_constraint Is an integrity constraint as part of the column definition table_constraint Is an integrity constraint as part of the table definition Oracle Database 10g: SQL Fundamentals I 9 - 19
  • 32. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Defining Constraints • Column-level constraint: CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...); • 1 Table-level constraint: CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), a ... as job_id VARCHAR2(10) NOT NULL,h ) ฺ CONSTRAINT emp_emp_id_pk comGuide ailฺ t PRIMARY KEY (EMPLOYEE_ID)); m e l rab fe s n -tra n no 2 N n @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN lic(continued) Defining Constraints IMH are usually created at the same time as the table. Constraints can be added to a table AS RConstraints and also temporarily disabled. A after its creation Both slide examples create a primary key constraint on the EMPLOYEE_ID column of the EMPLOYEES table. 1. The first example uses the column-level syntax to define the constraint. 2. The second example uses the table-level syntax to define the constraint. More details about the primary key constraint are provided later in this lesson. Oracle Database 10g: SQL Fundamentals I 9 - 20
  • 33. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. NOT NULL Constraint Ensures that null values are not permitted for the column: e … NOT NULL constraint (No row can contain a null value for this column.) NOT NULL constraint l rab fe s n -tra n Absence of NOT NULL constraint (Any row can contain a null value for this column.) N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen NOT NULL Constraint IMH The NOT NULL constraint ensures that the column contains no null values. Columns without AS Rthe NOT NULL constraint can contain null values by default. NOT NULL constraints must be A defined at the column level. Oracle Database 10g: SQL Fundamentals I 9 - 21
  • 34. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. UNIQUE Constraint UNIQUE constraint EMPLOYEES e l rab fe … INSERT INTO Allowed Not allowed: a already exists as s n -tra n no N h m) ideฺ o ilฺc t Gu a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen UNIQUE Constraint IMH key integrity constraint requires that every value in a column or set of columns (key) A UNIQUE AS Rbe unique—that is, no two rows of a table can have duplicate values in a specified column or set A of columns. The column (or set of columns) included in the definition of the UNIQUE key constraint is called the unique key. If the UNIQUE constraint comprises more than one column, that group of columns is called a composite unique key. UNIQUE constraints enable the input of nulls unless you also define NOT NULL constraints for the same columns. In fact, any number of rows can include nulls for columns without NOT NULL constraints because nulls are not considered equal to anything. A null in a column (or in all columns of a composite UNIQUE key) always satisfies a UNIQUE constraint. Note: Because of the search mechanism for UNIQUE constraints on more than one column, you cannot have identical values in the non-null columns of a partially null composite UNIQUE key constraint. Oracle Database 10g: SQL Fundamentals I 9 - 22
  • 35. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. UNIQUE Constraint Defined at either the table level or the column level: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), e salary NUMBER(8,2), abl r commission_pct NUMBER(2,2), sfe n hire_date DATE NOT NULL, -tra ... non CONSTRAINT emp_email_uk UNIQUE(email)); sa N ) ha eฺ m ฺco Guid il ma ent g t@ Stud c han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C en AN li(continued) UNIQUE Constraint c IMH UNIQUE constraints can be defined at the column level or table level. A composite unique key is AS Rcreated by using the table-level definition. A The example in the slide applies the UNIQUE constraint to the EMAIL column of the EMPLOYEES table. The name of the constraint is EMP_EMAIL_UK. Note: The Oracle server enforces the UNIQUE constraint by implicitly creating a unique index on the unique key column or columns. Oracle Database 10g: SQL Fundamentals I 9 - 23
  • 36. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY e … Not allowed (null value) l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m Not allowed @g tude t (50 already exists) anc S h his t m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C AN licen PRIMARY H KEY Constraint IM KEY constraint creates a primary key for the table. Only one primary key can be S A PRIMARY RA INSERT INTO created for each table. The PRIMARY KEY constraint is a column or set of columns that uniquely identifies each row in a table. This constraint enforces uniqueness of the column or column combination and ensures that no column that is part of the primary key can contain a null value. Note: Because uniqueness is part of the primary key constraint definition, the Oracle server enforces the uniqueness by implicitly creating a unique index on the primary key column or columns. Oracle Database 10g: SQL Fundamentals I 9 - 24
  • 37. SQL Star International Limited FOREIGN KEY Constraint Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DEPARTMENTS PRIMARY KEY … EMPLOYEES FOREIGN KEY e l rab fe s n -tra n NA o an has ฺ … INSERT INTO m) Not allowed o u de ilฺc t G(9idoes not a exist) gm den @ Allowed nct is Stu a th imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen FOREIGN H Constraint KEY IM S The FOREIGN KEY (or referential integrity) constraint designates a column or combination of RA columns as a foreign key and establishes a relationship between a primary key or a unique key in the same table or a different table. In the example in the slide, DEPARTMENT_ID has been defined as the foreign key in the EMPLOYEES table (dependent or child table); it references the DEPARTMENT_ID column of the DEPARTMENTS table (the referenced or parent table). Guidelines • A foreign key value must match an existing value in the parent table or be NULL. • Foreign keys are based on data values and are purely logical, rather than physical, pointers. Oracle Database 10g: SQL Fundamentals I 9 - 25
  • 38. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. FOREIGN KEY Constraint Defined at either the table level or the column level: CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email)); e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen (continued) FOREIGN H Constraint KEY IM KEY constraints can be defined at the column or table constraint level. A composite S FOREIGN RA foreign key must be created by using the table-level definition. The example in the slide defines a FOREIGN KEY constraint on the DEPARTMENT_ID column of the EMPLOYEES table, using table-level syntax. The name of the constraint is EMP_DEPTID_FK. The foreign key can also be defined at the column level, provided the constraint is based on a single column. The syntax differs in that the keywords FOREIGN KEY do not appear. For example: CREATE TABLE employees (... department_id NUMBER(4) CONSTRAINT emp_deptid_fk REFERENCES departments(department_id), ... ) Oracle Database 10g: SQL Fundamentals I 9 - 26
  • 39. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. FOREIGN KEY Constraint: Keywords • • • • FOREIGN KEY: Defines the column in the child table at the table-constraint level REFERENCES: Identifies the table and column in the parent table ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted e abl ON DELETE SET NULL: Converts dependent foreign key fer s values to null tran - non a NA has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Keywords FOREIGN H Constraint: KEY IM key is defined in the child table, and the table containing the referenced column is AS RThe foreign the parent table. The foreign key is defined using a combination of the following keywords: • FOREIGN KEY is used to define the column in the child table at the table-constraint level. • REFERENCES identifies the table and column in the parent table. • ON DELETE CASCADE indicates that when the row in the parent table is deleted, the dependent rows in the child table are also deleted. • ON DELETE SET NULL converts foreign key values to null when the parent value is removed. The default behavior is called the restrict rule, which disallows the update or deletion of referenced data. Without the ON DELETE CASCADE or the ON DELETE SET NULL options, the row in the parent table cannot be deleted if it is referenced in the child table. Oracle Database 10g: SQL Fundamentals I 9 - 27
  • 40. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. CHECK Constraint • • Defines a condition that each row must satisfy The following expressions are not allowed: – References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns – Calls to SYSDATE, UID, USER, and USERENV functions – Queries that refer to other values in other rows ..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),... e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen CHECK Constraint IMH constraint defines a condition that each row must satisfy. The condition can use the The CHECK AS Rsame constructs as query conditions, with the following exceptions: A • References to the CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns • Calls to SYSDATE, UID, USER, and USERENV functions • Queries that refer to other values in other rows A single column can have multiple CHECK constraints that refer to the column in its definition. There is no limit to the number of CHECK constraints that you can define on a column. CHECK constraints can be defined at the column level or table level. CREATE TABLE employees (... salary NUMBER(8,2) CONSTRAINT emp_salary_min CHECK (salary > 0), ... Oracle Database 10g: SQL Fundamentals I 9 - 28
  • 41. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. CREATE TABLE: Example CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn , email VARCHAR2(25) CONSTRAINT emp_email_nn CONSTRAINT emp_email_uk , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn , job_id VARCHAR2(10) CONSTRAINT emp_job_nn , salary NUMBER(8,2) CONSTRAINT emp_salary_ck , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk departments (department_id)); PRIMARY KEY NOT NULL NOT NULL UNIQUE e NOT NULL NOT NULL l rab fe s n -tra n o an CHECK (salary>0) has ฺ ) comGuide ailฺ nt m REFERENCES @g tude ct S han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C en AN Example CREATE TABLE: lic IMH shows the statement used to create the EMPLOYEES table in the HR schema. S The example RA A N Oracle Database 10g: SQL Fundamentals I 9 - 29
  • 42. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Violating Constraints UPDATE employees SET department_id = 55 WHERE department_id = 110; e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt Department 55 does not exist. gm de @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Integrity Constraint Error IMHhave constraints in place on columns, an error is returned to you if you try to violate AS RWhen you rule. A the constraint For example, if you attempt to update a record with a value that is tied to an integrity constraint, an error is returned. In the example in the slide, department 55 does not exist in the parent table, DEPARTMENTS, and so you receive the parent key violation ORA-02291. Oracle Database 10g: SQL Fundamentals I 9 - 30
  • 43. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Violating Constraints You cannot delete a row that contains a primary key that is used as a foreign key in another table. DELETE FROM departments WHERE department_id = 60; e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen (continued) Integrity Constraint Error IMH to delete a record with a value that is tied to an integrity constraint, an error is AS RIf you attempt A returned. The example in the slide tries to delete department 60 from the DEPARTMENTS table, but it results in an error because that department number is used as a foreign key in the EMPLOYEES table. If the parent record that you attempt to delete has child records, then you receive the child record found violation ORA-02292. The following statement works because there are no employees in department 70: DELETE FROM WHERE departments department_id = 70; 1 row deleted. Oracle Database 10g: SQL Fundamentals I 9 - 31
  • 44. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Table by Using a Subquery • Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option. CREATE TABLE table [(column, column...)] AS subquery; • • Match the number of specified columns to the number of e abl r subquery columns. sfe n Define columns with column names and -tra non default values. a NA has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN fromen in Another Table Creating HTable lic Rows a IM method for creating a table is to apply the AS subquery clause, which both creates S A second RA the table and inserts rows returned from the subquery. In the syntax: table is the name of the table column is the name of the column, default value, and integrity constraint subquery is the SELECT statement that defines the set of rows to be inserted into the new table Guidelines • The table is created with the specified column names, and the rows retrieved by the SELECT statement are inserted into the table. • The column definition can contain only the column name and default value. • If column specifications are given, the number of columns must equal the number of columns in the subquery SELECT list. • If no column specifications are given, the column names of the table are the same as the column names in the subquery. • The column data type definitions and the NOT NULL constraint are passed to the new table. The other constraint rules are not passed to the new table. However, you can add constraints in the column definition. Oracle Database 10g: SQL Fundamentals I 9 - 32
  • 45. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; CREATE TABLE Succeeded. DESCRIBE dept80 e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN fromen in Another Table (continued) Creating HTable lic Rows a IM example creates a table named DEPT80, which contains details of all the employees S The slide RA working in department 80. Notice that the data for the DEPT80 table comes from the EMPLOYEES table. You can verify the existence of a database table and check column definitions by using the DESCRIBE command. Be sure to provide a column alias when selecting an expression. The expression SALARY*12 is given the alias ANNSAL. Without the alias, the following error is generated: Oracle Database 10g: SQL Fundamentals I 9 - 33
  • 46. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. ALTER TABLE Statement Use the ALTER TABLE statement to: • • • • Add a new column Modify an existing column Define a default value for the new column Drop a column e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen ALTER TABLE Statement M IyouH a table, you may need to change the table structure for any of the following After AS create ARreasons: • You omitted a column. • Your column definition needs to be changed. • You need to remove columns. You can do this by using the ALTER TABLE statement. For information about the ALTER TABLE statement, see the Oracle Database 10g SQL Fundamentals II course. Oracle Database 10g: SQL Fundamentals I 9 - 34
  • 47. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Dropping a Table • • • • • All data and structure in the table are deleted. Any pending transactions are committed. All indexes are dropped. All constraints are dropped. You cannot roll back the DROP TABLE statement. e DROP TABLE dept80; DROP TABLE succeeded. l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen DroppingH Table a IM TABLE statement removes the definition of an Oracle table. When you drop a table, S The DROP RA the database loses all the data in the table and all the indexes associated with it. Syntax DROP TABLE table In the syntax, table is the name of the table. Guidelines • All data is deleted from the table. • Any views and synonyms remain but are invalid. • Any pending transactions are committed. • Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table. Note: The DROP TABLE statement, once executed, is irreversible. The Oracle server does not question the action when you issue the DROP TABLE statement. If you own that table or have a high-level privilege, then the table is immediately removed. As with all DDL statements, DROP TABLE is committed automatically. Oracle Database 10g: SQL Fundamentals I 9 - 35
  • 48. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Summary In this lesson, you should have learned how to: • Use the CREATE TABLE statement to create a table and include constraints • Categorize the main database objects • Review the table structure • List the data types that are available for columns e abl r • Create a simple table sfe an • Explain how constraints are created at the time of n-tr table o creation an has ฺ • Describe how schema objects work m) e NA o ilฺc t Guid a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Summary IMH you should have learned how to do the following: AS RIn this lesson, CREATE TABLE • Use the CREATE TABLE statement to create a table and include constraints. • Create a table based on another table by using a subquery. DROP TABLE • Remove rows and a table structure. • Once executed, this statement cannot be rolled back. Oracle Database 10g: SQL Fundamentals I 9 - 36
  • 49. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 9: Overview This practice covers the following topics: • Creating new tables • Creating a new table by using the CREATE TABLE AS syntax • Verifying that tables exist • Dropping tables e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Practice 9: Overview IMH tables by using the CREATE TABLE statement. Confirm that the new table is added Create new AS Rto the database. Create the syntax in the command file, and then execute the command file to A create the table. Oracle Database 10g: SQL Fundamentals I 9 - 37
  • 50. SQL Star International Limited Practice 9 1. Create the DEPT table based on the following table instance chart. Place the syntax in a script called lab_09_01.sql, and then execute the statement in the script to create the table. Confirm that the table is created. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Column Name ID Key Type Primary key NAME Nulls/Unique FK Table FK Column Data type NUMBER VARCHAR2 Length 7 25 e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt g DEPARTMENTS table. Include only columns 2. Populate the DEPT table with data from them de t@ Stu that you need. a c this hthenfollowing table instance chart. Place the syntax in m 3. Create the EMP table based on asi use then execute the statement in the script to create the r a script called lab_09_03.sql, and (na se to created. table. Confirm that the table is C ANNameicen LAST_NAME FIRST_NAME DEPT_ID l ID Column IMH Type S RA Key Nulls/Unique FK Table DEPT FK Column ID Data type NUMBER VARCHAR2 VARCHAR2 NUMBER Length 7 25 25 7 Oracle Database 10g: SQL Fundamentals I 9 - 38
  • 51. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 9 (continued) 4. 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. 5. Drop the EMP table. e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 9 - 39
  • 52. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 53. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Creating Other Schema Objects e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 54. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Objectives After completing this lesson, you should be able to do the following: • Create simple and complex views • Retrieve data from views • Create, maintain, and use sequences • Create and maintain indexes • Create private and public synonyms e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Objectives IMH you are introduced to the view, sequence, synonym, and index objects. You are AS RIn this lesson, taught the basics of creating and using views, sequences, and indexes. Oracle Database 10g: SQL Fundamentals I 10 - 2
  • 55. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Database Objects Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen DatabaseH Objects IM several other objects in a database in addition to tables. In this lesson, you learn about AS RThere are Synonym Gives alternative names to objects views, sequences, indexes, and synonyms. With views, you can present and hide data from tables. Many applications require the use of unique numbers as primary key values. You can either build code into the application to handle this requirement or use a sequence to generate unique numbers. If you want to improve the performance of some queries, you should consider creating an index. You can also use indexes to enforce uniqueness on a column or a collection of columns. You can provide alternative names for objects by using synonyms. Oracle Database 10g: SQL Fundamentals I 10 - 3
  • 56. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. What Is a View? EMPLOYEES table e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen What Is aH View? IMpresent logical subsets or combinations of data by creating views of tables. A view is a AS RYou can based on a table or another view. A view contains no data of its own but is like a A logical table window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is stored as a SELECT statement in the data dictionary. Oracle Database 10g: SQL Fundamentals I 10 - 4
  • 57. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Advantages of Views To restrict data access To make complex queries easy e l rab fe s n -tra n N o an To present To provide has ฺ different views of data ) same data independence comGuthee ilฺ t id a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C ANViews en lic Advantages of H IM • ASViews restrict access to the data because the view can display selected columns from the AR table. • Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing how to write a join statement. • Views provide data independence for ad hoc users and application programs. One view can be used to retrieve data from several tables. • Views provide groups of users access to data according to their particular criteria. For more information, see “CREATE VIEW” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 5
  • 58. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Simple Views and Complex Views Feature Simple Views Complex Views Number of tables One One or more Contain functions No Yes Contain groups of data No Yes DML operations through a view Yes Not always e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Complex Views Simple Views and lic IMH classifications for views: simple and complex. The basic difference is related to AS two RThere are (INSERT, UPDATE, and DELETE) operations. A the DML • A simple view is one that: - Derives data from only one table - Contains no functions or groups of data - Can perform DML operations through the view • A complex view is one that: - Derives data from many tables - Contains functions or groups of data - Does not always allow DML operations through the view Oracle Database 10g: SQL Fundamentals I 10 - 6
  • 59. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a View • You embed a subquery in the CREATE VIEW statement: CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]]; • e l rab fe The subquery can contain complex SELECT syntax. s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating HView a IMcreate a view by embedding a subquery in the CREATE VIEW statement. S You can RA In the syntax: OR REPLACE FORCE NOFORCE view alias Re-creates the view if it already exists Creates the view regardless of whether or not the base tables exist Creates the view only if the base tables exist (This is the default.) Is the name of the view Specifies names for the expressions selected by the view’s query (The number of aliases must match the number of expressions selected by the view.) subquery Is a complete SELECT statement (You can use aliases for the columns in the SELECT list.) WITH CHECK OPTION Specifies that only those rows that are accessible to the view can be inserted or updated constraint Is the name assigned to the CHECK OPTION constraint WITH READ ONLY ensures that no DML operations can be performed on this view Oracle Database 10g: SQL Fundamentals I 10 - 7
  • 60. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a View • Create the EMPVU80 view, which contains details of employees in department 80: CREATE VIEW AS SELECT FROM WHERE CREATE VIEW empvu80 employee_id, last_name, salary employees department_id = 80; succeeded. e N l rab • Describe the structure of the view by using the DESCRIBEfe s tran command: non a DESCRIBE empvu80 as h m) ideฺ o ilฺc t Gu a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C en AN (continued) Creating HView lic a IM in the slide creates a view that contains the employee number, last name, and AS RThe example employee in department 80. A salary for each You can display the structure of the view by using the DESCRIBE command. Guidelines for Creating a View • The subquery that defines a view can contain complex SELECT syntax, including joins, groups, and subqueries. • If you do not specify a constraint name for a view created with the WITH CHECK OPTION, the system assigns a default name in the format SYS_Cn. • You can use the OR REPLACE option to change the definition of the view without dropping and re-creating it or regranting object privileges previously granted on it. Oracle Database 10g: SQL Fundamentals I 10 - 8
  • 61. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a View • Create a view by using column aliases in the subquery: CREATE VIEW salvu50 AS SELECT employee_id ID_NUMBER, last_name NAME, salary*12 ANN_SALARY FROM employees WHERE department_id = 50; CREATE VIEW succeeded. • Select the columns from this view by the given alias ns a names: n-tr o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN (continued) Creating HView lic a IMcontrol the column names by including column aliases in the subquery. AS RYou can NA The example in the slide creates a view containing the employee number (EMPLOYEE_ID) with the alias ID_NUMBER, name (LAST_NAME) with the alias NAME, and annual salary (SALARY) with the alias ANN_SALARY for every employee in department 50. As an alternative, you can use an alias after the CREATE statement and before the SELECT subquery. The number of aliases listed must match the number of expressions selected in the subquery. CREATE OR REPLACE VIEW salvu50 (ID_NUMBER, NAME, ANN_SALARY) AS SELECT employee_id, last_name, salary*12 FROM employees WHERE department_id = 50; CREATE VIEW succeeded. Oracle Database 10g: SQL Fundamentals I 10 - 9 e l rab fe
  • 62. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Retrieving Data from a View SELECT * FROM salvu50; e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C e AN from a n lic View Retrieving Data H IM You can retrieve data from a view as you would from any table. You can display either the AS R contents of the entire view or just specific rows and columns. Oracle Database 10g: SQL Fundamentals I 10 - 10
  • 63. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Modifying a View • Modify the EMPVU80 view by using a CREATE OR REPLACE VIEW clause. Add an alias for each column name: CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id) AS SELECT employee_id, first_name || ' ' || last_name, salary, department_id FROM employees WHERE department_id = 80; CREATE VIEW succeeded. • e l rab fe s n -tra n o Column aliases in the CREATE OR REPLACE VIEW an s clause are listed in the same order as ) ha ฺ the columns in the m e subquery. ฺco uid il NA G a gm dent @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Modifying a View M Ithe H REPLACE option, a view can be created even if one exists with this name already, With AS OR R thus replacing the old version of the view for its owner. This means that the view can be altered without dropping, re-creating, and regranting object privileges. Note: When assigning column aliases in the CREATE OR REPLACE VIEW clause, remember that the aliases are listed in the same order as the columns in the subquery. Oracle Database 10g: SQL Fundamentals I 10 - 11
  • 64. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Complex View Create a complex view that contains group functions to display values from two tables: CREATE OR REPLACE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) AS SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary) FROM employees e JOIN departments d ON (e.department_id = d.department_id) GROUP BY d.department_name; CREATE VIEW succeeded. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating HComplex View a IM in the slide creates a complex view of department names, minimum salaries, AS RThe example maximum salaries, and average salaries by department. Note that alternative names have been specified for the view. This is a requirement if any column of the view is derived from a function or an expression. You can view the structure of the view by using the DESCRIBE command. Display the contents of the view by issuing a SELECT statement. SELECT FROM * dept_sum_vu; Oracle Database 10g: SQL Fundamentals I 10 - 12
  • 65. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Rules for Performing DML Operations on a View • • You can usually perform DML operations on simple views. You cannot remove a row if the view contains the following: – – – – Group functions A GROUP BY clause The DISTINCT keyword The pseudocolumn ROWNUM keyword e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Operations on a View Performing DML lic IMH AS RYou can perform DML operations on data through a view if those operations follow certain rules. You can remove a row from a view unless it contains any of the following: • Group functions • A GROUP BY clause • The DISTINCT keyword • The pseudocolumn ROWNUM keyword Oracle Database 10g: SQL Fundamentals I 10 - 13
  • 66. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Rules for Performing DML Operations on a View You cannot modify data in a view if it contains: • Group functions • A GROUP BY clause • The DISTINCT keyword • The pseudocolumn ROWNUM keyword • e l rab fe Columns defined by expressions s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Operations on a View (continued) Performing DML lic IMH data through a view unless it contains any of the conditions mentioned in the AS RYou can modify previous slide or columns defined by expressions (for example, SALARY * 12). Oracle Database 10g: SQL Fundamentals I 10 - 14
  • 67. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Rules for Performing DML Operations on a View You cannot add data through a view if the view includes: • Group functions • A GROUP BY clause • The DISTINCT keyword • The pseudocolumn ROWNUM keyword • • e Columns defined by expressions abl r NOT NULL columns in the base tables that are not selectede sf n -tra by the view on NA an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Operations on a View (continued) Performing DML lic IMH data through a view unless it contains any of the items listed in the slide. You AS RYou can add cannot add data to a view if the view contains NOT NULL columns without default values in the base table. All required values must be present in the view. Remember that you are adding values directly to the underlying table through the view. For more information, see “CREATE VIEW” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 15
  • 68. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the WITH CHECK OPTION Clause • You can ensure that DML operations performed on the view stay in the domain of the view by using the WITH CHECK OPTION clause: CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM employees WHERE department_id = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck ; CREATE VIEW succeeded. • e l rab fe s n -tra n o Any attempt to change the department numbern any row a for as CHECK h in the view fails because it violates the)WITH ฺ m ide o u OPTION constraint. ilฺc N G a gm dent @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C e AN CHECKnOPTION Clause Using the WITH lic H IM It is possible to perform referential integrity checks through views. You can also enforce AS ARconstraints at the database level. The view can be used to protect data integrity, but the use is very limited. The WITH CHECK OPTION clause specifies that INSERTs and UPDATEs performed through the view cannot create rows that the view cannot select, and therefore it enables integrity constraints and data validation checks to be enforced on data being inserted or updated. Note: The WITH CHECK OPTION clause relates to inserts and updates on the view only. It has no effect on deletes. If there is an attempt to perform DML operations on rows that the view has not selected, an error is displayed, along with the constraint name if that has been specified. UPDATE empvu20 SET department_id = 10 WHERE employee_id = 201; Oracle Database 10g: SQL Fundamentals I 10 - 16
  • 69. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the WITH CHECK OPTION Clause (continued) e l rab fe ns trathe view Note: No rows are updated because if the department number were to changen-10, no to clause, would no longer be able to see that employee. With the WITH CHECKaOPTION therefore, the view can see only employees in department 20 and does not allow the department has ฺ ) number for those employees to be changed through the view. comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM AS AR N Oracle Database 10g: SQL Fundamentals I 10 - 17
  • 70. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Denying DML Operations • You can ensure that no DML operations occur by adding the WITH READ ONLY option to your view definition. • Any attempt to perform a DML operation on any row in the view results in an Oracle server error. e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Denying DML Operations IMH that no DML operations occur on your view by creating it with the WITH READ You can ensure AS RONLY option. The example in the next slide modifies the EMPVU10 view to prevent any DML A operations on the view. Oracle Database 10g: SQL Fundamentals I 10 - 18
  • 71. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Denying DML Operations CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT employee_id, last_name, job_id FROM employees WHERE department_id = 10 WITH READ ONLY ; CREATE VIEW succeeded. e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen (continued) Denying DML Operations IMH to remove a row from a view with a read-only constraint results in an error: AS RAny attempt A DELETE FROM empvu10 WHERE employee_number = 200; Any attempt to insert a row or modify a row using the view with a read-only constraint results in an Oracle server error: 01733: virtual column not allowed here. Oracle Database 10g: SQL Fundamentals I 10 - 19
  • 72. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Removing a View You can remove a view without losing data because a view is based on underlying tables in the database. DROP VIEW view; e DROP VIEW empvu80; DROP VIEW empvu80 succeeded. s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Removing a View H IMthe DROP VIEW statement to remove a view. The statement removes the view S You use RA NA l rab fe definition from the database. Dropping views has no effect on the tables on which the view was based. Views or other applications based on deleted views become invalid. Only the creator or a user with the DROP ANY VIEW privilege can remove a view. In the syntax: view is the name of the view Oracle Database 10g: SQL Fundamentals I 10 - 20
  • 73. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 10: Overview of Part 1 This practice covers the following topics: • Creating a simple view • Creating a complex view • Creating a view with a check constraint • Attempting to modify data in the view • Removing views e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Part 1 Practice 10: Overview of IMH lesson’s practice provides you with a variety of exercises in creating, using, and Part 1 of AS Rremovingthis A views. Complete questions 1–6 at the end of this lesson. Oracle Database 10g: SQL Fundamentals I 10 - 21
  • 74. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Sequences Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries Synonym Gives alternative names to objects e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Sequences IMH is a database object that creates integer values. You can create sequences and then AS RA sequence use them to generate numbers. Oracle Database 10g: SQL Fundamentals I 10 - 22
  • 75. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Sequences A sequence: • Can automatically generate unique numbers • Is a sharable object • Can be used to create a primary key value • Replaces application code • Speeds up the efficiency of accessing sequence values when cached in memory e l rab fe s n -tra n NA o an has ฺ ) c6omGuide 10 2 4 8 ailฺ nt7 1 3 m 5 9 g e d @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Sequences (continued) IMH is a user-created database object that can be shared by multiple users to generate AS RA sequence integers. You can define a sequence to generate unique values or to recycle and use the same numbers again. A typical usage for sequences is to create a primary key value, which must be unique for each row. The sequence is generated and incremented (or decremented) by an internal Oracle routine. This can be a time-saving object because it can reduce the amount of application code needed to write a sequence-generating routine. Sequence numbers are stored and generated independently of tables. Therefore, the same sequence can be used for multiple tables. Oracle Database 10g: SQL Fundamentals I 10 - 23
  • 76. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. CREATE SEQUENCE Statement: Syntax Define a sequence to generate sequential numbers automatically: CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating HSequence a IM S Automatically generate sequential numbers by using the CREATE SEQUENCE statement. RA In the syntax: sequence INCREMENT BY n START WITH n MAXVALUE n NOMAXVALUE MINVALUE n NOMINVALUE Is the name of the sequence generator Specifies the interval between sequence numbers, where n is an integer (If this clause is omitted, the sequence increments by 1.) Specifies the first sequence number to be generated (If this clause is omitted, the sequence starts with 1.) Specifies the maximum value the sequence can generate Specifies a maximum value of 10^27 for an ascending sequence and –1 for a descending sequence (This is the default option.) Specifies the minimum sequence value Specifies a minimum value of 1 for an ascending sequence and –(10^26) for a descending sequence (This is the default option.) Oracle Database 10g: SQL Fundamentals I 10 - 24
  • 77. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Sequence • • Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of the DEPARTMENTS table. Do not use the CYCLE option. CREATE SEQUENCE dept_deptid_seq INCREMENT BY 10 START WITH 120 MAXVALUE 9999 NOCACHE NOCYCLE; CREATE SEQUENCE succeeded. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating HSequence (continued) a IM | NOCYCLE S CYCLE Specifies whether the sequence continues to generate RA values after reaching its maximum or minimum value (NOCYCLE is the default option.) CACHE n | NOCACHE Specifies how many values the Oracle server preallocates and keeps in memory (By default, the Oracle server caches 20 values.) The example in the slide creates a sequence named DEPT_DEPTID_SEQ to be used for the DEPARTMENT_ID column of the DEPARTMENTS table. The sequence starts at 120, does not allow caching, and does not cycle. Do not use the CYCLE option if the sequence is used to generate primary key values, unless you have a reliable mechanism that purges old rows faster than the sequence cycles. For more information, see “CREATE SEQUENCE” in the Oracle SQL Reference. Note: The sequence is not tied to a table. Generally, you should name the sequence after its intended use. However, the sequence can be used anywhere, regardless of its name. Oracle Database 10g: SQL Fundamentals I 10 - 25
  • 78. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. NEXTVAL and CURRVAL Pseudocolumns • • • NEXTVAL returns the next available sequence value. It returns a unique value every time it is referenced, even for different users. CURRVAL obtains the current sequence value. NEXTVAL must be issued for that sequence before CURRVAL contains a value. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen NEXTVAL H CURRVAL Pseudocolumns M and Iyou create your sequence, it generates sequential numbers for use in your tables. Reference AS RAfter the sequence values by using the NEXTVAL and CURRVAL pseudocolumns. The NEXTVAL pseudocolumn is used to extract successive sequence numbers from a specified sequence. You must qualify NEXTVAL with the sequence name. When you reference sequence.NEXTVAL, a new sequence number is generated and the current sequence number is placed in CURRVAL. The CURRVAL pseudocolumn is used to refer to a sequence number that the current user has just generated. NEXTVAL must be used to generate a sequence number in the current user’s session before CURRVAL can be referenced. You must qualify CURRVAL with the sequence name. When you reference sequence.CURRVAL, the last value returned to that user’s process is displayed. Oracle Database 10g: SQL Fundamentals I 10 - 26
  • 79. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited NEXTVAL and CURRVAL Pseudocolumns (continued) Rules for Using NEXTVAL and CURRVAL You can use NEXTVAL and CURRVAL in the following contexts: • The SELECT list of a SELECT statement that is not part of a subquery • The SELECT list of a subquery in an INSERT statement • The VALUES clause of an INSERT statement • The SET clause of an UPDATE statement You cannot use NEXTVAL and CURRVAL in the following contexts: • The SELECT list of a view • A SELECT statement with the DISTINCT keyword • A SELECT statement with GROUP BY, HAVING, or ORDER BY clauses • A subquery in a SELECT, DELETE, or UPDATE statement e • The DEFAULT expression in a CREATE TABLE or ALTER TABLE statement abl r For more information, see “Pseudocolumns” and “CREATE SEQUENCE” in Oracle SQLfe s n Reference. -tra non a has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 10 - 27
  • 80. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using a Sequence • Insert a new department named “Support” in location ID 2500: INSERT INTO departments(department_id, department_name, location_id) VALUES (dept_deptid_seq.NEXTVAL, 'Support', 2500); 1 row created. • e l rab fe s View the current value for the DEPT_DEPTID_SEQ -tran sequence: non N a as h SELECT dept_deptid_seq.CURRVAL m) ideฺ o FROM dual; ilฺc t Gu a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Using a Sequence IMH in the slide inserts a new department in the DEPARTMENTS table. It uses the The example AS RDEPT_DEPTID_SEQ sequence to generate a new department number as follows. A You can view the current value of the sequence: SELECT dept_deptid_seq.CURRVAL FROM dual; Suppose that you now want to hire employees to staff the new department. The INSERT statement to be executed for all new employees can include the following code: INSERT INTO employees (employee_id, department_id, ...) VALUES (employees_seq.NEXTVAL, dept_deptid_seq .CURRVAL, ...); Note: The preceding example assumes that a sequence called EMPLOYEE_SEQ has already been created to generate new employee numbers. Oracle Database 10g: SQL Fundamentals I 10 - 28
  • 81. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Caching Sequence Values • • Caching sequence values in memory gives faster access to those values. Gaps in sequence values can occur when: – A rollback occurs – The system crashes – A sequence is used in another table e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN liValues Caching Sequence c IMH sequences in memory to provide faster access to those sequence values. The You can cache AS Rcache is populated the first time you refer to the sequence. Each request for the next sequence A value is retrieved from the cached sequence. After the last sequence value is used, the next request for the sequence pulls another cache of sequences into memory. Gaps in the Sequence Although sequence generators issue sequential numbers without gaps, this action occurs independent of a commit or rollback. Therefore, if you roll back a statement containing a sequence, the number is lost. Another event that can cause gaps in the sequence is a system crash. If the sequence caches values in memory, those values are lost if the system crashes. Because sequences are not tied directly to tables, the same sequence can be used for multiple tables. If you do so, each table can contain gaps in the sequential numbers. Oracle Database 10g: SQL Fundamentals I 10 - 29
  • 82. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Modifying a Sequence Change the increment value, maximum value, minimum value, cycle option, or cache option: ALTER SEQUENCE dept_deptid_seq INCREMENT BY 20 MAXVALUE 999999 NOCACHE NOCYCLE; ALTER SEQUENCE dept_deptid_seq succeeded. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Modifying a Sequence IMH the MAXVALUE limit for your sequence, no additional values from the sequence are S If you reach RA allocated and you will receive an error indicating that the sequence exceeds the MAXVALUE. To continue to use the sequence, you can modify it by using the ALTER SEQUENCE statement. Syntax ALTER SEQUENCE sequence [INCREMENT BY n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; In the syntax, sequence is the name of the sequence generator. For more information, see “ALTER SEQUENCE” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 30
  • 83. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Guidelines for Modifying a Sequence • • • • • You must be the owner or have the ALTER privilege for the sequence. Only future sequence numbers are affected. The sequence must be dropped and re-created to restart the sequence at a different number. Some validation is performed. e abl To remove a sequence, use the DROP statement: fer s n -tra n NA o an ) ha eฺ m ฺco Guid il ma ent g t@ Stud c han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C en ANModifying a Sequence lic Guidelines for H IM • ASYou must be the owner or have the ALTER privilege for the sequence to modify it. You R DROP SEQUENCE dept_deptid_seq; DROP SEQUENCE dept_deptid_seq succeeded.s must be the owner or have the DROP ANY SEQUENCE privilege to remove it. • Only future sequence numbers are affected by the ALTER SEQUENCE statement. • The START WITH option cannot be changed using ALTER SEQUENCE. The sequence must be dropped and re-created to restart the sequence at a different number. • Some validation is performed. For example, a new MAXVALUE that is less than the current sequence number cannot be imposed. ALTER SEQUENCE dept_deptid_seq INCREMENT BY 20 MAXVALUE 90 NOCACHE NOCYCLE; Oracle Database 10g: SQL Fundamentals I 10 - 31
  • 84. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Guidelines for Modifying a Sequence (continued) e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 10 - 32
  • 85. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Indexes Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries Synonym Gives alternative names to objects e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H Indexes IM Indexes are database objects that you can create to improve the performance of some queries. AS R NA Indexes can also be created automatically by the server when you create a primary key or unique constraint. Oracle Database 10g: SQL Fundamentals I 10 - 33
  • 86. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Indexes An index: • Is a schema object • Can be used by the Oracle server to speed up the retrieval of rows by using a pointer • Can reduce disk I/O by using a rapid path access method to locate data quickly e abl r • Is independent of the table that it indexes sfe tran • Is used and maintained automatically by the Oracle-server n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Indexes (continued) IMHserver index is a schema object that can speed up the retrieval of rows by using a AS RAn Oracle A pointer. Indexes can be created explicitly or automatically. If you do not have an index on the column, then a full table scan occurs. An index provides direct and fast access to rows in a table. Its purpose is to reduce the necessity of disk I/O by using an indexed path to locate data quickly. The index is used and maintained automatically by the Oracle server. After an index is created, no direct activity is required by the user. Indexes are logically and physically independent of the table that they index. This means that they can be created or dropped at any time and have no effect on the base tables or other indexes. Note: When you drop a table, corresponding indexes are also dropped. For more information, see “Schema Objects: Indexes” in Database Concepts. Oracle Database 10g: SQL Fundamentals I 10 - 34
  • 87. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. How Are Indexes Created? • • Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition. Manually: Users can create nonunique indexes on columns to speed up access to the rows. s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Types of H Indexes IM of indexes can be created. AS RTwo types A N e l rab fe Unique index: The Oracle server automatically creates this index when you define a column in a table to have a PRIMARY KEY or a UNIQUE key constraint. The name of the index is the name that is given to the constraint. Nonunique index: This is an index that a user can create. For example, you can create a FOREIGN KEY column index for a join in a query to improve retrieval speed. Note: You can manually create a unique index, but it is recommended that you create a unique constraint, which implicitly creates a unique index. Oracle Database 10g: SQL Fundamentals I 10 - 35
  • 88. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating an Index • Create an index on one or more columns: CREATE INDEX index ON table (column[, column]...); • Improve the speed of query access to the LAST_NAME column in the EMPLOYEES table: CREATE INDEX emp_last_name_idx ON employees(last_name); CREATE INDEX succeeded. In the syntax: index table column Is the name of the index Is the name of the table Is the name of the column in the table to be indexed For more information, see “CREATE INDEX” in Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 36 s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating H Index an IM index on one or more columns by issuing the CREATE INDEX statement. S Create an RA NA e l rab fe
  • 89. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Index Creation Guidelines Create an index when: A column contains a wide range of values A column contains a large number of null values One or more columns are frequently used together in a WHERE clause or a join condition The table is large and most queries are expected to retrieve less than 2% to 4% of the rows in the table Do not create an index when: The columns are not often used as a condition in the query e l rab fe s n -tra n N o an has ฺ ) The table is updated frequently comGuide ฺ ailpart ntan expression The indexed columns are referenced as of m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN liBetter More Is Not Always c IMH indexes on a table does not produce faster queries. Each DML operation that is AS RHaving more a table with indexes means that the indexes must be updated. The more indexes A committed on The table is small or most queries are expected to retrieve more than 2% to 4% of the rows in the table that you have associated with a table, the more effort the Oracle server must make to update all the indexes after a DML operation. When to Create an Index Therefore, you should create indexes only if: • The column contains a wide range of values • The column contains a large number of null values • One or more columns are frequently used together in a WHERE clause or join condition • The table is large and most queries are expected to retrieve less than 2% to 4% of the rows Remember that if you want to enforce uniqueness, you should define a unique constraint in the table definition. A unique index is then created automatically. Oracle Database 10g: SQL Fundamentals I 10 - 37
  • 90. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Removing an Index • Remove an index from the data dictionary by using the DROP INDEX command: DROP INDEX index; • Remove the UPPER_LAST_NAME_IDX index from the data dictionary: DROP INDEX emp_last_name_idx; DROP INDEX emp_last_name_idx succeeded. • s n -tra n o To drop an index, you must be the owner of the index or an s have the DROP ANY INDEX privilege.) ha ฺ m e ฺco Guid il t a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Removing an Index IMH modify indexes. To change an index, you must drop it and then re-create it. AS RYou cannot NA Remove an index definition from the data dictionary by issuing the DROP INDEX statement. To drop an index, you must be the owner of the index or have the DROP ANY INDEX privilege. In the syntax, index is the name of the index. Note: If you drop a table, indexes and constraints are automatically dropped but views and sequences remain. Oracle Database 10g: SQL Fundamentals I 10 - 38 e l rab fe
  • 91. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Synonyms Object Description Table Basic unit of storage; composed of rows View Logically represents subsets of data from one or more tables Sequence Generates numeric values Index Improves the performance of some queries Synonym Gives alternative names to objects e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Synonyms IMHare database objects that enable you to call a table by another name. You can create AS RSynonyms synonyms to give an alternative name to a table. Oracle Database 10g: SQL Fundamentals I 10 - 39
  • 92. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Synonyms Simplify access to objects by creating a synonym (another name for an object). With synonyms, you can: • Create an easier reference to a table that is owned by another user • Shorten lengthy object names e CREATE [PUBLIC] SYNONYM synonym FOR object; l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN licfor an Object Creating HSynonym a IMto a table that is owned by another user, you need to prefix the table name with the AS RTo refer name of the user who created it, followed by a period. Creating a synonym eliminates the need to qualify the object name with the schema and provides you with an alternative name for a table, view, sequence, procedure, or other objects. This method can be especially useful with lengthy object names, such as views. In the syntax: PUBLIC Creates a synonym that is accessible to all users synonym Is the name of the synonym to be created object Identifies the object for which the synonym is created Guidelines • The object cannot be contained in a package. • A private synonym name must be distinct from all other objects that are owned by the same user. For more information, see “CREATE SYNONYM” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 40
  • 93. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating and Removing Synonyms • Create a shortened name for the DEPT_SUM_VU view: CREATE SYNONYM d_sum FOR dept_sum_vu; CREATE SYNONYM succeeded. • Drop a synonym: DROP SYNONYM d_sum; DROP SYNONYM succeeded. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Creating HSynonym a IM example creates a synonym for the DEPT_SUM_VU view for quicker reference. S The slide RA The database administrator can create a public synonym that is accessible to all users. The following example creates a public synonym named DEPT for Alice’s DEPARTMENTS table: CREATE PUBLIC SYNONYM dept FOR alice.departments; CREATE SYNONYM succeeded. Removing a Synonym To remove a synonym, use the DROP SYNONYM statement. Only the database administrator can drop a public synonym. DROP PUBLIC SYNONYM dept; DROP SYNONYM succeeded. For more information, see “DROP SYNONYM” in the Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I 10 - 41
  • 94. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Summary In this lesson, you should have learned how to: • Create, use, and remove views • Automatically generate sequence numbers by using a sequence generator • Create indexes to improve query retrieval speed • Use synonyms to provide alternative names for objects e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Summary IMH you should have learned about database objects such as views, sequences, indexes, AS RIn this lesson, and synonyms. Oracle Database 10g: SQL Fundamentals I 10 - 42
  • 95. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 10: Overview of Part 2 This practice covers the following topics: • Creating sequences • Using sequences • Creating nonunique indexes • Creating synonyms e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Part 2 Practice 10: Overview of IMH lesson’s practice provides you with a variety of exercises in creating and using a Part 2 of AS Rsequence,this index, and a synonym. A an Complete questions 7–10 at the end of this lesson. Oracle Database 10g: SQL Fundamentals I 10 - 43
  • 96. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Practice 10 Part 1 1. The staff in the HR department want to hide some of the data in the EMPLOYEES table. They want a view called EMPLOYEES_VU based on the employee numbers, employee names, and department numbers from the EMPLOYEES table. They want the heading for the employee name to be EMPLOYEE. 2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view. e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA 3. Using your EMPLOYEES_VU view, write a query for the HR department to display all employee names and department numbers. … Oracle Database 10g: SQL Fundamentals I 10 - 44
  • 97. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Practice 10 (continued) 4. Department 50 needs access to its employee data. Create a view named DEPT50 that contains the employee numbers, employee last names, and department numbers for all employees in department 50. You are asked to label the view columns EMPNO, EMPLOYEE, and DEPTNO. For security purposes, do not allow an employee to be reassigned to another department through the view. 5. Display the structure and contents of the DEPT50 view. e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m 6. Test your view. Attempt to reassigntMatos to department 80. @g tude c S han this m asi use r (na se to C AN licen IMH S RA NA Oracle Database 10g: SQL Fundamentals I 10 - 45
  • 98. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Practice 10 (continued) Part 2 7. You need a sequence that can be used with the primary key column of the DEPT table. The sequence should start at 200 and have a maximum value of 1,000. Have your sequence increment by 10. Name the sequence DEPT_ID_SEQ. 8. To test your sequence, write a script to insert two rows in the DEPT table. Name your script lab_10_08.sql. Be sure to use the sequence that you created for the ID column. Add two departments: Education and Administration. Confirm your additions. Run the commands in your script. 9. Create a nonunique index on the NAME column in the DEPT table. 10. Create a synonym for your EMPLOYEES table. Call it EMP. e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 10 - 46
  • 99. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Managing Objects with Data Dictionary Views e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 100. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 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 e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Objectives IMH you are introduced to the data dictionary views. You learn that the dictionary AS RIn this lesson, views can be used to retrieve metadata and create reports about your schema objects. Oracle Database 10g: SQL Fundamentals I 11 - 2
  • 101. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Data Dictionary Oracle server Tables containing business data: EMPLOYEES DEPARTMENTS LOCATIONS JOB_HISTORY ... Data dictionary e views: abl r DICTIONARY sfe n USER_OBJECTSra -t USER_TABLES non a USER_TAB_COLUMNS as h ... ฺ N ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Data Dictionary MH Itables are tables created by the user and contain business data, such as EMPLOYEES. There User AS Ris another collection of tables and views in the Oracle Database known as the data dictionary. A 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 also 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 Oracle Database 10g: SQL Fundamentals I 11 - 3
  • 102. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Data Dictionary Structure Oracle server Consists of: – Base tables – User-accessible views e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Structure lic Data Dictionary H IM Underlying base tables store information about the associated database. Only the Oracle server AS ARshould write to and read 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. Oracle Database 10g: SQL Fundamentals I 11 - 4
  • 103. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Data Dictionary Structure View naming convention: View Prefix Purpose USER User’s view (what is in your schema; what you own) ALL Expanded user’s view (what you can access) DBA Database administrator’s view (what is in everyone’s schemas) V$ Performance-related data e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Structure (continued) Data Dictionary lic IMH The data dictionary consists of sets of views. In a set consists of three AS Rcontaining similar information and distinguishedmany cases,other by their prefixes.views A from each For example, 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 on 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. Oracle Database 10g: SQL Fundamentals I 11 - 5
  • 104. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. How to Use the Dictionary Views Start with DICTIONARY. It contains the names and descriptions of the dictionary tables and views. DESCRIBE DICTIONARY e SELECT * FROM dictionary WHERE table_name = 'USER_OBJECTS'; l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Dictionary Views lic How to Use the H IM ToS A familiarize yourself with the dictionary views, you can use the dictionary view named ARDICTIONARY. It contains the name and short description of each dictionary view to which you have access. You can write queries to search for information on 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'; Note: The names in the data dictionary are uppercase. Oracle Database 10g: SQL Fundamentals I 11 - 6
  • 105. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. USER_OBJECTS and ALL_OBJECTS Views • Use the USER_OBJECTS view to: – See all of the objects that are owned by you – Obtain a listing of all object names and types in your schema, plus the following information: — — — • Date created Date of last modification Status (valid or invalid) Use the ALL_OBJECTS view to see all objects to which ns a you have access n-tr o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN View en USER_OBJECTS lic H IM You can query the USER_OBJECTS view to see the names and types of all the objects in your AS R NA schema. There are several columns in this view: • OBJECT_NAME: Name of the object • OBJECT_ID: Dictionary object number of the object • OBJECT_TYPE: Type of object (such as TABLE, VIEW, INDEX, SEQUENCE) • CREATED: Timestamp for the creation of the object • LAST_DDL_TIME: Timestamp for the last modification of the object resulting from a DDL command • STATUS: Status of the object (VALID, INVALID, or N/A) • GENERATED: Was the name of this object system-generated? (Y|N) 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. Oracle Database 10g: SQL Fundamentals I 11 - 7 e l rab fe
  • 106. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. USER_OBJECTS View SELECT object_name, object_type, created, status FROM user_objects ORDER BY object_type; e l rab fe s n -tra n NA o an has ฺ ) … comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN View (continued) USER_OBJECTS lic H IM The example shows the names, types, dates of creation, and status of all objects that are owned AS R by this 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. While 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. Oracle Database 10g: SQL Fundamentals I 11 - 8
  • 107. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Table Information USER_TABLES: DESCRIBE user_tables … e SELECT table_name FROM user_tables; l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m … @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen USER_TABLES View IMH the USER_TABLES view to obtain the names of all of your tables. The S You can use RA USER_TABLES view contains information about your tables. In addition to providing the table name, it contains detailed information on the storage. The TABS view is a synonym of the USER_TABLES view. You can query it to see a listing of tables that you own: SELECT table_name FROM tabs; 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. Oracle Database 10g: SQL Fundamentals I 11 - 9
  • 108. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Column Information USER_TAB_COLUMNS: DESCRIBE user_tab_columns e l rab fe s n -tra n N o an has ฺ ) … comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Column Information IMH the USER_TAB_COLUMNS view to find detailed information about the columns You can query AS Rin your tables. While the USER_TABLES view provides information on your table names and A 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. Oracle Database 10g: SQL Fundamentals I 11 - 10
  • 109. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Column Information SELECT column_name, data_type, data_length, data_precision, data_scale, nullable FROM user_tab_columns WHERE table_name = 'EMPLOYEES'; e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Column Information (continued) IMH the USER_TAB_COLUMNS table, you can find details about your columns such as ByS A querying Rthe names, data types, data type lengths, null constraints, and default value for a column. A 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. Oracle Database 10g: SQL Fundamentals I 11 - 11
  • 110. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Constraint Information • • USER_CONSTRAINTS describes the constraint definitions on your tables. USER_CONS_COLUMNS describes columns that are owned by you and that are specified in constraints. DESCRIBE user_constraints e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t … anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Constraint Information IMH out the names of your constraints, the type of constraint, the table name to which AS RYou can find 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. Oracle Database 10g: SQL Fundamentals I 11 - 12
  • 111. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Constraint Information SELECT constraint_name, constraint_type, search_condition, r_constraint_name, delete_rule, status FROM user_constraints WHERE table_name = 'EMPLOYEES'; e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen USER_CONSTRAINTS: Example IMH shown, the USER_CONSTRAINTS view is queried to find the names, types, S In the example RA 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) • 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. Oracle Database 10g: SQL Fundamentals I 11 - 13
  • 112. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Constraint Information DESCRIBE user_cons_columns e SELECT constraint_name, column_name FROM user_cons_columns WHERE table_name = 'EMPLOYEES'; s n -tra n o an has ฺ ) comGuide ailฺ nt m … @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen QueryingH USER_CONS_COLUMNS IM names of the columns to which a constraint applies, query the ToS the find RA NA l rab fe USER_CONS_COLUMNS dictionary view. This view tells you the name of the owner of a 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 the USER_CONSTRAINTS and USER_CONS_COLUMNS to create customized output from both tables. Oracle Database 10g: SQL Fundamentals I 11 - 14
  • 113. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. View Information 1 DESCRIBE user_views 2 SELECT DISTINCT view_name FROM user_views; e l rab fe s n -tra n o an 3 ) ฺ comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to N C licen AData Dictionary Views in the MH Iyour view is created, you can query the data dictionary view called USER_VIEWS to see After AS Rthe name of the view and the view definition. The text of the SELECT statement that constitutes NA your view is stored in a LONG column. The LENGTH column is the number of characters in the SELECT text FROM user_views s WHERE view_name = 'EMP_DETAILS_VIEW'; ha SELECT statement. By default, when you select from a LONG column, only the first 80 characters of the column’s value are displayed. To see more than 80 characters in SQL*Plus, use the command SET LONG: SET LONG 1000 In the examples in the slide: 1. The USER_VIEWS columns are displayed. Note that this is a partial listing. 2. The names of your views are retrieved. 3. The SELECT statement for the EMP_DETAILS_VIEW is displayed from the dictionary. Data Access Using Views When you access data using a view, the Oracle server performs the following operations: • It retrieves the view definition from the data dictionary table USER_VIEWS. • It checks access privileges for the view base table. • It converts the view query into an equivalent operation on the underlying base table or tables. In other words, data is retrieved from, or an update is made to, the base tables. Oracle Database 10g: SQL Fundamentals I 11 - 15
  • 114. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Sequence Information DESCRIBE user_sequences e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C e AN Viewn USER_SEQUENCES lic IMH S The USER_SEQUENCES view describes all sequences that are owned by you. When you create RA the 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 sequence is incremented • CYCLE_FLAG: Does sequence wrap around on reaching 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. Oracle Database 10g: SQL Fundamentals I 11 - 16
  • 115. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Sequence Information • Verify your sequence values in the USER_SEQUENCES data dictionary table. SELECT FROM sequence_name, min_value, max_value, increment_by, last_number user_sequences; e l rab fe s • n -tra n o The LAST_NUMBER column displays the next available an sequence number if NOCACHE is specified. s ha NA ) ฺ comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Confirming Sequences MH Icreating your sequence, it is documented in the data dictionary. Because a sequence is a AS RAfter 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. Oracle Database 10g: SQL Fundamentals I 11 - 17
  • 116. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Synonym Information DESCRIBE user_synonyms e SELECT * FROM user_synonyms; l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN Viewen USER_SYNONYMS lic IMH S The USER_SYNONYMS dictionary view describes private synonyms (synonyms that are owned RA by you). You can query this view to find your synonyms. You can query ALL_SYNONYMS to find out the name of all of 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) Oracle Database 10g: SQL Fundamentals I 11 - 18
  • 117. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Adding Comments to a Table • You can add comments to a table or column by using the COMMENT statement: COMMENT ON TABLE employees IS 'Employee Information'; COMMENT ON succeeded. • Comments can be viewed through the data dictionary views: – – – – ALL_COL_COMMENTS USER_COL_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN litoen Adding Comments c a Table IMH a comment of up to 4,000 bytes about a column, table, view, or snapshot by using AScan add RYouCOMMENT statement. The comment is stored in the data dictionary and can be viewed in one A the 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 ' '; Oracle Database 10g: SQL Fundamentals I 11 - 19
  • 118. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Summary In this lesson, you should have learned how to find information about your objects by using the following dictionary views: • DICTIONARY • USER_OBJECTS • USER_TABLES • USER_TAB_COLUMNS e abl r • USER_CONSTRAINTS sfe n -tra • USER_CONS_COLUMNS non a • USER_VIEWS as h • USER_SEQUENCES m) ideฺ o ilฺc t Gu • USER_TAB_SYNONYMS ma NA n @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Summary IMH you learned about some of the dictionary views that are available to you. You can AS RIn this lesson, use these dictionary views to find information about your tables, constraints, views, sequences, and synonyms. Oracle Database 10g: SQL Fundamentals I 11 - 20
  • 119. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 11: 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 e abl r • Querying the dictionary views for synonym information sfe n -tra • Adding a comment to a table and querying the dictionary non views for comment information sa ) ha eฺ m ฺco Guid il ma ent g t@ Stud c han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C AN licen Practice 11: Overview IMH you query the dictionary views to find information about the objects in your AS RIn this practice, A schema. N Oracle Database 10g: SQL Fundamentals I 11 - 21
  • 120. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 11 1. For a specified table, create a script that reports the column names, data types, and lengths of the data types, as well as whether nulls are allowed. Prompt the user to enter the table name. Give appropriate aliases to the DATA_PRECISION and DATA_SCALE columns. Save this script in a file named lab_11_01.sql. For example, if the user enters DEPARTMENTS, the following output results: e l rab e 2. Create a script that reports the column name, constraint name, constraint type, search nsf condition, and status for a specified table. You must join the USER_CONSTRAINTS tra n-the user to and USER_CONS_COLUMNS tables to obtain all this information. Prompt o an enter the table name. Save the script in a file named lab_11_02.sql. has ฺ ) For example, if the user enters DEPARTMENTS, the following e comGuidoutput results: ailฺ nt m @g tude t anc this S imh se s ara to u n e C ( toethesDEPARTMENTS table. Then query the 3. Add a comment AN lic n USER_TAB_COMMENTS view to verify that the comment is present. IMH S RA NA 4. Find the names of all synonyms that are in your schema. Oracle Database 10g: SQL Fundamentals I 11 - 22
  • 121. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Practice 11 (continued) 5. You need to determine the names and definitions of all the views in your schema. Create a report that retrieves the view information: the view name and text from the USER_VIEWS data dictionary view. Note: Another view already exists. The EMP_DETAILS_VIEW was created as part of your schema. Also, if you completed practice 10, you see the DEPT50 view. Note: 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. e 6. Find the names of your sequences. Write a query in a script to display the following abl information about your sequences: sequence name, maximum value, increment size, r sfe nscript. and last number. Name the script lab_11_06.sql. Run the statement intyour ra - non a has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I 11 - 23
  • 122. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 123. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. ________________ A Practice Solutions ________________ e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 124. SQL Star International Limited Practice 1: Solutions Part 1 Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Test your knowledge: 1. The following SELECT statement executes successfully: SELECT last_name, job_id, salary AS Sal FROM employees; True/False 2. The following SELECT statement executes successfully: SELECT * FROM job_grades; e l rab fe s n -tra n o an s 3. There are four coding errors in this statement. Can you identifyha them? ) ฺ SELECT employee_id, last_name comGuide sal x 12 ANNUAL SALARY ailฺ nt m e FROM employees; @ag tudcalled sal. The column is called t • The EMPLOYEES table does not contain column anc this S h SALARY. imis *,se x, as shown in line 2. s • The multiplication operator u not araaliaso n t cannot include spaces. The alias should read • The ANNUAL SALARY C ( eor se be enclosed in double quotation marks. ANNUAL_SALARY n should N lic HA • A comma is missing after the LAST_NAME column. IM AS True/False R NA Part 2 Note the following location for the lab files: homeoraclelabsSQL1labs If you are asked to save any lab files, save them at this location. To start Oracle SQL Developer, double-click the SQL Developer desktop icon. Before you begin with the practices, you need a database connection to be able to connect to the database and issue SQL queries. Oracle Database 10g: SQL Fundamentals I A - 2
  • 125. SQL Star International Limited Practice 1: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 4. To create a new database connection in the Connections Navigator, right-click Connections. Select New Connection from the menu. The New/Select Database Connection dialog box appears. 5. Create a database connection using the following information: a. Connection Name: myconnection b. Username: ora1 c. Password: ora1 d. Hostname: localhost e. Port: 1521 f. SID: ORCL g. Ensure that you select the Save Password check box. s NA Oracle Database 10g: SQL Fundamentals I A - 3 n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA e l rab fe
  • 126. SQL Star International Limited Practice 1: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. You have been hired as a SQL programmer for Acme Corporation. Your first task is to create some reports based on data from the Human Resources tables. 6. Your first task is to determine the structure of the DEPARTMENTS table and its contents. DESCRIBE departments SELECT * FROM departments; 7. You need to determine the structure of the EMPLOYEES table. e l rab fe DESCRIBE employees s The HR department wants a query to display the last name, job code, hire date, and employee number for each employee, with the employee number appearing first. Provide an alias STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named lab_01_07.sql so that you can dispatch this file to the HR department. n -tra n o an has ฺ ) SELECT employee_id, last_name, job_id, hire_date StartDate comGuide FROM employees; ailฺ nt m 8. Test your query in the lab_01_07.sql file to ensure that it runs correctly. @g tude t S anc job_id, hire_date StartDate SELECT employee_id, last_name, his h t m FROM employees; asi use r o (naneeds atquery to display all unique job codes from the EMPLOYEES 9. The HR department se C en table. AN lic H IM SELECT DISTINCT job_id AS FROM employees; R NA Part 3 If you have time, complete the following exercises: 10. The HR department wants more descriptive column headings for its report on employees. Copy the statement from lab_01_07.sql to the SQL Developer text box. Name the column headings Emp #, Employee, Job, and Hire Date, respectively. Then run your query again. SELECT employee_id "Emp #", last_name "Employee", job_id "Job", hire_date "Hire Date" FROM employees; Oracle Database 10g: SQL Fundamentals I A - 4
  • 127. SQL Star International Limited Practice 1: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 11. The HR department has requested a report of all employees and their job IDs. Display the last name concatenated with the job ID (separated by a comma and space) and name the column Employee and Title. SELECT last_name||', '||job_id "Employee and Title" FROM employees; If you want an extra challenge, complete the following exercise: 12. To familiarize yourself with the data in the EMPLOYEES table, create a query to display all the data from the EMPLOYEES table. Separate each column output with a comma. Name the column THE_OUTPUT. o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I A - 5 s n -tra n SELECT employee_id || ',' || first_name || ',' || last_name || ',' || email || ',' || phone_number || ','|| job_id || ',' || manager_id || ',' || hire_date || ',' || salary || ',' || commission_pct || ',' || department_id THE_OUTPUT FROM employees; e l rab fe
  • 128. SQL Star International Limited Practice 2: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. The HR department needs your assistance with creating some queries. 1. Because of budget issues, the HR department needs a report that displays the last name and salary of employees earning more than $12,000. Place your SQL statement in a text file named lab_02_01.sql. Run your query. SELECT FROM WHERE last_name, salary employees salary > 12000; 2. Create a report that displays the last name and department number for employee number 176. SELECT FROM WHERE last_name, department_id employees employee_id = 176; s n -tra n o an has ฺ ) comGuide ailฺ nt m SELECT last_name, salary @g tude FROM employees ct S WHERE salary NOT BETWEEN an 5000 AND 12000; h his im se t asthe last name, job ID, and start date for the employees whose last 4. Create a report to display u ar ( and se to names are Matosn Taylor. Order the query in ascending order by start date. C en SELECT AN last_name, job_id, hire_date lic FROM H employees SIM 3. The HR departments needs to find high-salary and low-salary employees. Modify lab_02_01.sql to display the last name and salary for all employees whose salary is not in the $5,000–$12,000 range. Place your SQL statement in a text file named lab_02_03.sql. N RAWHERE A ORDER last_name IN ('Matos', 'Taylor') BY hire_date; 5. Display the last name and department number of all employees in departments 20 or 50 in ascending alphabetical order by name. SELECT FROM WHERE ORDER BY last_name, department_id employees department_id IN (20, 50) last_name ASC; Oracle Database 10g: SQL Fundamentals I A - 6 e l rab fe
  • 129. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 2: Solutions (continued) 6. Modify lab_02_03.sql to list the last name and salary of employees who earn between $5,000 and $12,000, and are in department 20 or 50. Label the columns Employee and Monthly Salary, respectively. Resave lab_02_03.sql as lab_02_06.sql. Run the statement in lab_02_06.sql. SELECT FROM WHERE AND last_name "Employee", salary "Monthly Salary" employees salary BETWEEN 5000 AND 12000 department_id IN (20, 50); 7. The HR department needs a report that displays the last name and hire date for all employees who were hired in 1994. SELECT FROM WHERE last_name, hire_date employees hire_date LIKE '%94'; s n -tra n o an has ฺ ) SELECT last_name, job_id FROM employees comGuide ailฺ nt WHERE manager_id IS NULL; m e @g forudemployees who earn commissions. Sort 9. Display the last name, salary, and commissionSt all nct is aand commissions. data in descending order of salary imh se th s u SELECT last_name,a ar salary, commission_pct (n se to FROM employees C en WHERE commission_pct IS NOT NULL AN licDESC, commission_pct DESC; ORDERH salary BY IM AS 8. Create a report to display the last name and job title of all employees who do not have a manager. R NA 10. Members of the HR department want to have more flexibility with the queries that you are writing. They would like a report that displays the last name and salary of employees who earn more than an amount that the user specifies after a prompt. (You can use the query created in practice exercise 1 and modify it.) Save this query to a file named lab_02_10.sql. SELECT FROM WHERE last_name, salary employees salary > &sal_amt; Oracle Database 10g: SQL Fundamentals I A - 7 e l rab fe
  • 130. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 2: Solutions (continued) 11. The HR department wants to run reports based on a manager. Create a query that prompts the user for a manager ID and generates the employee ID, last name, salary, and department for that manager’s employees. The HR department wants the ability to sort the report on a selected column. You can test the data with the following values: manager ID = 103, sorted by employee last name manager ID = 201, sorted by salary manager ID = 124, sorted by employee ID SELECT employee_id, last_name, salary, department_id FROM employees WHERE manager_id = &mgr_num ORDER BY &order_col; s n -tra n o an has is a. ) 12. Display all employee last names in which the third letter of the name ฺ comGuide SELECT last_name ailฺ nt FROM employees gm de WHERE last_name LIKE '__a%';t@ tu anc this S 13. Display the last names of all employees who have both an a and an e in their last names. imh se s ara to u SELECT last_name n FROM employees se C ( en WHERE AN last_name LIKE '%a%' lic AND H last_name LIKE '%e%'; IM AS If you have time, complete the following exercises: R NA e l rab fe If you want an extra challenge, complete the following exercises: 14. Display the last name, job, and salary for all employees whose job is either that of a sales representative or a stock clerk, and whose salary is not equal to $2,500, $3,500, or $7,000. SELECT FROM WHERE AND last_name, job_id, salary employees job_id IN ('SA_REP', 'ST_CLERK') salary NOT IN (2500, 3500, 7000); 15. Modify lab_02_06.sql to display the last name, salary, and commission for all employees whose commission amount is 20%. Resave lab_02_06.sql as lab_02_15.sql. Rerun the statement in lab_02_15.sql. SELECT FROM WHERE last_name "Employee", salary "Monthly Salary", commission_pct employees commission_pct = .20; Oracle Database 10g: SQL Fundamentals I A - 8
  • 131. SQL Star International Limited Practice 3: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 1. Write a query to display the current date. Label the column Date. SELECT FROM sysdate "Date" dual; 2. The HR department needs a report to display the employee number, last name, salary, and salary increased by 15.5% (expressed as a whole number) for each employee. Label the column New Salary. Place your SQL statement in a text file named lab_03_02.sql. SELECT FROM employee_id, last_name, salary, ROUND(salary * 1.155, 0) "New Salary" employees; 3. Run your query in the lab_03_02.sql file. SELECT s n -tra n o an FROM has ฺ ) e 4. Modify your lab_03_02.sql query to add a columnom subtracts the old salary from the c thatGuidfile as new salary. Label the column Increase. Save ailฺ the contents of the lab_03_04.sql. Run the revised query. gm ent d @ nct is Stu SELECT employee_id, last_name, salary, a t "New Salary", ROUND(salary *imh 1.155, 0)h s 0) ROUND(salary s 1.155,e - salary "Increase" a* FROM employees; nar e to u C ( ens N ic 5. WriteAquery that displays the last name (with the first letter uppercase and all other letters H a andlthe length of the last name for all employees whose name starts with the IM lowercase) AS letters J, A, or M. Give each column an appropriate label. Sort the results by the employees’ R NA employee_id, last_name, salary, ROUND(salary * 1.155, 0) "New Salary" employees; e l rab fe last names. SELECT INITCAP(last_name) "Name", LENGTH(last_name) "Length" FROM employees WHERE last_name LIKE 'J%' OR last_name LIKE 'M%' OR last_name LIKE 'A%' ORDER BY last_name ; Oracle Database 10g: SQL Fundamentals I A - 9
  • 132. SQL Star International Limited Practice 3: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Rewrite the query so that the user is prompted to enter a letter that starts the last name. For example, if the user enters H when prompted for a letter, the output should show all employees whose last name starts with the letter H. SELECT INITCAP(last_name) "Name", LENGTH(last_name) "Length" FROM employees WHERE last_name LIKE '&start_letter%' ORDER BY last_name; 6. The HR department wants to find the duration of employment for each employee. For each employee, display the last name and calculate the number of months between today and the date on which the employee was hired. Label the column MONTHS_WORKED. Order your results by the number of months employed. Round the number of months up to the closest whole number. s n -tra n o an has ฺ SELECT last_name, ROUND(MONTHS_BETWEEN( ) e SYSDATE, hire_date)) MONTHS_WORKED com ilฺ t Guid FROM employees a ORDER BY months_worked; gm den @ nct is Stu employee: 7. Create a report that produces thea following for each h imh s <salary> monthly but wants <3 times <employee last name> earnse s u t a salary>. nar e to C ( ens LabelAN li H the columncDream Salaries. IM last_name || ' earns ' SELECT AS Note: Your results will differ. R NA FROM || TO_CHAR(salary, 'fm$99,999.00') || ' monthly but wants ' || TO_CHAR(salary * 3, 'fm$99,999.00') || '.' "Dream Salaries" employees; If you have time, complete the following exercises: 8. Create a query to display the last name and salary for all employees. Format the salary to be 15 characters long, left-padded with the “$” symbol. Label the column SALARY. SELECT last_name, LPAD(salary, 15, '$') SALARY FROM employees; Oracle Database 10g: SQL Fundamentals I A - 10 e l rab fe
  • 133. SQL Star International Limited Practice 3: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 9. Display each employee’s last name, hire date, and salary review date, which is the first Monday after six months of service. Label the column REVIEW. Format the dates to appear in the format similar to “Monday, the Thirty-First of July, 2000.” SELECT last_name, hire_date, TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date, 6),'MONDAY'), 'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW FROM employees; 10. Display the last name, hire date, and day of the week on which the employee started. Label the column DAY. Order the results by the day of the week, starting with Monday. SELECT last_name, hire_date, TO_CHAR(hire_date, 'DAY') DAY FROM employees ORDER BY TO_CHAR(hire_date - 1, 'd'); o an If you want an extra challenge, complete the following exercises: as h m) ideฺ amounts. If an 11. Create a query that displays the employees’ last names and commission o ilฺc t Gu the column COMM. employee does not earn commission, show “No Commission.” Label a gm den SELECT last_name, @ nct is Stu NVL(TO_CHAR(commission_pct), 'No Commission') COMM a FROM employees; mh se th i ras to u 12. Create a query that displays the first eight characters of the employees’ last names and (na se indicates the amounts of their salaries with asterisks. Each asterisk signifies a thousand N C ce in ASort thelidatan descending order of salary. Label the column dollars. IMH AS EMPLOYEES_AND_THEIR_SALARIES. R NA s n -tra n SELECT rpad(last_name, 8)||' '|| rpad(' ', salary/1000+1, '*') EMPLOYEES_AND_THEIR_SALARIES FROM employees ORDER BY salary DESC; Oracle Database 10g: SQL Fundamentals I A - 11 e l rab fe
  • 134. SQL Star International Limited Practice 3: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 13. Using the DECODE function, write a query that displays the grade of all employees based on the value of the column JOB_ID, using the following data: Job Grade AD_PRES A ST_MAN B IT_PROG C SA_REP D ST_CLERK E None of the above 0 SELECT job_id, decode (job_id, 'ST_CLERK', 'SA_REP', 'IT_PROG', 'ST_MAN', 'AD_PRES', '0')GRADE FROM employees; 'E', 'D', 'C', 'B', 'A', s FROM employees; Oracle Database 10g: SQL Fundamentals I A - 12 n -tra n o an has ฺ ) comGuide ailฺ nt m d @g using e CASE syntax. 14. Rewrite the statement in the precedingtexercise tu the nc is S a SELECT job_id, CASE job_id mh se th si u WHENa r 'ST_CLERK' THEN 'E' na 'SA_REP' THEN 'D' (WHEN se to C WHEN 'IT_PROG' THEN 'C' AN licen 'ST_MAN' THEN 'B' WHEN H WHEN 'AD_PRES' THEN 'A' IM ELSE '0' END GRADE AS R NA e l rab fe
  • 135. SQL Star International Limited Practice 4: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Determine the validity of the following three statements. Circle either True or False. 1. Group functions work across many rows to produce one result per group. True/False 2. Group functions include nulls in calculations. True/False 3. The WHERE clause restricts rows before inclusion in a group calculation. True/False e l rab fe The HR department needs the following reports: s n -tra n 4. Find the highest, lowest, sum, and average salary of all employees. Label the columns Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest whole number. Place your SQL statement in a text file named lab_04_04.sql. NA R o an SELECT ROUND(MAX(salary),0) "Maximum", has ฺ ) ROUND(MIN(salary),0) "Minimum", comGuide ROUND(SUM(salary),0) "Sum", ilฺ t ROUND(AVG(salary),0) "Average" a m n FROM employees; @g tude t anc this S the minimum, maximum, sum, and 5. Modify the query in lab_04_04.sql to display imh Resave lab_04_04.sql as lab_04_05.sql. Run the s average salary for each job type.use ara to n statement in lab_04_05.sql. C ( ense SELECT AN ROUND(MAX(salary),0) "Maximum", H job_id,lic ROUND(MIN(salary),0) "Minimum", SIM ROUND(SUM(salary),0) "Sum", A ROUND(AVG(salary),0) "Average" FROM employees GROUP BY job_id; 6. Write a query to display the number of people with the same job. SELECT job_id, COUNT(*) FROM employees GROUP BY job_id; Generalize the query so that the user in the HR department is prompted for a job title. Save the script to a file named lab_04_06.sql. SELECT job_id, COUNT(*) FROM employees WHERE job_id = '&job_title' GROUP BY job_id; Oracle Database 10g: SQL Fundamentals I A - 13
  • 136. SQL Star International Limited Practice 4: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 7. Determine the number of managers without listing them. Label the column Number of Managers. Hint: Use the MANAGER_ID column to determine the number of managers. SELECT COUNT(DISTINCT manager_id) "Number of Managers" FROM employees; 8. Find the difference between the highest and lowest salaries. Label the column DIFFERENCE. SELECT FROM MAX(salary) - MIN(salary) DIFFERENCE employees; e l rab fe If you have time, complete the following exercises: s n -tra n 9. Create a report to display the manager number and the salary of the lowest-paid employee for that manager. Exclude anyone whose manager is not known. Exclude any groups where the minimum salary is $6,000 or less. Sort the output in descending order of salary. o an has ฺ SELECT manager_id, MIN(salary) ) FROM employees comGuide WHERE manager_id IS NOT NULL ailฺ nt m GROUP BY manager_id HAVING MIN(salary) > 6000 @g tude t S ORDER BY MIN(salary) DESC; anc h his t m asi use If you want an extra challenge, complete the following exercises: r (na se to 10. Create aN C that displays the total number of employees and, of that total, the number of query n A employees hiredic 1995, 1996, 1997, and 1998. Create appropriate column headings. l ine IMH COUNT(*) total, SELECT AS R NA FROM SUM(DECODE(TO_CHAR(hire_date, SUM(DECODE(TO_CHAR(hire_date, SUM(DECODE(TO_CHAR(hire_date, SUM(DECODE(TO_CHAR(hire_date, employees; 'YYYY'),1995,1,0))"1995", 'YYYY'),1996,1,0))"1996", 'YYYY'),1997,1,0))"1997", 'YYYY'),1998,1,0))"1998" Oracle Database 10g: SQL Fundamentals I A - 14
  • 137. SQL Star International Limited Practice 4: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 11. Create a matrix query to display the job, the salary for that job based on the department number, and the total salary for that job, for departments 20, 50, 80, and 90, giving each column an appropriate heading. SELECT job_id "Job", SUM(DECODE(department_id SUM(DECODE(department_id SUM(DECODE(department_id SUM(DECODE(department_id SUM(salary) "Total" FROM employees GROUP BY job_id; , , , , 20, 50, 80, 90, salary)) salary)) salary)) salary)) "Dept "Dept "Dept "Dept 20", 50", 80", 90", e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I A - 15
  • 138. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 5: Solutions 1. Write a query for the HR department to produce the addresses of all the departments. Use the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or province, and country in the output. Use a NATURAL JOIN to produce the results. SELECT location_id, street_address, city, state_province, country_name FROM locations NATURAL JOIN countries; 2. The HR department needs a report of all employees. Write a query to display the last name, department number, and department name for all employees. SELECT last_name, department_id, department_name FROM employees JOIN departments USING (department_id); e l rab fe s n -tra n o an has ฺ ) SELECT e.last_name, e.job_id, e.department_id, d.department_name comGuide FROM employees e JOIN departments d ailฺ ON (e.department_id = d.department_id) nt m JOIN locations l @g tude t ON (d.location_id = l.location_id) anc this S WHERE LOWER(l.city) = 'toronto'; imh se s ara theo uname and employee number of employees along with their 4. Create a report ton display t last C ( e ande manager’s last name ns manager number. Label the columns Employee, Emp#, N Mgr#, respectively. Place your SQL statement in a text file named Manager, andlic HA IM AS lab_05_04.sql. 3. The HR department needs a report of employees in Toronto. Display the last name, job, department number, and department name for all employees who work in Toronto. R NA SELECT w.last_name "Employee", w.employee_id "EMP#", m.last_name "Manager", m.employee_id "Mgr#" FROM employees w join employees m ON (w.manager_id = m.employee_id); 5. Modify lab_05_04.sql to display all employees, including King, who has no manager. Order the results by the employee number. Place your SQL statement in a text file named lab_05_05.sql. Run the query in lab_05_05.sql. SELECT w.last_name "Employee", w.employee_id "EMP#", m.last_name "Manager", m.employee_id "Mgr#" FROM employees w LEFT OUTER JOIN employees m ON (w.manager_id = m.employee_id); Oracle Database 10g: SQL Fundamentals I A - 16
  • 139. SQL Star International Limited Practice 5: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 6. Create a report for the HR department that displays employee last names, department numbers, and all the employees who work in the same department as a given employee. Give each column an appropriate label. Save the script to a file named lab_05_06.sql. SELECT e.department_id department, e.last_name employee, c.last_name colleague FROM employees e JOIN employees c ON (e.department_id = c.department_id) WHERE e.employee_id <> c.employee_id ORDER BY e.department_id, e.last_name, c.last_name; 7. The HR department needs a report on job grades and salaries. To familiarize yourself with the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then create a query that displays the name, job, department name, salary, and grade for all employees. s n -tra n DESC JOB_GRADES o an SELECT e.last_name, e.job_id, d.department_name, has ฺ e.salary, j.grade_level ) FROM employees e JOIN departments d comGuide ON (e.department_id = d.department_id) ailฺ nt JOIN job_grades j m e ON (e.salary BETWEEN j.lowest_sal AND d @g tu j.highest_sal); t anc this S h If you want an extra challenge,m i complete the following exercises: ras to use 8. The HR department wants to determine the names of all employees who were hired after (na se Davies. N C a query to display the name and hire date of any employee hired after ACreate licen employee Davies. IMH e.last_name, e.hire_date SELECT AS R NA FROM ON WHERE employees e JOIN employees davies (davies.last_name = 'Davies') davies.hire_date < e.hire_date; 9. The HR department needs to find the names and hire dates for all employees who were hired before their managers, along with their managers’ names and hire dates. Save the script to a file named lab_05_09.sql. SELECT w.last_name, w.hire_date, m.last_name, m.hire_date FROM employees w JOIN employees m ON (w.manager_id = m.employee_id) WHERE w.hire_date < m.hire_date; Oracle Database 10g: SQL Fundamentals I A - 17 e l rab fe
  • 140. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 6: Solutions 1. The HR department needs a query that prompts the user for an employee last name. The query then displays the last name and hire date of any employee in the same department as the employee whose name the user supplies (excluding that employee). For example, if the user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey). UNDEFINE Enter_name SELECT last_name, hire_date FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE last_name = '&&Enter_name') AND last_name <> '&Enter_name'; e l rab fe s n -tra n 2. Create a report that displays the employee number, last name, and salary of all employees who earn more than the average salary. Sort the results in ascending order by salary. NA R o an SELECT employee_id, last_name, salary has ฺ FROM employees ) WHERE salary > (SELECT AVG(salary) comGuide FROM employees) ailฺ nt ORDER BY salary; m @g tude t 3. Write a query that displays the employee number and last name of all employees who work anc this S in a department with any employee whose last name contains a u. Place your SQL statement imh se s u in a text file namedara lab_06_03.sql. Run your query. (n se to C SELECT employee_id, last_name FROM employees AN licen WHEREH department_id IN (SELECT department_id IM FROM employees AS WHERE last_name like '%u%'); 4. The HR department needs a report that displays the last name, department number, and job ID of all employees whose department location ID is 1700. SELECT last_name, department_id, job_id FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = 1700); Modify the query so that the user is prompted for a location ID. Save this to a file named lab_06_04.sql. SELECT last_name, department_id, job_id FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = &Enter_location); Oracle Database 10g: SQL Fundamentals I A - 18
  • 141. SQL Star International Limited Practice 6: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 5. Create a report for the HR department that displays the last name and salary of every employee who reports to King. SELECT last_name, salary FROM employees WHERE manager_id = (SELECT employee_id FROM employees WHERE last_name = 'King'); 6. Create a report for the HR department that displays the department number, last name, and job ID for every employee in the Executive department. SELECT department_id, last_name, job_id FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE department_name = 'Executive'); e s n -tra n o an If you have time, complete the following exercise: has ฺ ) om uide cemployee number, last name, and 7. Modify the query in lab_06_03.sql to display ithe a lฺ nt Gand who work in a department salary of all employees who earn more thangm the average salary @ a u.tResave lab_06_03.sql to ude with any employee whose last name ct contains S lab_06_07.sql. Run the statement in lab_06_07.sql. han this im se SELECT employee_id,as last_name, salary r u FROM employees a (n se to C WHERE department_id IN (SELECT department_id FROM employees AN licen H WHERE last_name like '%u%') IM salary > (SELECT AVG(salary) AND AS R NA l rab fe FROM employees); Oracle Database 10g: SQL Fundamentals I A - 19
  • 142. SQL Star International Limited Practice 7: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 1. The HR department needs a list of department IDs for departments that do not contain the job ID ST_CLERK. Use set operators to create this report. SELECT FROM MINUS SELECT FROM WHERE department_id departments department_id employees job_id = 'ST_CLERK'; 2. The HR department needs a list of countries that have no departments located in them. Display the country ID and the name of the countries. Use set operators to create this report. SELECT country_id, country_name FROM countries MINUS SELECT country_id, country_name FROM countries NATURAL JOIN locations NATURAL JOIN departments; o an has ฺ ) comGuide ailฺin nt order. Display the job ID and 3. Produce a list of jobs for departments 10, 50, m 20, that and department ID using set operators. @g tude t anc this S COLUMN dummy NOPRINT imh se SELECT job_id, department_id, 'x' dummy s FROM employees r a a to u n WHERE department_id se10 C ( en = UNION N lic HA SELECT job_id, department_id, 'y' dummy IM employees FROM AS R NA s n -tra n WHERE department_id = 50 UNION SELECT job_id, department_id, 'z' dummy FROM employees WHERE department_id = 20 ORDER BY dummy; COLUMN dummy PRINT 4. Create a report that lists the employee ID and job ID of those employees who currently have a job title that is the same as their job title when they were initially hired by the company (that is, they changed jobs but have now gone back to doing their original job). SELECT employee_id,job_id FROM employees INTERSECT SELECT employee_id,job_id FROM job_history; Oracle Database 10g: SQL Fundamentals I A - 20 e l rab fe
  • 143. SQL Star International Limited Practice 7: Solutions (continued) 5. The HR department needs a report with the following specifications: Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. • Last name and department ID of all the employees from the EMPLOYEES table, regardless of whether or not they belong to a department • Department ID and department name of all the departments from the DEPARTMENTS table, regardless of whether or not they have employees working in them Write a compound query to accomplish this. SELECT last_name,department_id,TO_CHAR(null) FROM employees UNION SELECT TO_CHAR(null),department_id,department_name FROM departments; e s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I A - 21 l rab fe
  • 144. SQL Star International Limited Practice 8: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. The HR department wants you to create SQL statements to insert, update, and delete employee data. As a prototype, you use the MY_EMPLOYEE table, before giving the statements to the HR department. Insert data into the MY_EMPLOYEE table. 1. Run the statement in the lab_08_01.sql script to build the MY_EMPLOYEE table to be used for the lab. CREATE TABLE my_employee (id NUMBER(4) CONSTRAINT my_employee_id_nn NOT NULL, last_name VARCHAR2(25), first_name VARCHAR2(25), userid VARCHAR2(8), salary NUMBER(9,2)); e l rab fe s n -tra n o an has ฺ DESCRIBE my_employee ) comGuide lฺ 3. Create an INSERT statement to add the first rowai data to the MY_EMPLOYEE table from of gm dent the following sample data. Do not list the columns in the INSERT clause. @ nct is Stu a th ID LAST_NAME SALARY mh seFIRST_NAME USERID asi u ar (nPatel to e 1 Ralph rpatel 895 N C licens HA 2 Dancs Betty bdancs 860 IM AS 2. Describe the structure of the MY_EMPLOYEE table to identify the column names. R NA 3 Biri Ben bbiri 4 Newman Chad cnewman 5 Ropeburn Audrey aropebur INSERT INTO my_employee VALUES (1, 'Patel', 'Ralph', 'rpatel', 895); Oracle Database 10g: SQL Fundamentals I A - 22 1100 750 1550
  • 145. SQL Star International Limited Practice 8: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 4. Populate the MY_EMPLOYEE table with the second row of sample data from the preceding list. This time, list the columns explicitly in the INSERT clause. INSERT INTO my_employee (id, last_name, first_name, userid, salary) VALUES (2, 'Dancs', 'Betty', 'bdancs', 860); 5. Confirm your addition to the table. SELECT FROM * my_employee; s n -tra n NA R o an SET ECHO OFF has ฺ SET VERIFY OFF ) INSERT INTO my_employee comGuide VALUES (&p_id, '&&p_last_name', '&&p_first_name', ailฺ nt lower(substr('&p_first_name', 1, 1) || gm &p_salary); e substr('&p_last_name', t@ 1, 7)), tud c S SET VERIFY ON han this SET ECHO ON m UNDEFINE p_first_name asi use r UNDEFINE p_last_name (na se to C en AN table with the next two rows of sample data listed in step 3 by running the 7. Populate the lic IMH statement in the script that you created. INSERT AS SET ECHO OFF SET VERIFY OFF INSERT INTO my_employee VALUES (&p_id, '&&p_last_name', '&&p_first_name', lower(substr('&p_first_name', 1, 1) || substr('&p_last_name', 1, 7)), &p_salary); SET VERIFY ON SET ECHO ON UNDEFINE p_first_name UNDEFINE p_last_name 8. Confirm your additions to the table. SELECT * FROM my_employee; 9. Make the data additions permanent. COMMIT; Oracle Database 10g: SQL Fundamentals I A - 23 e l rab fe 6. Write an INSERT statement in a dynamic reusable script file named loademp.sql to load rows into the MY_EMPLOYEE table. Concatenate the first letter of the first name and the first seven characters of the last name to produce the user ID. Save this script to a file named lab_08_06.sql.
  • 146. SQL Star International Limited Practice 8: Solutions (continued) Update and delete data in the MY_EMPLOYEE table. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 10. Change the last name of employee 3 to Drexler. UPDATE SET WHERE my_employee last_name = 'Drexler' id = 3; 11. Change the salary to $1,000 for all employees with a salary less than $900. UPDATE SET WHERE my_employee salary = 1000 salary < 900; e s n -tra n 12. Verify your changes to the table. R NA o an has ฺ ) 13. Delete Betty Dancs from the MY_EMPLOYEE table. comGuide DELETE ailฺ nt m FROM my_employee @g tude t WHERE last_name = 'Dancs'; anc this S h 14. Confirm your changes tosim the table. e s a nar e to u SELECT * C ( ens FROM my_employee; N lic HA I Commit all pending changes. 15. M AS SELECT FROM last_name, salary my_employee; l rab fe COMMIT; Control data transaction to the MY_EMPLOYEE table. 16. Populate the table with the last row of sample data listed in step 3 by using the statements in the script that you created in step 6. Run the statements in the script. SET ECHO OFF SET VERIFY OFF INSERT INTO my_employee VALUES (&p_id, '&&p_last_name', '&&p_first_name', lower(substr('&p_first_name', 1, 1) || substr('&p_last_name', 1, 7)), &p_salary); SET VERIFY ON SET ECHO ON UNDEFINE p_first_name UNDEFINE p_last_name Oracle Database 10g: SQL Fundamentals I A - 24
  • 147. SQL Star International Limited Practice 8: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 17. Confirm your addition to the table. SELECT FROM * my_employee; 18. Mark an intermediate point in the processing of the transaction. SAVEPOINT step_18; 19. Empty the entire table. DELETE FROM my_employee; 20. Confirm that the table is empty. s n -tra n o an s haearlier INSERT operation. ) 21. Discard the most recent DELETE operation without discarding the ฺ comGuide ROLLBACK TO step_18; ailฺ nt m @g tude t 22. Confirm that the new row is still intact. anc this S SELECT * imh se FROM my_employee;as r u (na se to C 23. Make the data addition permanent. AN licen COMMIT; IMH AS SELECT * FROM my_employee; R NA e l rab fe Oracle Database 10g: SQL Fundamentals I A - 25
  • 148. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 9: Solutions 1. Create the DEPT table based on the following table instance chart. Place the syntax in a script called lab_09_01.sql, and then execute the statement in the script to create the table. Confirm that the table is created. CREATE TABLE dept (id NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY, name VARCHAR2(25)); DESCRIBE dept 2. Populate the DEPT table with data from the DEPARTMENTS table. Include only columns that you need. INSERT INTO dept SELECT department_id, department_name FROM departments; no athe syntax in 3. Create the EMP table based on the following table instance chart. as h Placeฺ script to create the ) a script called lab_09_03.sql, and then execute the statement in the comGuide table. Confirm that the table is created. ailฺ nt m CREATE TABLE emp @g tude (id NUMBER(7), t last_name VARCHAR2(25), anc this S first_name VARCHAR2(25), imh se s dept_id NUMBER(7) ara to u REFERENCES dept (id) CONSTRAINT n emp_dept_id_FK C ( ense ); N HA emp lic DESCRIBE IM AS R NA s n -tra n 4. 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. CREATE TABLE employees2 AS SELECT employee_id id, first_name, last_name, salary, department_id dept_id FROM employees; 5. Drop the EMP table. DROP TABLE emp; Oracle Database 10g: SQL Fundamentals I A - 26 e l rab fe
  • 149. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 10: Solutions Part 1 1. The staff in the HR department wants to hide some of the data in the EMPLOYEES table. They want a view called EMPLOYEES_VU based on the employee numbers, employee last names, and department numbers from the EMPLOYEES table. They want the heading for the employee name to be EMPLOYEE. CREATE OR REPLACE VIEW employees_vu AS SELECT employee_id, last_name employee, department_id FROM employees; 2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view. SELECT FROM * employees_vu; s n -tra n o an has ฺ SELECT employee, department_id ) FROM employees_vu; comGuide ailฺ nt gm d 4. Department 50 needs access to its employee data. Create a view named DEPT50 that @last names,e department numbers for all t contains the employee numbers, employee Stu and anc this that you label the view columns employees in department 50. They have requested imh se security purposes, do not allow an employee to be EMPNO, EMPLOYEE,rand DEPTNO. For as u a department through the view. reassigned to another (n se to C e AS CREATE AN dept50n VIEW lic H SELECT employee_id empno, last_name employee, IM department_id deptno AS 3. Using your EMPLOYEES_VU view, write a query for the HR department to display all employee names and department numbers. R NA e l rab fe FROM employees WHERE department_id = 50 WITH CHECK OPTION CONSTRAINT emp_dept_50; 5. Display the structure and contents of the DEPT50 view. DESCRIBE dept50 SELECT FROM * dept50; 6. Test your view. Attempt to reassign Matos to department 80. UPDATE SET WHERE dept50 deptno = 80 employee = 'Matos'; The error is due to the fact that the view “DEPT50” is created with CHECK OPTION CONSTRAINT. This ensures that the deptno column in the view is protected from being changed. Oracle Database 10g: SQL Fundamentals I A - 27
  • 150. SQL Star International Limited Practice 10: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. You cannot make modifications to the deptno column that will result in the row being removed from the view. Part 2 7. You need a sequence that can be used with the primary key column of the DEPT table. The sequence should start at 200 and have a maximum value of 1000. Have your sequence increment by 10. Name the sequence DEPT_ID_SEQ. CREATE SEQUENCE dept_id_seq START WITH 200 INCREMENT BY 10 MAXVALUE 1000; s tran 8. To test your sequence, write a script to insert two rows in the DEPT table. Name your script non Add two lab_10_08.sql. Be sure to use the sequence that you created for the ID column. a departments: Education and Administration. Confirm your additions. Run the commands in as h your script. m) ideฺ o ilฺc t Gu INSERT INTO dept a VALUES (dept_id_seq.nextval, 'Education');en gm d @ nct is Stu INSERT INTO dept a VALUES (dept_id_seq.nextval, 'Administration'); mh se th i ras to u (na se 9. Create a nonunique index on the NAME column in the DEPT table. C n CREATE AN dept_name_idx ON dept (name); INDEX lice IMH AS Create a synonym for your EMPLOYEES table. Call it EMP. 10. R NA CREATE SYNONYM emp FOR EMPLOYEES; Oracle Database 10g: SQL Fundamentals I A - 28 e l rab fe
  • 151. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice 11: Solutions 1. For a specified table, create a script that reports the column names, data types, and lengths of data types, as well as whether nulls are allowed. Prompt the user to enter the table name. Give appropriate aliases to the columns DATA_PRECISION and DATA_SCALE. Save this script in a file named lab_11_01.sql. SELECT column_name, data_type, data_length, data_precision PRECISION, data_scale SCALE, nullable FROM user_tab_columns WHERE table_name = UPPER('&tab_name'); 2. 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 of this information. Prompt the user to enter the table name. Save the script in a file named lab_11_02.sql. e l rab fe s tran SELECT ucc.column_name, uc.constraint_name, uc.constraint_type, non uc.search_condition, uc.status a FROM user_constraints uc JOIN user_cons_columns ucc as h ON uc.table_name = ucc.table_name m) ideฺ o AND uc.constraint_name = ucc.constraint_name u ilฺc t G a AND uc.table_name = UPPER('&tab_name'); gm den @ 3. Add a comment to the DEPARTMENTS table. Then query the USER_TAB_COMMENTS view nct is Stu a to verify that the comment is present. th mh se si u COMMENT ON TABLE ara departments IS (n s to 'Company departmenteinformation including name, code, and location.'; C AN licen SELECT COMMENTS IMH user_tab_comments FROM AS WHERE table_name = 'DEPARTMENTS'; R NA 4. Find the names of all synonyms that are in your schema. SELECT * FROM user_synonyms; Oracle Database 10g: SQL Fundamentals I A - 29
  • 152. SQL Star International Limited Practice 11: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 5. You need to determine the names and definitions of all the views in your schema. Create a report that retrieves view information (the view name and text) from the USER_VIEWS data dictionary view. Note: Another view already exists. The EMP_DETAILS_VIEW was created as part of your schema. Also, if you completed practice 10, you see the DEPT50 view. Note: 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. SET LONG 600 SELECT FROM e view_name, text user_views; s n -tra n o an has ฺ ) comGuide SELECT sequence_name, max_value, increment_by, last_number ailฺ nt FROM user_sequences; m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM AS l rab fe 6. 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_11_06.sql. Run the statement in your script. R NA Oracle Database 10g: SQL Fundamentals I A - 30
  • 153. SQL Star International Limited Practice C: Solutions Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 1. Write a query for the HR department to produce the addresses of all the departments. Use the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or province, and country in the output. SELECT location_id, street_address, city, state_province, country_name FROM locations, countries WHERE locations.country_id = countries.country_id; 2. The HR department needs a report of all employees. Write a query to display the last name, department number, and department name for all employees. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id; s tran 3. The HR department needs a report of employees in Toronto. Display the last name, job, non department number, and department name for all employees who work in Toronto. a as SELECT e.last_name, e.job_id, e.department_id, d.department_name h FROM employees e, departments d , locations l m) ideฺ o u WHERE e.department_id = d.department_idilฺc AND d.location_id = l.location_idma nt G g e AND LOWER(l.city) = 'toronto'; ct@ Stud han his 4. Create a report to display the employeetlast name and employee number along with the last im se amanager and the manager number. Label the columns Employee, name of the employee’s s r u Emp#, Manager, and Mgr#, respectively. Place your SQL statement in a text file named (na se to C lab_c_04.sql. en AN lic SELECT w.last_name "Employee", w.employee_id "EMP#", IMH m.last_name "Manager", m.employee_id "Mgr#" AS R NA FROM WHERE employees w, employees m w.manager_id = m.employee_id; 5. Modify lab_c_04.sql to display all employees, including King, who has no manager. Order the results by the employee number. Place your SQL statement in a text file named lab_c_05.sql. Run the query in lab_c_05.sql. SELECT w.last_name "Employee", w.employee_id "EMP#", m.last_name "Manager", m.employee_id "Mgr#" FROM employees w, employees m WHERE w.manager_id = m.employee_id (+); Oracle Database 10g: SQL Fundamentals I A - 31 e l rab fe
  • 154. SQL Star International Limited Practice C: Solutions (continued) Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 6. Create a report for the HR department that displays employee last names, department numbers, and all the employees who work in the same department as a given employee. Give each column an appropriate label. Save the script to a file named lab_c_06.sql. SELECT e.department_id department, e.last_name employee, c.last_name colleague FROM employees e, employees c WHERE e.department_id = c.department_id AND e.employee_id <> c.employee_id ORDER BY e.department_id, e.last_name, c.last_name; 7. The HR department needs a report on job grades and salaries. To familiarize yourself with the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then create a query that displays the name, job, department name, salary, and grade for all employees. s n -tra n DESC JOB_GRADES o an SELECT e.last_name, e.job_id, d.department_name, has ฺ e.salary, j.grade_level ) FROM employees e, departments d, job_grades j comGuide WHERE e.department_id = d.department_idilฺ a j.highest_sal; AND e.salary BETWEEN j.lowest_salm g AND dent @ tu nct following exercises: If you want an extra challenge, complete the is S a mh se th i 8. The HR department wants to determine the names of all employees hired after Davies. Create ras to u (na se a query to display the name and hire date of any employee hired after employee Davies. C en SELECT AN e.last_name, e.hire_date lic FROM H employees e , employees davies IM WHERE davies.last_name = 'Davies' AS R NA AND davies.hire_date < e.hire_date; 9. The HR department needs to find the names and hire dates for all employees who were hired before their managers, along with their manager’s names and hire dates. Label the columns Employee, Emp Hired, Manager, and Mgr Hired, respectively. Save the script to a file named lab_c_09.sql. SELECT FROM WHERE AND w.last_name, w.hire_date, m.last_name, m.hire_date employees w , employees m w.manager_id = m.employee_id w.hire_date < m.hire_date; Oracle Database 10g: SQL Fundamentals I A - 32 e l rab fe
  • 155. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited B Table Descriptions and Data e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 156. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Human Resources (HR) Data Set e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA JOB_GRADES GRADE_LEVEL LOWEST_SAL HIGHEST_SAL Oracle Database 10g: SQL Fundamentals I B - 2
  • 157. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Human Resources (HR) Data Set The Human Resources (HR) schema is part of the Oracle Common Schema that can be installed in an Oracle Database. The practices in this course use the data from the HR schema. Table Descriptions REGIONS contains rows representing a region (such as Americas, Asia, and so on). COUNTRIES contains rows for countries, each of which are associated with a region. LOCATIONS contains the addresses of specific offices, warehouses, and/or production sites of a company in a particular country. DEPARTMENTS shows details of the departments in which employees work. Each department can have a relationship representing the department manager in the EMPLOYEES table. EMPLOYEES contains details about each employee who works for a department. Some employees may not be assigned to any department. JOBS contains the job types that can be held by each employee. JOB_HISTORY contains the job history of the employees. If an employee changes departments within the job or changes jobs within the department, a new row is inserted in this table with the old job information of the employee. JOB_GRADES identifies a salary range per job grade. The salary ranges do not overlap. s o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 3 e l rab fe
  • 158. SQL Star International Limited COUNTRIES Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE countries SELECT * FROM countries; e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 4
  • 159. SQL Star International Limited DEPARTMENTS Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE departments SELECT * FROM departments; e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 5
  • 160. SQL Star International Limited EMPLOYEES Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE employees e s l rab fe o n -tra n an has ฺ SELECT * FROM employees; ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM AS R NA Oracle Database 10g: SQL Fundamentals I B - 6
  • 161. SQL Star International Limited JOBS Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE jobs e SELECT * FROM jobs; s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 7 l rab fe
  • 162. SQL Star International Limited JOB_GRADES Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE job_grades SELECT * FROM job_grades; e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 8
  • 163. SQL Star International Limited JOB_HISTORY Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE job_history e SELECT * FROM job_history; s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 9 l rab fe
  • 164. SQL Star International Limited LOCATIONS Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE locations e s n -tra n SELECT * FROM locations; o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 10 l rab fe
  • 165. SQL Star International Limited REGIONS Table Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DESCRIBE regions SELECT * FROM regions; e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I B - 11
  • 166. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 167. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Oracle Join Syntax e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 168. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Objectives After completing this lesson, you should be able to do the following: • Write SELECT statements to access data from more than one table using equijoins and nonequijoins • Use outer joins to view data that generally does not meet a join condition e abl • Join a table to itself by using a self-join fer s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Objectives IMHexplains how to obtain data from more than one table. A join is used to view information S This lesson RA multiple tables. Therefore, you can join tables together to view information from more than one NA from table. Note: Information on joins is found in “SQL Queries and Subqueries: Joins” in Oracle SQL Reference. Oracle Database 10g: SQL Fundamentals I C - 2
  • 169. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … e l rab fe s n -tra n o an has ฺ ) … comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Tables Data from H Multiple lic IM Sometimes you need to use data from more than one table. In the slide example, the report displays AS R NA data from two separate tables: • Employee IDs exist in the EMPLOYEES table. • Department IDs exist in both the EMPLOYEES and DEPARTMENTS tables. • Department names exist in the DEPARTMENTS table. To produce the report, you need to link the EMPLOYEES and DEPARTMENTS tables and access data from both of them. Oracle Database 10g: SQL Fundamentals I C - 3
  • 170. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Cartesian Products • A Cartesian product is formed when: – A join condition is omitted – A join condition is invalid – All rows in the first table are joined to all rows in the second table • To avoid a Cartesian product, always include a valid join condition in a WHERE clause. e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Cartesian H Products IaM condition is invalid or omitted completely, the result is a Cartesian product, in which all S When join RA NA combinations of rows are displayed. All rows in the first table are joined to all rows in the second table. A Cartesian product tends to generate a large number of rows, and the result is rarely useful. You should always include a valid join condition unless you have a specific need to combine all rows from all tables. Cartesian products are useful for some tests when you need to generate a large number of rows to simulate a reasonable amount of data. Oracle Database 10g: SQL Fundamentals I C - 4
  • 171. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Generating a Cartesian Product EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … e l rab fe s n -tra n o an has ฺ … ) Cartesian product: comGuide 20 x 8 = 160 rows ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN l(continued) Cartesian H Products ic IM A Cartesian product is generated if a join condition is omitted. The example in the slide displays AS last name and department name from the EMPLOYEES and DEPARTMENTS tables. R NA employee Because no join condition has been specified, all rows (20 rows) from the EMPLOYEES table are joined with all rows (8 rows) in the DEPARTMENTS table, thereby generating 160 rows in the output. SELECT last_name, department_name dept_name FROM employees, departments; … Oracle Database 10g: SQL Fundamentals I C - 5
  • 172. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Types of Joins Oracle-proprietary joins (8i and earlier releases) SQL:1999–compliant joins • • • • • • • • Equijoin Nonequijoin Outer join Self-join • Cross join Natural join Using clause e abl r Full (or two-sided) nsfe a outer join n-tr o Arbitrary join condition an has ฺ for outer join ) N m e ฺco Guid il t a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Types of Joins IMH S Before the release of Oracle9i Database, the join syntax was proprietary. RA The SQL:1999–compliant join syntax does not offer any performance benefits over the OracleA Note: proprietary join syntax that existed in prior releases. For detailed information about the SQL:1999– compliant join syntax, see Lesson 5. Oracle Database 10g: SQL Fundamentals I C - 6
  • 173. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Joining Tables Using Oracle Syntax Use a join to query data from more than one table: SELECT FROM WHERE table1.column, table2.column table1, table2 table1.column1 = table2.column2; Write the join condition in the WHERE clause. e • l rab fe • Prefix the column name with the table name when the ns a same column name appears in more than one table.tr no an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Defining Joins MH Idata from more than one table in the database is required, a join condition is used. Rows in one S When RA can be joined to rows in another table according to common values that exist in corresponding NA table columns (that is, usually primary and foreign key columns). To display data from two or more related tables, write a simple join condition in the WHERE clause. In the syntax: table1.column table1.column1 = table2.column2 denotes the table and column from which data is retrieved is the condition that joins (or relates) the tables together Guidelines • When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access. • If the same column name appears in more than one table, the column name must be prefixed with the table name. • To join n tables together, you need a minimum of n-1 join conditions. For example, to join four tables, a minimum of three joins is required. This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row. Oracle Database 10g: SQL Fundamentals I C - 7
  • 174. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Equijoins EMPLOYEES DEPARTMENTS e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t Foreign key nc Primary key a this S h m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C AN licen Equijoins H IM To determine an employee’s department name, you compare the value in the DEPARTMENT_ID AS in the EMPLOYEES table with the DEPARTMENT_ID values in the DEPARTMENTS table. R NA column The relationship between the EMPLOYEES and DEPARTMENTS tables is an equijoin—that is, values in the DEPARTMENT_ID column in both tables must be equal. Frequently, this type of join involves primary and foreign key complements. Note: Equijoins are also called simple joins or inner joins. Oracle Database 10g: SQL Fundamentals I C - 8
  • 175. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Retrieving Records with Equijoins SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id; e l rab fe s … n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C e AN lwith n RetrievingH Records ic Equijoins IM In the slide example: AS SELECT clause specifies the column names to retrieve: R NA • The - Employee last name, employee number, and department number, which are columns in the EMPLOYEES table - Department number, department name, and location ID, which are columns in the DEPARTMENTS table • The FROM clause specifies the two tables that the database must access: - EMPLOYEES table - DEPARTMENTS table • The WHERE clause specifies how the tables are to be joined: EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID Because the DEPARTMENT_ID column is common to both tables, it must be prefixed by the table name to avoid ambiguity. Oracle Database 10g: SQL Fundamentals I C - 9
  • 176. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Additional Search Conditions Using the AND Operator EMPLOYEES DEPARTMENTS e l rab fe s n -tra n o an … … has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Conditions AdditionalH Search lic IM In addition to the join, you may have criteria for your WHERE clause to restrict the rows under AS R NA consideration for one or more tables in the join. For example, to display employee Matos’s department number and department name, you need an additional condition in the WHERE clause. SELECT last_name, employees.department_id, department_name FROM employees, departments WHERE employees.department_id = departments.department_id AND last_name = 'Matos'; Oracle Database 10g: SQL Fundamentals I C - 10
  • 177. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Qualifying Ambiguous Column Names • • • Use table prefixes to qualify column names that are in multiple tables. Use table prefixes to improve performance. Use column aliases to distinguish columns that have identical names but reside in different tables. e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen QualifyingH Ambiguous Column Names IM to qualify the names of the columns in the WHERE clause with the table name to avoid S You need RA ambiguity. Without the table prefixes, the DEPARTMENT_ID column could be from either the NA DEPARTMENTS table or the EMPLOYEES table. It is necessary to add the table prefix to execute your query. If there are no common column names between the two tables, there is no need to qualify the columns. However, using the table prefix improves performance, because you tell the Oracle server exactly where to find the columns. The requirement to qualify ambiguous column names is also applicable to columns that may be ambiguous in other clauses, such as the SELECT clause or the ORDER BY clause. Oracle Database 10g: SQL Fundamentals I C - 11
  • 178. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using Table Aliases • • Use table aliases to simplify queries. Use table prefixes to improve performance. SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e , departments d WHERE e.department_id = d.department_id; e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Using Table Aliases IMH S Qualifying column names with table names can be very time consuming, particularly if table names RA lengthy. You can use table aliases instead of table names. Just as a column alias gives a column NA are another name, a table alias gives a table another name. Table aliases help to keep SQL code smaller, therefore using less memory. Notice how table aliases are identified in the FROM clause in the example. The table name is specified in full, followed by a space and then the table alias. The EMPLOYEES table has been given an alias of e, and the DEPARTMENTS table has an alias of d. Guidelines • Table aliases can be up to 30 characters in length, but shorter aliases are better than longer ones. • If a table alias is used for a particular table name in the FROM clause, then that table alias must be substituted for the table name throughout the SELECT statement. • Table aliases should be meaningful. • The table alias is valid for only the current SELECT statement. Oracle Database 10g: SQL Fundamentals I C - 12
  • 179. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Joining More Than Two Tables EMPLOYEES DEPARTMENTS LOCATIONS e l rab fe s n -tra n N o an … has ฺ ) o ca mGuide n–1 To join n tables together, you need minimum of ailฺ nt m join conditions. For example, tode three tables, a @gjoinsuisjoin minimum ct two St of required. han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C en AN Conditions AdditionalH Search lic IM Sometimes you may need to join more than two tables. For example, to display the last name, the AS department name, and the city for each employee, you have to join the EMPLOYEES, AR DEPARTMENTS, and LOCATIONS tables. SELECT FROM WHERE AND e.last_name, d.department_name, l.city employees e, departments d, locations l e.department_id = d.department_id d.location_id = l.location_id; … Oracle Database 10g: SQL Fundamentals I C - 13
  • 180. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Nonequijoins EMPLOYEES JOB_GRADES e l rab fe s n -tra n … o Salary in the EMPLOYEES an table must bes between ha and highest ) lowest salary eฺ comGuid salary ailฺ ntin the JOB_GRADES gm table. e d @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen Nonequijoins IMH is a join condition containing something other than an equality operator. S A nonequijoin RA relationship between the EMPLOYEES table and the JOB_GRADES table is an example of a NA The nonequijoin. A relationship between the two tables is that the SALARY column in the EMPLOYEES table must be between the values in the LOWEST_SALARY and HIGHEST_SALARY columns of the JOB_GRADES table. The relationship is obtained using an operator other than equality (=). Oracle Database 10g: SQL Fundamentals I C - 14
  • 181. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Retrieving Records with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal; e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt … m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to N C licen A(continued) Nonequijoins MH TheSI example creates a nonequijoin to evaluate an employee’s salary grade. The salary must be slide A between any pair of the low and high salary ranges. AR N It is important to note that all employees appear exactly once when this query is executed. No employee is repeated in the list. There are two reasons for this: • None of the rows in the job grade table contain grades that overlap. That is, the salary value for an employee can lie only between the low salary and high salary values of one of the rows in the salary grade table. • All of the employees’ salaries lie within the limits that are provided by the job grade table. That is, no employee earns less than the lowest value contained in the LOWEST_SAL column or more than the highest value contained in the HIGHEST_SAL column. Note: Other conditions (such as <= and >=) can be used, but BETWEEN is the simplest. Remember to specify the low value first and the high value last when using BETWEEN. Table aliases have been specified in the slide example for performance reasons, not because of possible ambiguity. Oracle Database 10g: SQL Fundamentals I C - 15
  • 182. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Outer Joins DEPARTMENTS EMPLOYEES e l rab fe s n -tra n o an … has ฺ ) comGuide ailฺ nt There are no employees in m e d @g department 190. nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C e AN with n Direct Match with Outer Joins ReturningH Records lic No IM If a S does not satisfy a join condition, the row does not appear in the query result. For example, in row A equijoin condition of the EMPLOYEES and DEPARTMENTS tables, employee Grant does not R NA the appear because there is no department ID recorded for her in the EMPLOYEES table. Instead of seeing 20 employees in the result set, you see 19 records. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id; … Oracle Database 10g: SQL Fundamentals I C - 16
  • 183. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Outer Joins Syntax • • You use an outer join to see rows that do not meet the join condition. The outer join operator is the plus sign (+). SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column a as h FROM table1, table2 m) ideฺ o u WHERE table1.column = table2.column(+); ilฺc e l rab fe s n -tra n no G a gm dent @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN toicen Records with No Direct Match Using Outer Joins l Return IMH rows can be returned if an outer join operator is used in the join condition. The operator TheS missing RA plus sign enclosed in parentheses (+), and it is placed on the “side” of the join that is deficient in NA is a information. This operator has the effect of creating one or more null rows, to which one or more rows from the nondeficient table can be joined. In the syntax: table1.column = is the condition that joins (or relates) the tables together table2.column (+) is the outer join symbol, which can be placed on either side of the WHERE clause condition, but not on both sides. (Place the outer join symbol following the name of the column in the table without the matching rows.) Oracle Database 10g: SQL Fundamentals I C - 17
  • 184. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using Outer Joins SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; e l rab fe s … n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN toicen Records with No Direct Match (continued) Using Outer Joins l Return H IMexample displays employee last names, department IDs, and department names. The TheS slide RA NA Contracting department does not have any employees. The empty value is shown in the output. Outer Join Restrictions • The outer join operator can appear on only one side of the expression - the side that has information missing. It returns those rows from one table that have no direct match in the other table. • A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator. Oracle Database 10g: SQL Fundamentals I C - 18
  • 185. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Self-Joins EMPLOYEES (WORKER) EMPLOYEES (MANAGER) e l rab fe s n -tra n o an … … has ฺ ) comGuide ailฺ nt m e MANAGER_ID in @gWORKER table is equal to the ud nct i in the EMPLOYEE_IDs St MANAGER table. a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C e ANto Itself n Joining a Table lic H IM Sometimes you need to join a table to itself. To find the name of each employee’s manager, you need AS the EMPLOYEES table to itself; this type of join is called a self-join. R NA to join For example, to find the name of Lorentz’s manager, you need to do the following: • Find Lorentz in the EMPLOYEES table by looking at the LAST_NAME column. • Find the manager number for Lorentz by looking at the MANAGER_ID column. Lorentz’s manager number is 103. • Find the name of the manager who has EMPLOYEE_ID 103 by looking at the LAST_NAME column. Hunold’s employee number is 103, so Hunold is Lorentz’s manager. In this process, you look in the table twice. The first time you look in the table to find Lorentz in the LAST_NAME column and the MANAGER_ID value of 103. The second time you look in the EMPLOYEE_ID column to find 103 and the LAST_NAME column to find Hunold. Oracle Database 10g: SQL Fundamentals I C - 19
  • 186. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Joining a Table to Itself SELECT worker.last_name || ' works for ' || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ; e l rab fe s n -tra n o an has ฺ ) … comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en ANto Itself (continued) Joining a Table lic H M TheSI example joins the EMPLOYEES table to itself. To simulate two tables in the FROM clause, A slidetwo aliases, namely w and m, for the same table, EMPLOYEES. R NA there are In this example, the WHERE clause contains the join that means “where a worker’s manager number matches the employee number for the manager.” Oracle Database 10g: SQL Fundamentals I C - 20
  • 187. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Summary In this appendix, you should have learned how to use joins to display data from multiple tables by using Oracle-proprietary syntax for versions 8i and earlier. e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Summary H IM There are multiple ways to join tables. AS R NA Types of Joins • Cartesian products • Equijoins • Nonequijoins • Outer joins • Self-joins Cartesian Products A Cartesian product results in a display of all combinations of rows. This is done by omitting the WHERE clause. Table Aliases • Table aliases speed up database access. • Table aliases can help to keep SQL code smaller by conserving memory. Oracle Database 10g: SQL Fundamentals I C - 21
  • 188. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C: Overview This practice covers writing queries to join tables using Oracle syntax. e l rab fe s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Practice C: Overview IMH is designed to give you a variety of exercises that join tables using the Oracle syntax S This practice RA was covered in this appendix. NA that Oracle Database 10g: SQL Fundamentals I C - 22
  • 189. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C 1. Write a query for the HR department to produce the addresses of all the departments. Use the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or province, and country in the output. 2. The HR department needs a report of all employees. Write a query to display the last name, department number, and department name for all employees. s o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I C - 23 e l rab fe
  • 190. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C (continued) 3. The HR department needs a report of employees in Toronto. Display the last name, job, department number, and department name for all employees who work in Toronto. 4. Create a report to display the employee last name and employee number along with the employee’s manager’s last name and manager number. Label the columns Employee, Emp#, Manager, and Mgr#, respectively. Place your SQL statement in a text file named lab_c_04.sql. e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I C - 24
  • 191. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C (continued) 5. Modify lab_c_04.sql to display all employees including King, who has no manager. Order the results by the employee number. Place your SQL statement in a text file named lab_c_05.sql. Run the query in lab_c_05.sql. … e l rab fe s n -tra n no 6. Create a report for the HR department that displays employee lasts a department numbers, names, a employee. Give each and all the employees who work in the same department as ) given ah ฺ m lab_c_06.sql. column an appropriate label. Save the script to a file named o ide c ailฺ nt Gu m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM AS … R NA Oracle Database 10g: SQL Fundamentals I C - 25
  • 192. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C (continued) 7. The HR department needs a report on job grades and salaries. To familiarize yourself with the JOB_GRADES table, first show the structure of the JOB_GRADES table. Second, create a query that displays the last name, job, department name, salary, and grade for all employees. e s l rab fe o n -tra n an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I C - 26
  • 193. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Practice C (continued) If you want an extra challenge, complete the following exercises: 8. The HR department wants to determine the names of all employees hired after Davies. Create a query to display the name and hire date of any employee hired after employee Davies. e l rab fe s n -tra n 9. The HR department needs to find the name and hire date for all employees who were hired no a Label the columns before their managers, along with their manager’s name and hire date. Employee, Emp Hired, Manager, and Mgr Hired, respectively. Save the script to a file has ฺ ) named lab_c_09.sql. om ide c ailฺ nt Gu m @g tude t anc this S imh se s ara to u n C ( ense N lic HA IM S RA NA Oracle Database 10g: SQL Fundamentals I C - 27
  • 194. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 195. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Using SQL*Plus e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 196. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Objectives After completing this appendix, you should be able to do the following: • Log in to SQL*Plus • Edit SQL commands • Format output using SQL*Plus commands • Interact with script files e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Objectives IMHwant to create SELECT statements that can be used again and again. This appendix S You might RA also covers the use 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. Oracle Database 10g: SQL Fundamentals I D - 2
  • 197. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL and SQL*Plus Interaction SQL statements Server SQL*Plus e l rab fe Query results s Buffer n -tra n N o an has ฺ ) comGuide SQL ailฺ gm dent scripts @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C AN licen SQL and H M SQL*Plus Iis a command language for communication with the Oracle9i Server from any tool or AS RSQL A application. Oracle SQL contains many extensions. When you enter a SQL statement, it is stored in a 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 Oracle Database 10g: SQL Fundamentals I D - 3
  • 198. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Statements Versus SQL*Plus Commands SQL • A language • ANSI-standard • Keywords cannot be abbreviated • Statements manipulate data and table definitions in the database SQL*Plus • An environment • Oracle-proprietary • Keywords can be abbreviated • Commands do not allow le manipulation of values in erab f the database ans tr non N a as h m) ideฺ o SQL SQL SQL*Plus u SQL*Plus ilฺc t G a n statements buffer commands buffer m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN li(continued) SQL and H SQL*Plus c IM The following table compares SQL and SQL*Plus: AS AR 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 Oracle Database 10g: SQL Fundamentals I D - 4
  • 199. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 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 e abl r Execute saved files sfe n -tra Load commands from file to buffer to edit on NA an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen SQL*Plus IMHis an environment in which you can do the following: AS RSQL*Plus • 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 Environment Format File manipulation Execution Edit Interaction Miscellaneous Purpose Affect the general behavior of SQL statements for the session Format query results Save, load, and run script files Send SQL statements from the SQL buffer to the Oracle server Modify SQL statements in the buffer Create and pass variables to SQL statements, print variable values, and print messages to the screen Connect to the database, manipulate the SQL*Plus environment, and display column definitions Oracle Database 10g: SQL Fundamentals I D - 5
  • 200. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Logging In to SQL*Plus • • From a Linux desktop icon From a Linux terminal sqlplus [username[/password [@database]]] e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Logging In to SQL*Plus M IyouH How AS invoke SQL*Plus depends on which type of operating system or environment you are ARrunning. To log in using a desktop icon: 1. Double-click the sqlplus desktop icon. 2. Enter the username, password, and database name. To log in from a Linux terminal: 1. Log on to your machine and open a terminal. 2. Enter the SQL*Plus 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. Oracle Database 10g: SQL Fundamentals I D - 6
  • 201. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Displaying Table Structure Use the SQL*Plus DESCRIBE command to display the structure of a table: DESC[RIBE] tablename e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Structure Displaying Table lic IMH you can display the structure of a table using the DESCRIBE command. The result S In SQL*Plus, RA of the command is a display of column names and data types as well as an indication if a column must contain data. In the syntax: tablename The name of any existing table, view, or synonym that is accessible to the user To describe the JOB_GRADES table, use this command: SQL> DESCRIBE job_grades Name ---------------------------------GRADE_LEVEL LOWEST_SAL HIGHEST_SAL Null? -------- Type ----------VARCHAR2(3) NUMBER NUMBER Oracle Database 10g: SQL Fundamentals I D - 7
  • 202. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Displaying Table Structure SQL> DESCRIBE departments Name ----------------------DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID Null? Type -------- -----------NOT NULL NUMBER(4) NOT NULL VARCHAR2(30) NUMBER(6) NUMBER(4) e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Structure (continued) Displaying Table lic IMH in the slide displays the information about the structure of the DEPARTMENTS S The example RA table. In the result: Null? Type Specifies whether a column must contain data (NOT NULL indicates that a column must contain data.) Displays the data type for a column The following table describes the data types: Data Type NUMBER(p,s) VARCHAR2(s) DATE CHAR(s) Description Number value that has a maximum number of digits p, which is the number of digits to the right of the decimal point s Variable-length character value of maximum size s Date and time value between January 1, 4712 B.C., and December 31, 9999 A.D. Fixed-length character value of size s Oracle Database 10g: SQL Fundamentals I D - 8
  • 203. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL*Plus Editing Commands • • • • • • • A[PPEND] text C[HANGE] / old / new C[HANGE] / text / CL[EAR] BUFF[ER] DEL DEL n DEL m n e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Commands SQL*Plus Editing lic IMHcommands are entered one line at a time and are not stored in the SQL buffer. AS RSQL*Plus Command A[PPEND] text C[HANGE] / old / new Description Adds text to the end of the current line Changes old text to new in the current line C[HANGE] / text / CL[EAR] BUFF[ER] DEL DEL n DEL m n Deletes Deletes Deletes Deletes Deletes text from the current line all lines from the SQL buffer current line line n lines m to n inclusive 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. Oracle Database 10g: SQL Fundamentals I D - 9
  • 204. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL*Plus Editing Commands • • • • • • • • • I[NPUT] I[NPUT] text L[IST] L[IST] n L[IST] m n R[UN] n n text 0 text e s I[NPUT] I[NPUT] text L[IST] L[IST] n L[IST] m n R[UN] n n text 0 text n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Commands (continued) SQL*Plus Editing lic IMH S Description RA Command NA l rab fe Inserts an indefinite number of lines Inserts a line consisting of text Lists all lines in the SQL buffer Lists one line (specified by n) Lists a range of lines (m to n) inclusive Displays and runs the current SQL statement in the buffer Specifies the line to make the current line Replaces line n with text Inserts a line before line 1 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 (-). Oracle Database 10g: SQL Fundamentals I D - 10
  • 205. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using LIST, n, and APPEND SQL> LIST 1 SELECT last_name 2* FROM employees SQL> 1 e l rab fe 1* SELECT last_name SQL> A , job_id s n -tra n N o an has ฺ ) SQL> L comGuide ailฺ nt 1 SELECT last_name, job_id gm de 2* FROM employees ct@ tu an this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to N C cen An, andliAPPEND Using LIST, IMH L[IST] command to display the contents of the SQL buffer. The asterisk (*) •SUse the RA beside line 2 in the buffer indicates that line 2 is the current line. Any edits that you made A 1* SELECT last_name, job_id 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. Oracle Database 10g: SQL Fundamentals I D - 11
  • 206. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the CHANGE Command SQL> L 1* SELECT * from employees SQL> c/employees/departments e l rab fe 1* SELECT * from departments s SQL> L n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Command Using the CHANGE lic IMH •SUse L[IST] to display the contents of the buffer. RA Use the C[HANGE] command to alter the contents of the current line in the SQL buffer. In A • 1* SELECT * from departments 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. Oracle Database 10g: SQL Fundamentals I D - 12
  • 207. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL*Plus File Commands • • • • • • • SAVE filename GET filename START filename @ filename EDIT filename SPOOL filename EXIT e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen SQL*Plus File Commands MH Istatements communicate with the Oracle server. SQL*Plus commands control the AS RSQL environment, format query results, and manage files. You can use the commands described in the following table: Command Description SAV[E] filename [.ext] [REP[LACE]APP[END]] Saves current contents of SQL buffer to a file. Use APPEND to add to an existing file; use REPLACE to overwrite an existing file. The default extension is .sql. GET filename [.ext] STA[RT] filename [.ext] Writes the contents of a previously saved file to the SQL buffer. The default extension for the file name is .sql. Runs a previously saved command file @ filename Runs a previously saved command file (same as START) ED[IT] Invokes the editor and saves the buffer contents to a file named afiedt.buf ED[IT] [filename[.ext]] SPO[OL] [filename[.ext]| OFF|OUT] EXIT Invokes the editor to edit the contents of a saved file Stores query results in a file. OFF closes the spool file. OUT closes the spool file and sends the file results to the printer. Quits SQL*Plus Oracle Database 10g: SQL Fundamentals I D - 13
  • 208. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using the SAVE and START Commands SQL> 1 2* SQL> L SELECT last_name, manager_id, department_id FROM employees SAVE my_query Created file my_query SQL> START my_query e l rab fe ns a LAST_NAME MANAGER_ID DEPARTMENT_ID n-tr o ------------------------- ---------- ------------an King 90 has ฺ Kochhar 100 90 ) om uide ... c ailฺ nt G 20 rows selected. m g t@ Stude c han this m asiCopyrightse Oracle. All rights reserved. r u (na se to © 2009, C AN licen H SAVE IM Use the SAVE command to store the current contents of the buffer in a file. In this way, you can AS R NA store frequently used scripts for use in the future. START Use the START command to run a script in SQL*Plus. EDIT Use the 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. Oracle Database 10g: SQL Fundamentals I D - 14
  • 209. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 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 output • Interact with script files s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Summary IMHis an execution environment that you can use to send SQL commands to the database AS RSQL*Plus NA server and to edit and save SQL commands. You can execute commands from the SQL prompt or from a script file. Oracle Database 10g: SQL Fundamentals I D - 15 e l rab fe
  • 210. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 211. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Using SQL Developer e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen H
  • 212. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 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 • Identify menu items of Oracle SQL Developer • Create a database connection e abl r • Manage database objects sfe n -tra • Use SQL Worksheet non • Execute SQL statements and SQL scripts s a ) ha eฺ • Create and save reports om d NA i c ailฺ nt Gu m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Objectives IMH AS RIn this appendix, you are introduced to the graphical tool SQL Developer. You learn how to use SQL Developer for your database development tasks. You learn how to use SQL Worksheet to execute SQL statements and SQL scripts. Oracle Database 10g: SQL Fundamentals I E - 2
  • 213. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. What Is Oracle SQL Developer? • • Oracle SQL Developer is a free graphical tool that enhances productivity and simplifies database development tasks. You can connect to any target Oracle Database schema using standard Oracle Database authentication. e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C ANSQLicen l Developer? What Is Oracle IMH Developer is a free graphical tool designed to improve your productivity and Oracle SQL AS Rsimplify the development of everyday database tasks. With just a few clicks, you can easily A 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 using standard Oracle Database authentication. When connected, you can perform operations on objects in the database. Oracle Database 10g: SQL Fundamentals I E - 3
  • 214. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Key Features • • • • • • Developed in Java Supports Windows, Linux, and Mac OS X platforms Default connectivity by using the JDBC Thin driver Does not require an installer Connects to any Oracle Database version 9.2.0.1 and later Bundled with JRE 1.5 s n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN SQL Developer Key Features of lic IMH Developer is developed in Java, leveraging the Oracle JDeveloper IDE. The tool AS ROracle SQLWindows, Linux, and Mac OS X platforms. You can install SQL Developer on the A runs on the N Database Server and connect remotely from your desktop, thus avoiding client server network traffic. Default connectivity to the database is through the JDBC Thin driver; so, no Oracle Home is required. SQL Developer does not require an installer and you need to just unzip the downloaded file. With SQL Developer, users can connect to Oracle Database 9.2.0.1 and later versions, and all Oracle Database editions including Express Edition. SQL Developer is bundled with JRE 1.5, with an additional tools.jar to support Windows clients. Non-Windows clients need only JDK 1.5. Oracle Database 10g: SQL Fundamentals I E - 4 e l rab fe
  • 215. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Installing SQL Developer Download the Oracle SQL Developer kit and unzip it into any directory on your machine. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en ANDeveloper lic InstallingH SQL IM Oracle SQL Developer does not require an installer. To install SQL Developer, you need an AS R 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/software/products/sql/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. Oracle Database 10g: SQL Fundamentals I E - 5
  • 216. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Menus for SQL Developer 4 2 1 3 6 7 5 e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Developer lic Menus for SQL H IM SQL Developer has two main navigation tabs. AS AR • Connections Navigator: By using this tab, you can browse database objects and users to which you have access. • Reporting Tab: By using this tab, you can run predefined reports or create and add your own reports. 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 menus at the top contain standard entries, plus entries for features specific to SQL Developer. 1. View: Contains options that affect what is displayed in the SQL Developer interface 2. Navigate: Contains options for navigating to panes and for the execution of subprograms 3. Run: Contains the Run File and Execution Profile options that are relevant when a function or procedure is selected 4. Source: Contains options for use when editing functions and procedures 5. Versioning: Enables you to work with the files placed under source code control 6. Migration: Enables you to migrate from another database, such as Microsoft SQL Server and Microsoft Access, to an Oracle Database 7. Tools: Invokes SQL Worksheet, Preferences, and any added External Tools Oracle Database 10g: SQL Fundamentals I E - 6
  • 217. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Database Connection • • You must have at least one database connection to use SQL Developer. You can create and test connections: – For multiple databases – For multiple schemas • • • SQL Developer automatically imports any connections defined in the tnsnames.ora file on your system. e l rab fe s n You can export connections to an XML file. -tra non Each additional database connection created is listed in a as the connections navigator hierarchy. ) h NA ฺ comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN licConnection Creating HDatabase a IM is a SQL Developer object that specifies the necessary information for connecting AS RA connection to a specific database as a specific user of that database. To use SQL Developer, you must have 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 systems, 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 to connect to the same database but as different users, or to connect to different databases. Each database connection is listed in the Connections navigator hierarchy. Oracle Database 10g: SQL Fundamentals I E - 7
  • 218. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Database Connection e l rab fe s o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN licConnection (continued) Creating HDatabase a IM a database connection, perform the following steps: AS RTo create NA n -tra n 1. Double-click <your_path>sqldevelopersqldeveloper.exe. 2. On the Connections tabbed page, right-click Connections and select New Connection. 3. Enter the connection name, username, password, host name, port number, and SID for the database you want to connect. 4. Click Test to make sure that the connection has been set correctly. 5. Click Connect. Note: If you select the Save Password check box, the password is saved to an XML file. So, after you close the SQL Developer connection and open it again, you will not be prompted for the password. Oracle Database 10g: SQL Fundamentals I E - 8
  • 219. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Browsing Database Objects Use the Database Navigator to: • Browse through many objects in a database schema • Do a quick review of the definitions of objects e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Browsing Database Objects M IyouH a database connection, you can use the Database Navigator to browse through After AS create R many objects in a database schema including Tables, Views, Indexes, Packages, Procedures, Triggers, Types, and so on. 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 more are all displayed in an easy-to-read tabbed page. If you want to see the definition of the EMPLOYEES table as shown on the slide, perform the following steps: 1. Expand the connection node in the Connections Navigator. 2. Expand Tables. 3. Double-click EMPLOYEES. Using the Data tab, you can enter new rows, update data, and commit these changes to the database. Oracle Database 10g: SQL Fundamentals I E - 9
  • 220. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a Schema Object • SQL Developer supports the creation of any schema object by: – Executing a SQL statement in SQL Worksheet – Using the context menu • • Edit the objects by using an edit dialog box or one of many context-sensitive menus. e abl r View the DDL for adjustments, such sfe n as creating a new object or editing -tra an existing schema object. non NA a as h m) ideฺ o ilฺc t Gu a gm den @ nct is Stu a mh se th i ras Copyright © 2009, Oracle. All rights reserved. u (na se to C en AN liObject Creating HSchema c Ma IDeveloper supports the creation of any schema object by executing a SQL statement in AS RSQL SQL Worksheet. Alternatively, you can create objects using the context menus. Once created, you can edit the objects using an edit dialog or one of 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 creating 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 for creating and editing database objects have multiple tabs, each reflecting a logical grouping of properties for that type of object. Oracle Database 10g: SQL Fundamentals I E - 10
  • 221. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a New Table: Example e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C n AN Table:eExample lic Creating HNew a IM In the Create Table dialog box, if you do not select the Advanced check box, you can create a AS R table quickly by specifying columns and some frequently used features. If you select the Advanced check box, the Create Table dialog box changes to one with multiple tabs, in which you can specify an extended set of features while creating the table. The example in the slide shows creating the DEPENDENT 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 New 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 selecting Primary Key in the dialog box. Sometimes, you may want to edit the table that you have created. To edit a table, right-click the table in the Connections Navigator and select Edit. Oracle Database 10g: SQL Fundamentals I E - 11
  • 222. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using SQL Worksheet • • Use SQL Worksheet to enter and execute SQL, PL/SQL, and SQL *Plus statements. Specify any actions that can be processed by the database connection associated with the worksheet. e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Using SQL Worksheet IMHconnect to a database, a SQL Worksheet window for that connection is automatically AS RWhen you can use SQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus A opened. You 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 any 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 any of the following two options: • Select Tools > SQL Worksheet. • Click the Open SQL Worksheet icon. Oracle Database 10g: SQL Fundamentals I E - 12
  • 223. SQL Star International Limited Using SQL Worksheet 4 Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 2 1 3 6 5 7 8 e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C n AN lice(continued) Using SQL Worksheet IMH to use shortcut keys or icons to perform certain tasks such as executing a SQL You may AS Rstatement,want a script, and viewing the history of SQL statements that you have executed. A running You can use the SQL Worksheet toolbar that contains icons to perform the following tasks: 1. Execute Statement: Executes the statement at the cursor 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. Execute Explain Plan: Generates the execution plan, which you can see by clicking the Explain tab 7. Autotrace: Generates trace information for the statement, which you can see by clicking the Autotrace tab 8. Clear: Erases the statement or statements in the Enter SQL Statement box Oracle Database 10g: SQL Fundamentals I E - 13
  • 224. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Executing SQL Statements Use the Enter SQL Statement box to enter single or multiple SQL statements. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Statements lic Executing SQL H IM In SQL Worksheet, you can use the Enter SQL Statement box to enter a single or multiple SQL AS R statements. For a single statement, the semicolon at the end is optional. When you type in 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, as 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. Oracle Database 10g: SQL Fundamentals I E - 14
  • 225. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Viewing the Execution Plan e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C n AN licePlan Viewing the Execution IMH You can execute a SQL script AS Rperform the following steps: and view the execution plan. To execute a SQL script file, A 1. From the File menu, Select Open. 2. In the Open dialog box, double-click the .sql file. 3. Click the Run Script icon. When you double-click the .sql file, the SQL statements are loaded into the Enter SQL Statement box. You can execute the script or each line individually. The results are displayed in the Script Output area. The example in the slide shows the execution plan. The Execute Explain Plan icon generates the execution plan. An execution plan is the sequence of operations that are performed to execute the statement. You can see the execution plan by clicking the Explain tab. Oracle Database 10g: SQL Fundamentals I E - 15
  • 226. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Formatting the SQL Code Before Formatting e l rab fe s n -tra n NA o an has ฺ ) comGuide After ailฺ nt m Formatting @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C ANSQLicen l Code Formatting the IMH to beautify the indentation, spacing, capitalization, and line separation of the AS RYou may want SQL code. SQL Developer has the feature of formatting the SQL code. To format the SQL code, right-click in the statement area, and select Format. 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. Oracle Database 10g: SQL Fundamentals I E - 16
  • 227. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using Snippets Snippets are code fragments that may be just syntax or examples. e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Using Snippets IMH to use certain code fragments when you are using the SQL Worksheet or creating AS RYou may want A or editing 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 and drop snippets into the editor window. To display Snippets, select View > Snippets. The Snippets window is displayed on the right. 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. Oracle Database 10g: SQL Fundamentals I E - 17
  • 228. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using Snippets: Example Inserting a snippet e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C en AN Example Using Snippets: lic IMHsnippet into your code in SQL Worksheet or in a PL/SQL function or procedure, drag ToS A Rthe insert a from the Snippets window to the desired place in your code. Then, you can edit the A snippet Editing the snippet 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 such as in the following: SELECT CONCAT(first_name, last_name) FROM employees; Oracle Database 10g: SQL Fundamentals I E - 18
  • 229. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Using SQL*Plus • • SQL Worksheet does not support all SQL*Plus statements. SQL*Plus statements that are not supported by SQL Worksheet are: – – – – – – append archive attribute break change clear e l rab fe s n -tra n N o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Using SQL*Plus MH IWorksheet supports some SQL*Plus statements. SQL*Plus statements must be interpreted AS RSQL SQL Worksheet before being passed to the database; any SQL*Plus statements that are A by the not supported by the SQL Worksheet are ignored and not passed to the database. For example, some of the SQL*Plus statements that are not supported by SQL Worksheet are listed in the slide. For the complete list of SQL*Plus statements that are supported and not supported by SQL Worksheet, refer to SQL Developer online Help. Oracle Database 10g: SQL Fundamentals I E - 19
  • 230. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Database Reporting • • • SQL Developer provides you with a number of predefined reports about your database and objects. The Reports are organized into categories. You can create your own customized reports too. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen DatabaseH M Reporting IDeveloper provides many reports about the database and its objects. These reports are AS RSQL grouped into the following categories: • About Your Database reports • Object reports • Application Express reports • Charts • Database Administration reports • Data Dictionary reports • Jobs reports • PL/SQL reports • Security reports • Streams reports • Table reports • XML reports To display a report, click the Reports tabbed page and then select the report type. You can also create your own user-defined reports. Oracle Database 10g: SQL Fundamentals I E - 20
  • 231. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. Creating a User-Defined Report Create and save user-defined reports for repeated use. e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licenReport Creating HUser-Defined a IM reports are any reports that are created by SQL Developer users. To create a userAS RUser-defined defined report, 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. Oracle Database 10g: SQL Fundamentals I E - 21
  • 232. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. 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 e l rab fe s n -tra n NA o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s u ara Copyright © 2009, Oracle. All rights reserved. (n se to C AN licen Summary MH IDeveloper is a free graphical tool to simplify database development tasks. Using SQL AS RSQL Developer, you can browse, create, and edit database objects. You can use SQL Worksheet to run SQL statements and scripts. SQL Developer enables you to create and save your own special set of reports for repeated use. Oracle Database 10g: SQL Fundamentals I E - 22
  • 233. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited Index e s l rab fe o n -tra n NA S RA IM an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic HA
  • 234. SQL Star International Limited Note: A bolded number or letter refers to an entire lesson or appendix. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. A Adding Data Through a View 10-15 ADD_MONTHS Function 3-22, 3-23, 3-46, 3-60 Advanced Features of the SELECT Statement 6-2 Alias 1-4, 1-8, 1-14, 1-15, 1-16, 1-17, 1-25, 1-37, 1-40, 2-7, 2-20, 2-21, 2-31, 3-46, 4-12, 5-8, 5-11, 5-12, 5-20, 5-29, 7-17, 7-21, 9-33, 10-7, 10-9, 10-11, 11-22, C-11, C-12, C-15, C-20, C-21 ALL Operator 6-16, 7-11, 7-12, 7-18, 7-22 ALL_COL_COMMENTS Dictionary View 11-19 ALL_OBJECTS Dictionary View 11-5, 11-7 ALL_TAB_COMMENTS Dictionary View 11-19 ALTER SEQUENCE Statement 10-30, 10-31 ALTER TABLE Statement 9-34, 10-27 AS Keyword 1-14, 1-15, 1-16 AS Subquery 9-32, 10-7 Attributes i-18, i-19, i-20 AUTOCOMMIT Command 8-29 AVG Function 4-13 B BETWEEN Range Condition 2-9 Oracle Database 10g: SQL Fundamentals I Index -2 s n -tra n o an has ฺ ) comGuide American National Standards Institute (ANSI) i-12, i-25,ti-28, i-30, 3-26, 3-54, ailฺ n m 5-4, 8-27, D-4 @g tude ct S Ampersand Substitution 2-2, 2-24,n a 2-25, 2-28, 2-31, 2-32, 3-11 h his t m Double-ampersand (&&) 2-23, 2-28 asi use r ANY Operator 6-15 a (n se to C Arguments Function 3-3, 3-5, 3-15, 3-50 AN licen Arithmetic Expressions 1-9, 1-13, 1-16, 2-4 IMH AS Arithmetic Operators 1-9, 1-10, 3-20, 3-21, 3-60 R NA e l rab fe
  • 235. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. C Calculations 1-9, 1-14, 1-38, 3-3, 3-14, 3-20, 3-25, 3-60, 3-61, 4-26, D-5 Cardinality i-20 Cartesian Product 5-2, 5-5, 5-26, 5-27, 5-28, 5-29, C-4, C-5, C-21 CASE Expression 3-51, 3-54, 3-55, 3-56, 3-57, 3-60 Case-manipulation Functions 3-7, 3-9, 3-10 CAT View 11-8 Character strings 1-16, 1-17, 1-18, 2-6, 2-15, 3-9, 3-11, 3-35, 3-38 Character-manipulation Functions 3-7, 3-11, 3-12 CHECK Constraint 8-7, 9-28, 10-21, 11-12, 11-13 COALESCE Function 3-52, 3-53, 4-5 Column Alias 1-8, 1-14, 1-15, 1-17, 1-37, 2-21, 3-46, 4-12, 5-11, R 11-20, 11-22, E-9 Conversion Functions 3-2, 3-6, 3-9, 3-26, 3-31, 3-60, 7-19 COUNT Function 4-8 CREATE INDEX Statement 10-36 CREATE PUBLIC SYNONYM Statement 10-41 CREATE SEQUENCE Statement 10-24 CREATE SYNONYM Statement 10-39, 10-40, 10-41 CREATE TABLE Statement 8-11, 9-5, 9-32, 9-36, 9-37 Creating a Database Connection 1-24, 1-25, 1-26, E-7, E-8 Creating a User-Defined Report E-21 Cross Joins 5-4, 5-28, 5-29 CURRVAL 9-7, 9-28, 10-26, 10-27, 10-28 CYCLE Option (with Sequences) 10-25, 10-30 Oracle Database 10g: SQL Fundamentals I Index -3 s n -tra n o an has ฺ ) comGuide ailฺ nt m Composite Unique Key 9-22, 9-23 @g 3-38,de 3-60-61, 8-41, C-7, E-18 t CONCAT Function 1-16, 1-18, 1-42, 3-11-12, Stu 3-46, anc this Concatenation Operator 1-16 h m asi use r t Conditional Processing 3-54 o (na9-19, 11-13 CONSTRAINT_TYPE se C en AN i-9, i-30, 1-12, 1-27, 8-7, 8-17, 8-21, 9-2, 9-10, CONSTRAINTS lic H IM9-17-23, 9-26, 9-28, 9-30-32, 9-35, 9-36, 10-16, 10-38, 11-11-14, AS 5-12, 9-33, 10-9, 10-11, C-11, C-12 COMMENT Statement 11-19 COMMENTS Column 11-6, 11-19 COMMIT Statement 8-29, 8-32, 8-33 NA e l rab fe
  • 236. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. D Data from More Than One Table 5-2, 5-3, 5-5, C-2, C-3, C-7 Data Structures i-9, i-14, i-17, 9-3 Data Types i-6, i-9, 1-9, 1-35, 1-36, 3-3, 3-25, 3-26, 3-48, 3-50, 3-60, 3-61, 4-5, 4-7, 5-6, 5-8, 7-8, 7-13, 7-15, 8-7, 8-11, 9-2, 9-9-12, 9-14, 9-36, 11-10-12, D-7, D-8 Data Warehouse Applications i-9 Database I, 1-2, 1-3, 1-22-29, 1-34, 1-37, 1-39, 2-2, 2-6, 3-10, 3-17-20, 3-26, 4-13, 4-16, 5-29, 6-7, 8-3, 8-13, 8-18, 8-24, 8-25, 8-29, 8-31, 8-32, 8-37, 8-38, 8-39, 9-2-6, 9-13, 9-18, 9-33-37, 10-3, 10-16, 10-20, 10-22, 10-23, 10-33, 10-34, 10-39, 10-41, 10-42, 11-3-12, 11-17-19, B-3, C-6, C-7, C-9, C-21, D-3-6, D-15, E o A R NA DDL Statement 8-11, 8-24, 8-25, 8-29, 8-36, 9-1, 9-5, 9-8, 9-35 DECODE Function 3-54, 3-56, 3-57, 3-58, 3-59, 3-60, 3-67 Default Date Display 2-6, 3-17 DEFAULT Option 9-7, 10-24, 10-25 Default Sort Order 2-21, 4-16 DELETE Statement 8-18, 8-19, 8-20, 8-21, 8-37, 8-39 DESC Keyword 2-21 DESCRIBE Command 1-35, 1-36, 8-7, 9-8, 9-33, 10-8, 10-12, 11-11, D-7 Dictionary Views i-3, 11-1, 11-2, 11-3, 11-6, 11-19, 11-20, 11-21 Oracle Database 10g: SQL Fundamentals I Index -4 s n -tra n Database Structures 9-5 Date i-3, i-9, i-13, i-14, i-18, i-28, 1-8, 1-9, 1-17, 1-27, 1-40, 1-42, 2-6, 2-7, 2-10, 2-11, 2-20, 2-21, 2-23, 2-26, 2-33, 2-34, 3-2-6, 3-14-27, 3-32-37, 3-41-48, 3-60-65, 4-5, 4-7, 4-24, 5-35, 6-21, 7-4, 7-6, 7-19, 8-2, 8-3, 8-6, 8-8, 8-9, 8-12-16, 8-22, 8-23, 8-27, 8-28, 8-33, 8-37-42, 9-7-17, 9-23, 9-26-30, 9-33, 10-6, 10-7, 10-16, 10-17, 10-27, 10-37, 11-4, 11-7, 11-8, 11-15, C-27, E-9 DATE Data Type 3-6, 3-18, 3-22, 3-25, 3-61, 4-7, 7-19, 9-12 an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s Datetime Data Typeara 9-12, u 9-11, o 9-14 n t DBA_OBJECTS 11-5 se C ( en N lic DBMS i-2, i-13, i-14, i-21, i-23, i-26, i-27, i-30 HA SIMStatement 8-25, 8-29, 9-5 DCL e l rab fe
  • 237. SQL Star International Limited D Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. DISTINCT Keyword 1-20, 4-9, 7-11, 10-13, 10-14, 10-15, 10-27 DML Operations on Data Through a View 10-13 Double-ampersand 2-23, 2-28 DROP ANY INDEX Privilege 10-38 DROP ANY VIEW Privilege 10-20 DROP INDEX Statement 10-38 DROP SYNONYM Statement 10-41 DROP TABLE Statement 9-35 DROP VIEW Statement 10-20 DUAL Table 3-14, 3-19 e s n -tra n Duplicate Rows i-23, 1-20, 4-8, 7-8, 7-11, 7-12, 7-18, 7-22 o an E has ฺ ) Entity Relationship i-17, i-19, i-20 comGuide Equijoins 5-2, 5-9, 5-19, 5-20, 5-29, C-2, C-8, C-9, C-14, C-15, C-21 ailฺ nt m ESCAPE Option 2-12 @g tude ct D-15, Execute SQL 1-2, 1-28, 1-37, D-2,n a D-5,his SE-2, E-12, E-22 imh se t Execution Plan 1-29, E-13, E-15 s u ara to3-26, 3-29, 3-30, 3-31 Explicit Data Typen Conversion C ( ense N lic HA F IM AS R NA Foreign Key i-21, i-22, i-24, 5-9, 8-7, 9-17, 9-25, 9-26, 9-27, 9-31, 10-35, 11-12, 11-13, C-7, C-8 Format Model 3-22, 3-24, 3-32, 3-33, 3-35, 3-37, 3-40, 3-41 FROM Clause 1-4, 1-9, 2-4, 3-14, 4-13, 4-16, 5-12, 6-4, C-9, C-12, C-20 FULL OUTER Join 5-5, 5-22, 5-25 Functions i-3, i-7, i-10, 1-23, 2-4, 2-6, 3-1-15, 3-22-26, 3-29, 3-31, 3-41, 3-42, 3-45, 3-46, 3-47, 3-60, 3-61, 4-1-7, 4-10-13, 4-17, 4-18, 4-20, 4-23-26, 6-10, 6-19, 7-19, 8-8, 9-7, 9-28, 10-6, 10-12-15, 11-3, 11-8, E-6, E-17, E-18 fx Modifier 3-41, 3-42 Oracle Database 10g: SQL Fundamentals I Index -5 l rab fe
  • 238. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. G Generate Unique Numbers 10-3, 10-23 GROUP BY Clause 4-2, 4-11, 4-12, 4-13, 4-14, 4-16, 4-17, 4-20, 4-21, 4-24, 6-12, 10-13, 10-14, 10-15 GROUP BY Column 4-14, 4-16 Group Functions 3-4, 4-1-13, 4-17, 4-18, 4-20, 4-23-26, 6-10, 6-19, 10-12-15 Group Functions in a Subquery 6-10 H e l rab fe HAVING Clause 4-2, 4-18-25, 6-4, 6-11, 6-19 s I R NA o an has ฺ ) comGuide ailฺ nt 5-26, 5-27, 10-37, C-2, C-4-7, C-13, C-14, C-16, C-17 m @g 10-3, de 10-34-38, Index 1-27, 9-3, 9-6, 9-23, 9-24, 9-35,t10-2, tu 10-33, anc this S h11-7, 11-8, E-5, E-9 10-42, 10-43, 10-46, 11-3, m asi use INSERT Statement 8-5, 8-11, 8-22, 8-23, 8-41, 9-8, 9-19, 10-27, 10-28 ar (ni-30,s8-7,to 9-17, 9-19, 9-22, 9-30, e 8-21, Integrity Constraint N C l10-16, 11-3 en 9-31, 9-32, ic HA IM International Standards Organization (ISO) i-28 AS IF-THEN-ELSE Logic 3-54, 3-55, 3-57, 3-60 Implicit Data Type Conversion 3-26, 3-27, 3-28 IN Condition 2-7, 2-10, 5-2, 5-4, 5-13, 5-18, 5-19, 5-21, 5-22, INTERSECT Operator 7-3, 7-13, 7-14, 7-22 INTERVAL YEAR TO MONTH 9-11, 9-14, 9-15 IS NOT NULL Condition 2-13 IS NULL Condition 2-13 J Java i-4, i-7, i-10, i-27, E-4 Joining Tables 5-5, 5-22, 5-30, C-7 K Keywords 1-4, 1-7, 1-31, 1-32, 5-6, 9-26, 9-27, D-4, E-14, E-16 Oracle Database 10g: SQL Fundamentals I Index -6 n -tra n
  • 239. SQL Star International Limited L Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. LEFT OUTER Join 5-23 LIKE Condition 2-11, 2-12 Literal 1-17, 1-18, 1-19, 2-4, 2-11, 2-12, 3-11, 3-35, 3-51, 3-55, 7-20, 9-7 Logical Condition 2-14 Logical Subsets 10-4 M MAX Function 4-6, 4-7 MIN Function 4-7 MINUS Operator 7-15, 7-16, 7-17, 7-22, 7-23 MOD Function 3-16 s Nested SELECT 6-4, 6-20 NEXTVAL 9-7, 9-28, 10-26, 10-27, 10-28 NEXTVAL and CURRVAL Pseudocolumns 10-26, 10-27 Nonunique Index 10-35, 10-43, 10-46 NOT NULL Constraint 1-35, 9-19, 9-21, 9-22, 9-32, 11-10 NOT Operator 2-17, 2-31, 6-16 NULL Conditions 2-13, 2-31 Null Value i-24, 1-12, 1-13, 1-16, 2-13, 2-21, 3-47-51, 3-57, 4-5, 4-8-10, 6-13, 6-17, 7-8, 7-13, 8-7, 9-7, 9-21, 9-24, 10-37 NULLIF Function 3-51 NUMBER Data Type 3-38, 7-19, 8-6 Number Functions 3-6, 3-13 NVL Function 3-48, 3-49, 3-52, 3-60, 4-10 NVL2 Function 3-50 Oracle Database 10g: SQL Fundamentals I Index -7 n -tra n o an Modifier 3-41, 3-42 has ฺ ) MONTHS_BETWEEN Function 3-6 comGuide Multiple-column Subqueries 6-7 ailฺ nt m Multiple-row Functions 3-4 @g tude t Multiple-row Subqueries 6-2, 6-6, 6-7, 6-14, 6-15, 6-16 anc this S imh se s ara to u n N C ( ense NamingAN 9-4,c H 1-33, li 9-18, 11-5 IM Nested Functions 3-45, 3-61 AS R NA e l rab fe
  • 240. Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. SQL Star International Limited O Object Relational i-2, i-9, i-13, i-30 Object Relational Database Management System i-2, i-30 Object-oriented Programming i-9 OLTP i-9 ON clause 5-5, 5-13-18, 5-22, 7-12, 10-16, 10-17 ON DELETE CASCADE 9-27 ON DELETE SET NULL 9-27 Online Transaction Processing i-9 OR REPLACE Option 10-8, 10-11 e Oracle Application Server 10g i-5, i-7, i-30 Oracle Database 10g i-3, i-5, i-6, i-27, i-30, 6-7, 9-34 Oracle Enterprise Manager 10g Grid Control i-5, i-8, i-30 Oracle Instance i-27 ORDBMS i-2 Order i-18, i-23, 1-6, 1-11, 2-2, 2-18, 2-20, 2-21, 2-23, 2-27, 2-28, 2-31-34, 3-5, 3-46, 3-53, 3-63, 3-65, 3-66, 4-5, 4-12, 4-14, 4-16, 4-20, 4-22, 4-24, 4-27, 5-33, 6-6, 6-21, 7-2, 7-3, 7-8, 7-10, 7-12, 7-13, 7-17, 7-18, 7-21, 7-22, 7-24, 8-6, 9-10, 9-13, 10-11, 10-27, 11-8, 11-16, C-11, C-25 ORDER BY Clause 2-20, 2-21, 2-23, 2-31, 2-32, 3-5, 4-14, 4-24, Order of Rows i-23, 2-20, 7-2, 7-21 Outer Query 6-3, 6-4, 6-5, 6-9, 6-10, 6-12, 6-13, 6-20 P PRIMARY KEY Constraint 9-20, 9-24 Projection 1-3 Oracle Database 10g: SQL Fundamentals I Index -8 n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S imh se s ara to u n C ( ense N lic 6-6, 7-17, 7-21, 7-22, 9-10, 10-27, C-11 HA SIM of Precedence 1-11, 2-18 Order A R NA s l rab fe
  • 241. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. R RDBMS i-2, i-14, i-21, i-23, i-26, i-27, i-30 Read Consistency 8-31, 8-37, 8-38 READ ONLY Option 10-18 Read-only Constraint 10-19 REFERENCES 1-23, 1-27, 1-34, 8-29, 9-25-29, 11-13, E-6, E-9 Referential Integrity Constraint 8-21 Relational Database i Relational Database Management System i-2, i-14, i-27, i-30 Restrict the Rows 1-3, 2-2, 2-4, 4-19, C-10 Retrieve Data from a View 10-10 Return a Value 3-3, 3-6, 3-14, 3-22 RIGHT OUTER Join 5-24 ROLLBACK Statement 8-2, 8-25-27, 8-29, 8-31, 8-34, 8-36, 8-39 ROUND and TRUNC Functions 3-24 ROUND Function 3-14, 3-15 e s n -tra n o an has ฺ ) comGuide ailฺ nt m RR Date Format 3-43, 3-44 @g tude t Rules of Precedence 1-10, 1-11, 2-18, 2-19 S anc this imh se s ara to u n S C ( ense SAVEPOINT Statement 8-28 N lic HA Schema 1-22-27, 9-2, 9-5, 9-6, 9-19, 9-29, 9-36, 10-1, 10-34, 10-40, SIM11-2-4, 11-7, 11-21-23, B-3, E-3, E-7, E-9, E-10 RA NA SELECT Statement i-3, 1-1-6, 1-17, 1-18, 1-37, 1-39, 2-5, 2-8, 2-9, 2-11, 2-19, 2-20, 2-23, 2-27, 2-29, 2-31, 2-32, 3-2, 3-10, 4-8, 4-13-18, 5-2, 5-12, 6-2-9, 6-19, 6-20, 7-8, 7-13-20, 8-19, 8-31, 8-37, 8-38, 9-32, 10-4, 10-7, 10-12, 10-27, 11-6, 11-15, C-2, C-7, C-12, D-2 Selection 1-3, 2-3 Sequences 2-21, 9-6, 10-2, 10-3, 10-22, 10-23, 10-29, 10-38, 10-42, 10-43, 11-3, 11-16, 11-17, 11-20, 11-23 Set operators 7-1, 7-2, 7-3, 7-17, 7-18, 7-23, 7-24 SET VERIFY ON 2-30 Sets of Rows 4-3 SGA i-27 Oracle Database 10g: SQL Fundamentals I Index -9 l rab fe
  • 242. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. S Single-row Functions 2-6, 3-1, 3-4, 3-5, 3-6, 3-45, 3-60, 4-3 Single-row Operator 6-4, 6-6, 6-8, 6-12, 6-14, 6-19 Single-row Subqueries 6-2, 6-6, 6-7, 6-8, 6-9 SOME Operator 6-15 Sorted i-3, 2-35, 7-8, 7-10, 7-11, 7-18, 7-21, 7-22 Sorting 2-1, 2-21, 2-31, 2-32 SQL Developer i-2, 1-2, 1-7, 1-8, 1-14, 1-20, 1-21, 1-22, 1-23, 1-24, 1-25, 1-27, 1-28, 1-32, 1-34, 1-35, 1-37, 1-38, 1-39, 1-42, 2-22-30, 8-25, 8-29, 8-30, E Statement-level Rollback 8-36 Structured Query Language i-25, i-26, 1-2 Sub-SELECT 6-4 Subqueries in UPDATE statements 8-16 System Development Life Cycle i-11, i-12, i-17 System Failure 8-24, 8-29, 8-30 System Global Area i-27 Oracle Database 10g: SQL Fundamentals I Index -10 s n -tra n o an has ฺ ) Subqueries to Delete Rows 8-20 om 9-32, e c9-10,Guid9-33, 9-36, Subquery 6-3-19, 8-11, 8-13, 8-15, 8-20, 8-22, 8-23, ailฺ nt m e 10-7, 10-8, 10-9, 10-11, 10-27 d @g 2-30-32, 8-10, E-13 Substitution Variables 2-22, 2-23, nct 2-27, tu 2-26, S a s SUM Function 4-6, 4-16 mh se thi i ras t 4-16 Summary Results for Groupso u (na se 9-3, 9-6, 9-35, 10-2, 10-3, 10-39, 10-40-43, Synonym i-19, i-20, 1-35, 6-15, C AN11-3,icen 11-9, 11-18, 11-20, 11-21, 11-22, D-7 l 11-8, 10-46, IMH Function 3-18, 3-19, 8-8 SYSDATE AS R NA e l rab fe
  • 243. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. T Table Alias 5-12, 5-20, 5-29, C-12, C-15, C-21 Table Prefixes 5-11, C-11, C-12 Three-way Join 5-18 TO_CHAR Function 3-32, 3-37, 3-38, 3-39, 3-40 TO_NUMBER or TO_DATE Functions 3-41 Transactions 8-2, 8-24, 8-25, 8-27, 8-36, 8-40, 9-35 TRUNC Function 3-15, 3-24 Tuple i-23 Types of Indexes 10-35 e s l rab fe U R NA o an has ฺ ) comGuide ailฺ nt m Unique Identifier i-19, i-20 @g tude ct S Unique Index 9-23, 9-24, 10-35, an 10-37, 10-43, 10-46 h his t m UNIQUE Key Integrity Constraint se asi u 9-22 r UPDATE Statement 8-13, 8-14, 8-15, 8-16, 10-27 (na se to C UPPER Function 3-10 n AN lice USER_CONS_COLUMNS Dictionary View 11-14 IMH AS USER_SYNONYMS Dictionary View 11-18 UNION ALL Operator 7-11, 7-12, 7-18, 7-22 UNION Clause 7-12 UNION Operator 7-8, 7-9, 7-10, 7-19, 7-20, 7-21, 7-22, 7-23 UNIQUE Constraint 9-22, 9-23, 10-33, 10-35, 10-37, 11-13 USING Clause 5-4, 5-8, 5-9, 5-10, 5-11, C-6 Using Snippets E-17, E-18 Using SQL Worksheet E-12, E-13 Oracle Database 10g: SQL Fundamentals I Index -11 n -tra n
  • 244. SQL Star International Limited Unauthorized reproduction or distribution prohibited. Copyright© 2010, Oracle and/or its affiliates. V VALUES Clause 8-5, 8-7, 8-11, 8-22, 10-27 VARIANCE 4-4, 4-7, 4-24 VERIFY Command 2-30 Views i-3, i-8, 1-27, 9-6, 9-35, 10-2, 10-3, 10-4, 10-5, 10-6, 10-13, 10-16, 10-20, 10-21, 10-38, 10-40, 10-42, 11-1, 11-2, 11-3, 11-4, 11-5, 11-6, 11-7, 11-8, 11-15, 11-19, 11-20, 11-21, 11-23, E-9 W When to Create an Index 10-37 WHERE Clause 2-3, 2-4, 2-5, 2-6, 2-7, 2-8, 2-10, 2-14, 2-22, 2-23, 2-26, 2-27, 2-31, 2-32, 3-10, 4-8, 4-12, 4-13, 4-18, 4-19, 4-24, 4-26, 5-7, 5-8, 5-13, 5-17, 5-29, 6-2, 6-4, 6-11, 6-12, 6-13, 6-18, 7-17, 8-14, 8-19, 10-37, 11-4, C-4, C-7, C-9, C-10, C-11, C-17, C-20, C-21 Wildcard Search 2-11 WITH CHECK OPTION 10-7, 10-8, 10-16, 10-17, 11-13 e s Oracle Database 10g: SQL Fundamentals I Index -12 n -tra n o an has ฺ ) comGuide ailฺ nt m @g tude t anc this S X imh se E-20, E-21 XML i-4, i-6, i-27, 1-24,as E-7, E-8, ar 1-25,o u n t C ( ense N lic HA IM AS R NA l rab fe