D80190GC11 sg2
D80190GC11 sg2
D80190GC11 sg2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
Oracle Database 12c: a
) h SQL
Workshop I lฺco m eฺ
i i d
g ma nt Gu
i 5
Student7@ de
Guide t–uVolume II
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
D80190GC11
Edition 1.1
July 2014
D87241
M/sฺSeed Infotech Ltdฺ
Author Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Nancy Greenberg publish, license, post, transmit, or distribute this document in whole or in part without
the express authorization of Oracle.
Swarnapriya Shridhar
The information contained in this document is subject to change without notice. If you
Bryan Roberts find any problems in the document, please report them in writing to: Oracle University,
Laszlo Czinkoczki 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
KimSeong Loh
Restricted Rights Notice
Brent Dayley
If this documentation is delivered to the United States Government or anyone using
Jim Spiller the documentation on behalf of the United States Government, the following notice is
applicable:
Christopher Wensley
Manish Pawar U.S. GOVERNMENT RIGHTS
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
Clair Bennett
s
disclose these training materials are restricted by the terms of the applicable Oracle a
Yanti Chang h a
license agreement and/or the applicable U.S. Government contract.
)
Trademark Notice
o m
c uideฺ
Joel Goodman
i l ฺ
Gerlinde Frenzen
g ma nt G
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names
7@ tude
may be trademarks of their respective owners.
Madhavi Siddireddy
i 5
m his S
t
u eta
Editors
g a
Smita Kommini
j e s h
t o us
i
Aju Kumar
i (br ense
u t am e lic
Publishers
G a abl
Pavithran Adka
es h sfer
j
Bri n-tran
Giri Venugopal
no
M/sฺSeed Infotech Ltdฺ
Contents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
1 Introduction
Lesson Objectives 1-2
Lesson Agenda 1-3
Course Objectives 1-4
Course Agenda 1-5
Appendixes and Practices Used in the Course 1-7
Lesson Agenda 1-8
Oracle Database 12c: Focus Areas 1-9
Oracle Database 12c 1-10
s a
Oracle Fusion Middleware 1-12
) h a
Oracle Cloud 1-14
o m
c uideฺ
Oracle Cloud Services 1-15 i l ฺ
Cloud Deployment Models 1-16 g ma nt G
Lesson Agenda 1-17
i 5 7@ tude
t a m his S
Relational and Object Relational Database Management Systems 1-18
g au se t
Data Storage on Different Media 1-19
h
i j es e to u
Relational Database Concept 1-20
r
i (b ens
Definition of a Relational Database 1-21
t am e lic
Data Models 1-22
u
G a abl
Entity Relationship Model 1-23
es h sfer
jEntity Relationship Modeling Conventions 1-25
Bri n-tran
Relating Multiple Tables 1-27
no Relational Database Terminology 1-29
Lesson Agenda 1-31
Using SQL to Query Your Database 1-32
SQL Statements Used in the Course 1-33
Development Environments for SQL 1-34
Lesson Agenda 1-35
Human Resources (HR) Schema 1-36
Tables Used in the Course 1-37
Lesson Agenda 1-38
Oracle Database Documentation 1-39
Additional Resources 1-40
Summary 1-41
Practice 1: Overview 1-42
iii
M/sฺSeed Infotech Ltdฺ
no Quiz 2-27
Summary 2-28
Practice 2: Overview 2-29
iv
M/sฺSeed Infotech Ltdฺ
h g au se t
Character and Date Values with Substitution Variables 3-35
r i j es e to u
Specifying Column Names, Expressions, and Text 3-36
(b ens
Using the Double-Ampersand Substitution Variable 3-37
i
u t am e lic
Using the Ampersand Substitution Variable in SQL*Plus 3-38
a abl
Lesson Agenda 3-39
G
s h sfer
Using the DEFINE Command 3-40
e
j
Bri n-tran
Using the VERIFY Command 3-41
no Quiz 3-42
Summary 3-43
Practice 3: Overview 3-44
v
M/sฺSeed Infotech Ltdฺ
G a abl
5 Using
j es hConversion
s f erFunctions and Conditional Expressions
i
BrObjectives r an5-2
- t
n on Agenda 5-3
Lesson
Conversion Functions 5-4
Implicit Data Type Conversion 5-5
Explicit Data Type Conversion 5-7
Lesson Agenda 5-9
Using the TO_CHAR Function with Dates 5-10
Elements of the Date Format Model 5-11
Using the TO_CHAR Function with Dates 5-14
Using the TO_CHAR Function with Numbers 5-15
Using the TO_NUMBER and TO_DATE Functions 5-18
Using TO_CHAR and TO_DATE Functions with the RR Date Format 5-20
Lesson Agenda 5-21
General Functions 5-22
NVL Function 5-23
vi
M/sฺSeed Infotech Ltdฺ
vii
M/sฺSeed Infotech Ltdฺ
viii
M/sฺSeed Infotech Ltdฺ
ix
M/sฺSeed Infotech Ltdฺ
no
Changing Data in a Table 10-14
UPDATE Statement Syntax 10-15
Updating Rows in a Table 10-16
Updating Two Columns with a Subquery 10-17
Updating Rows Based on Another Table 10-18
Lesson Agenda 10-19
Removing a Row from a Table 10-20
DELETE Statement 10-21
Deleting Rows from a Table 10-22
Deleting Rows Based on Another Table 10-23
TRUNCATE Statement 10-24
Lesson Agenda 10-25
Database Transactions 10-26
Database Transactions: Start and End 10-27
x
M/sฺSeed Infotech Ltdฺ
n on Tables 11-8
Creating
Lesson Agenda 11-9
Datetime Data Types 11-12
DEFAULT Option 11-13
Lesson Agenda 11-14
Including Constraints 11-15
Constraint Guidelines 11-16
Defining Constraints 11-17
NOT NULL Constraint 11-19
UNIQUE Constraint 11-20
PRIMARY KEY Constraint 11-22
FOREIGN KEY Constraint 11-23
FOREIGN KEY Constraint: Keywords 11-25
CHECK Constraint 11-26
xi
M/sฺSeed Infotech Ltdฺ
xii
M/sฺSeed Infotech Ltdฺ
C Using SQL*Plus
Objectives C-2
SQL and SQL*Plus Interaction C-3
SQL Statements Versus SQL*Plus Commands C-4
SQL*Plus: Overview C-5
Logging In to SQL*Plus C-6
Displaying the Table Structure C-7
SQL*Plus Editing Commands C-9 s a
Using LIST, n, and APPEND C-11 ) h a
m
c uideฺ
o
Using the CHANGE Command C-12
i l ฺ
SQL*Plus File Commands C-13
g ma nt G
Using the SAVE and START Commands C-14
i 5 7@ tude
SERVEROUTPUT Command C-15
t a m his S
Using the SQL*Plus SPOOL Command C-16
h g au se t
Using the AUTOTRACE Command C-17
r i j es e to u
Summary C-18
i (b ens
u t am e lic
D Commonly Used
G a SQL a l
bCommands
sh nD-2sfe
Objectives r
r i j e
tra Statement D-3
BBasicnSELECT
-
n o Statement D-4
SELECT
WHERE Clause D-5
ORDER BY Clause D-6
GROUP BY Clause D-7
Data Definition Language D-8
CREATE TABLE Statement D-9
ALTER TABLE Statement D-10
DROP TABLE Statement D-11
GRANT Statement D-12
Privilege Types D-13
REVOKE Statement D-14
TRUNCATE TABLE Statement D-15
Data Manipulation Language D-16
INSERT Statement D-17
xiii
M/sฺSeed Infotech Ltdฺ
xiv
M/sฺSeed Infotech Ltdฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
following:
• Describe set operators
• Use a set operator to combine multiple queries into a
single query
• Control the order of rows returned
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a howabtolwrite queries by using set operators.
In this lesson, you learn
G
es h sfer
j
Bri n-tran
no
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Set Operators
A B A B
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
UNION/UNION ALL
A B
INTERSECT
s a
A B a
)h ฺ
o m
a ilฺc Guide
MINUS @ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Set operators combine
G r bl of two or more component queries into one result. Queries
a the aresults
h sfeare called compound queries.
r i jes operators
containing set
n
B n-traReturns
Operator
UNION n
o Rows from both queries after eliminating duplications
UNION ALL Rows from both queries, including all duplications
INTERSECT Rows that are common to both queries
MINUS Rows in the first query that are not present in the second query
All set operators have equal precedence. If a SQL statement contains multiple set operators,
the Oracle server evaluates them from left (top) to right (bottom), if no parentheses explicitly
specify another order. You should use parentheses to specify the order of evaluation explicitly
in queries that use the INTERSECT operator with other set operators.
number.
• The data type of each column in the subsequent query
must match the data type of its corresponding column in
the first query.
• Parentheses can be used to alter the sequence of
execution.
• ORDER BY clause can appear only at the very end of the
statement. s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
• The expressions
G r bl
a in theaSELECT lists of the queries must match in number and data type.
h usesUNION,
Queriessthat fe UNION ALL, INTERSECT, and MINUS operators must have the
r
samei jenumberr n
a data type of columns in their SELECT list. The data type of the
and
B
columns - t
n in the SELECT list of the queries in the compound query may not be exactly the
n o
same. The column in the second query must be in the same data type group (such as
numeric or character) as the corresponding column in the first query.
• Set operators can be used in subqueries.
• You should use parentheses to specify the order of evaluation in queries that use the
INTERSECT operator with other set operators. This ensures compliance with emerging
SQL standards that will give the INTERSECT operator greater precedence than the
other set operators.
UNION ALL.
• Column names from the first query appear in the result.
• The output is sorted in ascending order by default except
in UNION ALL.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
When a query uses a
G r a bl the Oracle server eliminates duplicate rows automatically
set operators,
h of sthefeUNION ALL operator. The column names in the output are decided
except in thescase
r i
by the columnje listrainnthe first SELECT statement. By default, the output is sorted in ascending
B
order of the - t
n column of the SELECT clause.
n ofirst
The corresponding expressions in the SELECT lists of the component queries of a compound
query must match in number and data type. If component queries select character data, the
data type of the return values is determined as follows:
• If both queries select values of CHAR data type, of equal length, the returned values
have the CHAR data type of that length. If the queries select values of CHAR with different
lengths, the returned value is VARCHAR2 with the length of the larger CHAR value.
• If either or both of the queries select values of VARCHAR2 data type, the returned values
have the VARCHAR2 data type.
If component queries select numeric data, the data type of the return values is determined by
numeric precedence. If all queries select values of the NUMBER type, the returned values have
the NUMBER data type. In queries using set operators, the Oracle server does not perform
implicit conversion across data type groups. Therefore, if the corresponding expressions of
component queries resolve to both character data and numeric data, the Oracle server returns
an error.
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Two tables are usedain this lesson:
G r a bl the EMPLOYEES table and the RETIRED_EMPLOYEES
table.
r i j esh ansfe
You areB already
n - trfamiliar with the EMPLOYEES table that stores employee details such as a
n o
unique identification number, email address, job identification (such as ST_CLERK, SA_REP,
and so on), salary, manager, and so on.
RETIRED_EMPLOYEES stores the details of the employees who have left the company.
The structure and data from the EMPLOYEES and RETIRED_EMPLOYEES tables are shown on
the following pages.
DESCRIBE employees
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
DESCRIBEo retired_employees
n
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
UNION Operator
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
A B
s a
) h a
m
c uideฺ
o
a tGi l ฺ
g m
@ tuden
The UNION operator returns rows from both queries after eliminating
duplications. i57
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The UNION operatorareturns all
G r a blrows that are selected by either query. Use the UNION
r i j esh aallnrows
operator to return
sfe from multiple tables and eliminate any duplicate rows.
B n-tr
Guidelines
o
• Thennumber of columns being selected must be the same.
• The data types of the columns being selected must be in the same data type group
(such as numeric or character).
• The names of the columns need not be identical.
• UNION operates over all of the columns being selected.
• NULL values are not ignored during duplicate checking.
• By default, the output is sorted in ascending order of the columns of the SELECT clause.
Display the job details of all the current and retired employees.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The UNION operatoraeliminates
G r a bl any duplicatetables
records. If records that occur in both the
EMPLOYEES s
e h sfe
and the RETIRED_EMPLOYEES are identical, the records are displayed
j
Bri n-tran
only once.
no
A B
s a
a
)h ฺ
o m
a ilฺc Guide
The UNION ALL operator returns rows from both queries,
@ gm including
e n t all
duplications. i57
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Use the UNION ALLa operatorb tol return all rows from multiple queries.
h G r a
Guidelines
r i jes ransfe
B n-tfor UNION and UNION ALL are the same, with the following two exceptions
The guidelines
noto UNION ALL: Unlike UNION, duplicate rows are not eliminated and the output is
that pertain
not sorted by default.
employees.
SELECT job_id, department_id
FROM employees
UNION ALL
SELECT job_id, department_id
FROM retired_employees
ORDER BY job_id;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
… i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014, iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In the example, 35 rows
G r bl
a areaselected. The combination of the two tables totals to 35 rows.
The UNION ALL
i sh operator
jeeither n s fedoes not eliminate duplicate rows. UNION returns all distinct rows
selectedrby r a
query. UNION ALL returns all rows selected by either query, including all
B - t
n n
duplicates.oConsider the query in the slide, now written with the UNION clause:
SELECT job_id,department_id
FROM employees
UNION
SELECT job_id,department_id
FROM retired_employees
ORDER BY job_id;
The preceding query returns 19 rows. This is because it eliminates all the duplicate rows.
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
INTERSECT Operator
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
A B
s a
)h ฺa
o m
a ilฺc Guide
The INTERSECT operator returns rows that are common
@ gmto both e n t
queries.
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Use the INTERSECTaoperatorbto
G a l return all rows that are common to multiple queries.
h r
Guidelines
r i jes ransfe
B number
• The
n -t of columns and the data types of the columns being selected by the
o
n statements in the queries must be identical in all the SELECT statements used
SELECT
in the query. The names of the columns, however, need not be identical.
• Reversing the order of the intersected tables does not alter the result.
• INTERSECT does not ignore NULL values.
SELECT manager_id,department_id
FROM employees
INTERSECT
SELECT manager_id,department_id
FROM retired_employees
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In the example in this
G r blquery returns only those records that have the same values in
aslide,athe
the selected s h sinfeboth tables.
i jecolumns
B n-tran
r
no
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
MINUS Operator
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
A B
s a
a
)h ฺ
o m
a ilฺc Guide
The MINUS operator returns all the distinct rows selectedgby the first
m nquery, t but
@
7 set.tud e
not present in the second query i 5
m his S
result
t a
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Use the MINUS operator
G r bl all distinct rows selected by the first query, but not present
a to areturn
h result set (the first SELECT statement MINUS the second SELECT
je ransfe
in the secondsquery
r
statement).i
B n-t
Note: Thenonumber of columns must be the same and the data types of the columns being
selected by the SELECT statements in the queries must belong to the same data type group in
all the SELECT statements used in the query. The names of the columns, however, need not
be identical.
Display the employee IDs and Job IDs of those employees who
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
You must match the data type (using the TO_CHAR function or
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
…
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The EMPLOYEES and
G r a bl
aRETIRED_EMPLOYEES tables have several columns in common (for
i sh nsfe JOB_ID, and DEPARTMENT_ID). But what if you want the query to
example, EMPLOYEE_ID,
jeFIRST_NAME,
B r
display the
t r a JOB_ID, and HIRE_DATE using the UNION operator, knowing that
the HIRE_DATE -
on exists only in the EMPLOYEES table?
n
The code example in the slide matches the FIRST_NAME and JOB_ID columns in the
EMPLOYEES and RETIRED_EMPLOYEES tables. NULL is added to the RETIRED_EMPLOYEES
SELECT statement to match the HIRE_DATE column in the EMPLOYEES SELECT statement.
In the results shown in the slide, each row in the output that corresponds to a record from the
RETIRED_EMPLOYEES table contains a NULL in the HIRE_DATE column.
Lesson Agenda
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Quiz
Summary
Practice 9: Overview
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In this practice, you a
G r a bl using the set operators.
write queries
h
r i jes ransfe
B n-t
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
following:
• Describe each data manipulation language (DML)
statement
• Control transactions
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a howabtoluse the data manipulation language (DML) statements to
In this lesson, you learn
G
s
insert rows into
j e ha table, s f er existing rows in a table, and delete existing rows from a table.
update
You alsorilearn how r anto control transactions with the COMMIT, SAVEPOINT, and ROLLBACK
B - t
non
statements.
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Data manipulation language
G a a(DML)
r bl is a core part of SQL. When you want to add, update, or
delete data instheh sfe you execute a DML statement. A collection of DML statements
that formr i jelogicalradatabase,
n of work is called a transaction.
B n-t unit
a
Considernaobanking database. When a bank customer transfers money from a savings
account to a checking account, the transaction might consist of three separate operations:
decreasing the savings account, increasing the checking account, and recording the
transaction in the transaction journal. The Oracle server must guarantee that all the three SQL
statements are performed to maintain the accounts in proper balance. When something
prevents one of the statements in the transaction from executing, the other statements of the
transaction must be undone.
Notes
• Most of the DML statements in this lesson assume that no constraints on the table are
violated. Constraints are discussed later in this course.
• In SQL Developer, click the Run Script icon or press [F5] to run the DML statements.
The feedback messages will be shown on the Script Output tabbed page.
New
DEPARTMENTS row
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G r a bl the addition of a new department to the DEPARTMENTS
a illustrates
The graphic in the slide
h
table.
r i jes ransfe
B n-t
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can add new rows
G r bl by issuing the INSERT statement.
a to aatable
h
r i jes ransfe
In the syntax:
tableB -t Is the name of the table
o n
columnn Is the name of the column in the table to populate
value Is the corresponding value for the column
Note: This statement with the VALUES clause adds only one row at a time to a table.
DESCRIBE departments
column list.
INSERT INTO departments (department_id,
department_name)
VALUES (30, 'Purchasing');
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The DD-MON-RR format
G r a bl used to insert a date value. With the RR format, the
a is generally
r i j esh the
system provides
n s fe century automatically.
correct
tra the date value in the DD-MON-YYYY format. This is recommended
B alson-supply
You may
because ito clearly specifies the century and does not depend on the internal RR format logic of
n
specifying the correct century.
If a date must be entered in a format other than the default format (for example, with another
century or a specific time), you must use the TO_DATE function.
The example in the slide records information for employee Raphealy in the EMPLOYEES table.
It sets the HIRE_DATE column to be February 3, 2003.
Creating a Script
values.
• & is a placeholder for the variable value.
INSERT INTO departments
(department_id, department_name, location_id)
VALUES (&department_id, '&department_name',&location);
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can save commands
G a with a l
bsubstitution variables to a file and execute the commands in
r
table. Brij
esh ansinfe
the file. The example the slide records information for a department in the DEPARTMENTS
n tr
-file
n o
Run the script and you are prompted for input for each of the ampersand (&) substitution
variables. After entering a value for the substitution variable, click the OK button. The values
that you input are then substituted into the statement. This enables you to run the same script
file over and over, but supply a different set of values each time you run it.
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
EMPLOYEES
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a abthe
The slide illustrates changing
G l department number for employees in department 60 to
h r
r i jes ransfe
department 80.
B n-t
no
statement:
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a avalues
You can modify the existing
G r bl in a table by using the UPDATE statement.
h
r i jes ransfe
In the syntax:
B n-t Is the name of the table
table
column no Is the name of the column in the table to populate
value Is the corresponding value or subquery for the column
condition Identifies the rows to be updated and is composed of column names,
expressions, constants, subqueries, and comparison operators
Confirm the update operation by querying the table to display the updated rows.
For more information, see the section on “UPDATE” in Oracle Database SQL Language
Reference for 12c database.
Note: In general, use the primary key column in the WHERE clause to identify a single row for
update. Using other columns can unexpectedly cause several rows to be updated. For
example, identifying a single row in the EMPLOYEES table by name may return more than one
employee having the same name.
• Values for all the rows in the table are modified if you omit
the WHERE clause:
UPDATE copy_emp s a
SET department_id = 110;
a
)h ฺ
o m
a ilฺc Guide
• Specify SET column_name= NULL to@ gm eancolumn
update t
value to NULL. i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The UPDATE statement
G a modifies
r a bl the values of a specific row or rows if the WHERE clause is
specified. The
r i j eshexample
n s fine the slide shows the transfer of employee 113 (Popp) to department 50.
If you B tra clause, values for all the rows in the table are modified. Examine the
omit the WHERE
n -
no in the
updated rows COPY_EMP table.
SELECT last_name, department_id
FROM copy_emp;
For example, an employee who was an SA_REP has now changed his job to an IT_PROG.
Therefore, his JOB_ID needs to be updated and the commission field needs to be set to NULL.
UPDATE employees
SET job_id = 'IT_PROG', commission_pct = NULL
WHERE employee_id = 114;
Note: The COPY_EMP table has the same data as the EMPLOYEES table.
employee 205.
UPDATE employees
SET (job_id,salary) = (SELECT job_id,salary
FROM employees
WHERE employee_id = 205)
WHERE employee_id = 103;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a columns
You can update multiple
r a bl in the SET clause of an UPDATE statement by writing
h The fesyntax is as follows:
r i jes UPDATE
multiple subqueries.
n s
ra table
B n-tSET
no
column =
(SELECT column
FROM table
WHERE condition)
[ ,
column =
(SELECT column
FROM table
WHERE condition)]
[WHERE condition ] ;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a ainblthe UPDATE statements to update values in a table. The
You can use the subqueries
G
example in the
j es s f er the COPY_EMP table based on the values from the EMPLOYEES
hslide updates
ri trthe
table. It changes
B andepartment number of all employees with employee 200’s job ID to
employee o -
n current department number.
n100’s
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
DEPARTMENTS
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a ahas
The contracting department
G r bl been removed from the DEPARTMENTS table (assuming no
hthe DEPARTMENTS table are violated), as shown by the graphic in the slide.
jes ransfe
constraints on
r
B n-ti
no
DELETE Statement
DELETE statement:
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a rows
You can remove existing
G a l a table by using the DELETE statement.
bfrom
h r
r i jes ransfe
In the syntax:
B n-t Is the name of the table
table
no
condition Identifies the rows to be deleted, and is composed of column names,
expressions, constants, subqueries, and comparison operators
Note: If no rows are deleted, the message “0 rows deleted” is returned (on the Script Output
tab in SQL Developer).
For more information, see the section on “DELETE” in Oracle Database SQL Language
Reference for 12c database.
• All rows in the table are deleted if you omit the WHERE
clause:
However, if you omit the WHERE clause, all rows in the table are deleted. The second example
in the slide deletes all rows from the COPY_EMP table, because no WHERE clause was
specified.
Example
Remove rows identified in the WHERE clause.
DELETE FROM employees WHERE employee_id = 114;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a atobldelete rows from a table based on values from another table.
You can use the subqueries
G
The examplesinhthe slidef r
edeletes all the employees in a department, where the department
r i j e n s
B n-tra
name contains the string Public.
no searches the DEPARTMENTS table to find the department number based on the
The subquery
department name containing the string Public. The subquery then feeds the department
number to the main query, which deletes rows of data from the EMPLOYEES table based on
this department number.
TRUNCATE Statement
• Example:
TRUNCATE TABLE copy_emp;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
A more efficient method
G r a bl a table is by using the TRUNCATE statement.
a of emptying
You can use s h TRUNCATE
the
s fe statement to quickly remove all rows from a table or cluster.
r
Removing i je
rows withr n
a TRUNCATE statement is faster than removing them with the DELETE
the
B
statement o - t
fornthe following reasons:
n
• The TRUNCATE statement is a data definition language (DDL) statement and generates
no rollback information. Rollback information is covered later in this lesson.
If the table is the parent of a referential integrity constraint, you cannot truncate the table. You
need to disable the constraint before issuing the TRUNCATE statement. Disabling constraints
is covered in the lesson titled “Introduction to DDL Statements.”
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Database Transactions
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a adata
The Oracle server ensures
G r bl consistency based on transactions. Transactions give you
hand controlfe when changing data, and they ensure data consistency in the
ijesprocess
more flexibility
of ruser
event B a n sfailure or system failure.
- t r
Transactions
n onconsist of DML statements that constitute one consistent change to the data. For
example, a transfer of funds between two accounts should include the debit in one account
and the credit to another account of the same amount. Both actions should either fail or
succeed together; the credit should not be committed without the debit.
Transaction Types
Type Description
Data manipulation Consists of any number of DML statements that the Oracle
language (DML) server treats as a single entity or a logical unit of work
Data definition Consists of only one DDL statement
language (DDL)
Data control language Consists of only one DCL statement
(DCL)
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
When does a database
G r a bl start and end?
a transaction
A transaction h when
esbegins s fe the first DML statement is encountered and ends when one of the
r i j n
B occurs:
following
n - tra
no or ROLLBACK statement is issued.
• A COMMIT
• A DDL statement, such as CREATE, is issued.
• A DCL statement is issued.
• The user exits SQL Developer or SQL*Plus.
• A machine fails or the system crashes.
After one transaction ends, the next executable SQL statement automatically starts the next
transaction.
A DDL statement or a DCL statement is automatically committed and, therefore, implicitly
ends a transaction.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
With the COMMIT and
G a ROLLBACK
r a bl statements, you have control over making changes to the
h
r i jes ransfe
data permanent.
B n-t
no
Time COMMIT
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Transaction
DELETE
SAVEPOINT A
INSERT
s a
UPDATE a
)h ฺ
o m
SAVEPOINT B
a ilฺc Guide
@ gm ent
INSERT
ROLLBACK i 5 7
ROLLBACK
S t ud ROLLBACK
to SAVEPOINT tBa to SAVEPOINTm h is A
a u
g use t
s h
( b r je and/or
Copyright © 2014,iOracle
s e titsoaffiliates. All rights reserved.
m i cen
a li
ut of transactions
l e
You can control the a
logic b by using the COMMIT, SAVEPOINT, and ROLLBACK
statements. sh
G r a
r i je ransfe
B n-t
Statement Description
n o
COMMIT COMMIT ends the current transaction by making all pending
data changes permanent.
SAVEPOINT name SAVEPOINT name marks a savepoint within the current
transaction.
ROLLBACK ROLLBACK ends the current transaction by discarding all
pending data changes.
ROLLBACK TO ROLLBACK TO <savepoint> rolls back the current
SAVEPOINT name transaction to the specified savepoint, thereby discarding any
changes and/or savepoints that were created after the
savepoint to which you are rolling back. If you omit the TO
SAVEPOINT clause, the ROLLBACK statement rolls back the
entire transaction. Because savepoints are logical, there is
no way to list the savepoints that you have created.
Note: You cannot COMMIT to a SAVEPOINT. SAVEPOINT is not ANSI-standard SQL.
SAVEPOINT statement.
• Roll back to that marker by using the ROLLBACK TO
SAVEPOINT statement.
UPDATE...
SAVEPOINT update_done;
INSERT...
ROLLBACK TO update_done;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can create a marker
G a inathe
r blcurrent transaction by using the SAVEPOINT statement, which
h sfinto e smaller sections. You can then discard pending changes back to
r i jebys using
divides the transaction
n
B n-tra ROLLBACK TO SAVEPOINT statement.
that marker the
Note thatnifoyou create a second savepoint with the same name as an earlier savepoint, the
earlier savepoint is deleted.
circumstances:
– A DDL statement issued
– A DCL statement issued
– Normal exit from SQL Developer or SQL*Plus, without
explicitly issuing COMMIT or ROLLBACK statements
• An automatic rollback occurs when there is an abnormal
termination of SQL Developer or SQL*Plus or a system
failure. a
h a s
m )
i l ฺ c uideฺ
o
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Status G r a bl
a Circumstances
Automatici sh nsfeDDL statement or DCL statement issued
jecommit
r
B n-tra SQL Developer or SQL*Plus exited normally, without
n o explicitly issuing COMMIT or ROLLBACK commands
Automatic rollback Abnormal termination of SQL Developer or SQL*Plus
or system failure
Note: In SQL*Plus, the AUTOCOMMIT command can be toggled ON or OFF. If set to ON, each
individual DML statement is committed as soon as it is executed. You cannot roll back the
changes. If set to OFF, the COMMIT statement can still be issued explicitly. Also, the COMMIT
statement is issued when a DDL statement is issued or when you exit SQL*Plus. The SET
AUTOCOMMIT ON/OFF command is skipped in SQL Developer. DML is committed on a
normal exit from SQL Developer only if you have the Autocommit preference enabled. To
enable Autocommit, perform the following:
• In the Tools menu, select Preferences. In the Preferences dialog box, expand Database
and select Worksheet Parameters.
• In the right pane, select the “Autocommit in SQL Worksheet” option. Click OK.
System Failures
When a transaction is interrupted by a system failure, the entire transaction is automatically
rolled back. This prevents the error from causing unwanted changes to the data and returns the
tables to the state at the time of the last commit. In this way, the Oracle server protects the
integrity of the tables.
In SQL Developer, a normal exit from the session is accomplished by selecting Exit from the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
File menu. In SQL*Plus, a normal exit is accomplished by entering the EXIT command at the
prompt. Closing the window is interpreted as an abnormal exit.
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a during
Every data change made
r a bl the transaction is temporary until the transaction is
committed. sh
r i j e ansfe
r before COMMIT or ROLLBACK statements are issued can be described
B of nthe-tdata
The state
no
as follows:
• Data manipulation operations primarily affect the database buffer; therefore, the
previous state of the data can be recovered.
• The current session can review the results of the data manipulation operations by
querying the tables.
• Other sessions cannot view the results of the data manipulation operations made by the
current session. The Oracle server institutes read consistency to ensure that each
session sees data as it existed at the last commit.
• The affected rows are locked; other session cannot change the data in the affected
rows.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Make all pending changes
G a permanent
r a bl by using the COMMIT statement. Here is what happens
after a COMMIT
i j eshstatement:
n s fe
r
B changes
• Data tra are written to the database.
o n -
• Thenprevious state of the data is no longer available with normal SQL queries.
• All sessions can view the results of the transaction.
• The locks on the affected rows are released; the rows are now available for other
sessions to perform new data changes.
• All savepoints are erased.
Committing Data
UPDATE employees
SET department_id = 80
WHERE employee_id = 206;
COMMIT;
statement:
• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are released.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a abbyl using the ROLLBACK statement, which results in the following:
Discard all pending changes
G
• Data e s h are
changes f r
eundone.
j s
Briprevious
• The - t r n of the data is restored.
astate
n the affected rows are released.
• Locksnoon
ROLLBACK;
Rollback complete.
no
Statement-Level Rollback
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
A part of a transaction
G a can be a l
bdiscarded through an implicit rollback if a statement execution
h If a single r
fe DML statement fails during execution of a transaction, its effect is
undone r
byi jea sstatement-level
error is detected.
r a n s rollback, but the changes made by the previous DML statements
B - t
n are not discarded. They can be committed or rolled back explicitly by the
in the transaction
user. n o
The Oracle server issues an implicit commit before and after any DDL statement. So, even if
your DDL statement does not execute successfully, you cannot roll back the previous
statement because the server issued a commit.
Terminate your transactions explicitly by executing a COMMIT or ROLLBACK statement.
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Read Consistency
at all times.
• Changes made by one user do not conflict with the
changes made by another user.
• Read consistency ensures that, on the same data:
– Readers do not wait for writers
– Writers do not wait for readers
– Writers wait for writers
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G r bl
a theadatabase
Database users access in two ways:
h fe
r i j s rans(SELECT
• Readeoperations statement)
B operations
• Write
n -t (INSERT, UPDATE, DELETE statements)
o
nread consistency so that the following occur:
You need
• The database reader and writer are ensured a consistent view of the data.
• Readers do not view data that is in the process of being changed.
• Writers are ensured that the changes to the database are done in a consistent manner.
• Changes made by one writer do not disrupt or conflict with the changes being made by
another writer.
The purpose of read consistency is to ensure that each user sees data as it existed at the last
commit, before a DML operation started.
Note: The same user can log in to different sessions. Each session maintains read
consistency in the manner described above, even if they are the same users.
User A
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Undo
segments
Changed
SELECT * and unchanged
Read- data
FROM userA.employees;
s a
consistent
image )h ฺ
Before
a
m
a i lฺco change
u i de
User B
g m nt G (“old” data)
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Read consistency isa
G r a bl implementation. It keeps a partial copy of the database in
an automatic
h The feread-consistent image is constructed from the committed data in the
r i jesoldrdata
the undo segments.
n s
B n-t a
table and the that is being changed and is not yet committed from the undo segment.
o update, or delete operation is made on the database, the Oracle server takes
When anninsert,
a copy of the data before it is changed and writes it to an undo segment.
All readers, except the one who issued the change, see the database as it existed before the
changes started; they view the undo segment’s “snapshot” of the data.
Before the changes are committed to the database, only the user who is modifying the data
sees the database with the alterations. Everyone else sees the snapshot in the undo
segment. This guarantees that readers of the data read consistent data that is not currently
undergoing change.
When a DML statement is committed, the change made to the database becomes visible to
anyone issuing a SELECT statement after the commit is done. The space occupied by the old
data in the undo segment file is freed for reuse.
If the transaction is rolled back, the changes are undone:
• The original, older version of the data in the undo segment is written back to the table.
• All users see the database as it existed before the transaction began.
Lesson Agenda
– INSERT statement
• Changing data in a table
– UPDATE statement
• Removing rows from a table:
– DELETE statement
– TRUNCATE statement
• Database transaction control using COMMIT, ROLLBACK,
and SAVEPOINT a
as ) h
• Read consistency m
co uideฺ
i l ฺ
• FOR UPDATE clause in a SELECT statement
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
SA_REP.
SELECT employee_id, salary, commission_pct, job_id
FROM employees
WHERE job_id = 'SA_REP'
FOR UPDATE
ORDER BY employee_id;
no the FOR UPDATE OF column_name to qualify the column that you intend to
You can use
change. The OF list of the FOR UPDATE clause does not restrict you to changing only those
columns of the selected rows. Locks are still placed on all rows; if you simply state FOR
UPDATE in the query and do not include one or more columns after the OF keyword, the
database will lock all identified rows across all the tables listed in the FROM clause.
The following statement locks only those rows in the EMPLOYEES table with ST_CLERK
located in LOCATION_ID 1500. No rows are locked in the DEPARTMENTS table:
SELECT e.employee_id, e.salary, e.commission_pct
FROM employees e JOIN departments d
USING (department_id)
WHERE job_id = 'ST_CLERK' AND location_id = 1500
FOR UPDATE OF e.salary
ORDER BY e.employee_id;
ORDER BY employee_id;
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Quiz
a. True
b. False
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Answer: b G a abl
es h sfer
j
Bri n-tran
no
Summary
following statements:
Function Description
INSERT Adds a new row to the table
UPDATE Modifies existing rows in the table
DELETE Removes existing rows from the table
TRUNCATE Removes all rows from a table
Makes all pending changes permanent
COMMIT
s a
SAVEPOINT Is used to roll back to the savepoint marker a
)h ฺ
o m
ROLLBACK Discards all pending data changes
a ilฺc Guide
FOR UPDATE clause Locks rows identified by the SELECT gm query nt
in SELECT i 5 7 @ t u de
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a have
In this lesson, you should
r a bllearned how to manipulate data in the Oracle database by
using the INSERT, h UPDATE,fe DELETE, and TRUNCATE statements, as well as how to control
r
data changesi jesbyrusing
n s
a the COMMIT, SAVEPOINT, and ROLLBACK statements. You also
B
learned how - t
nto use the FOR UPDATE clause of the SELECT statement to lock rows for your
n
changes only.
o
Remember that the Oracle server guarantees a consistent view of data at all times.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
add rowsbtol the MY_EMPLOYEE table, update and delete data from the
In this practice, you a
h
table, and control
G e ra
your transactions. You run a script to create the MY_EMPLOYEE table.
i s
je rans f
r
B n-t
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
following:
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Explain how constraints are created at the time of table
creation
a
• Describe how schema objects work has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In this lesson, you are
G a introduced
r a bl to the data definition language (DDL) statements. You learn
the basics ofs h to create
how
s fe simple tables, alter them, and remove them. The data types
available r i
injeDDL r a
arenshown and schema concepts are introduced. Constraints are discussed
B
in this lesson. - t
nException messages that are generated from violating constraints during DML
n o
operations are shown and explained.
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• CREATE TABLE statement
• Data types
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Database Objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Object Description
Table Is the 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 name to an object
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The Oracle database
G r a bl multiple data structures. Each structure should be outlined
acan contain
h sfsoe that it can be created during the build stage of database
jes design
in the database
i
B n-tran
r
development.
no Stores data
• Table:
• View: Is a subset of data from one or more tables
• Sequence: Generates numeric values
• Index: Improves the performance of some queries
• Synonym: Gives an alternative name to an object
Oracle Table Structures
• Tables can be created at any time, even when 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.
Naming Rules
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You name databaseatables and
G r a bl columns according to the standard rules for naming any
Oracle database
i sh and
jenames
object.
n s e
fcolumn
• Tabler
B nmust names must begin with a letter and be 1–30 characters long.
tracontain only the characters A–Z, a–z, 0–9, _ (underscore), $, and # (legal
• Names -
no but their use is discouraged).
characters,
• 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.
- You may also use quoted identifiers to represent the name of an object. A quoted
identifier begins and ends with double quotation marks (“”). If you name a schema
object using a quoted identifier, you must use the double quotation marks
whenever you refer to that object. Quoted identifiers can be reserved words,
although this is not recommended.
Naming Guidelines
Use descriptive names for tables and other database objects.
Note: Names are not case-sensitive. For example, EMPLOYEES is treated to be the same
name as eMPloyees or eMpLOYEES. However, quoted identifiers are case-sensitive.
For more information, see the “Schema Object Names and Qualifiers” section in the Oracle
Database SQL Language Reference for 12c database.
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• CREATE TABLE statement
• Data types
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
• You specify:
– The table name
– The column name, column data type, and column size
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You create tables toa
G store data
r a blby executing the SQL CREATE TABLE statement. This
statement is s h thesfDDL e statements that are a subset of the SQL statements used to
create, r i jeoneorrofaremove
modify, n Oracle Database structures. These statements have an immediate
B - t
effect on the
n ondatabase 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 (DBA) uses data control language (DCL)
statements to grant privileges to users.
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
Note: The CREATE ANY TABLE privilege is needed to create a table in any schema other
than the user’s schema.
Creating Tables
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• CREATE TABLE statement
• Data types
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Data Types
Data Type Description
VARCHAR2(size) Variable-length character data
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
CHAR [(size)] Fixed-length character data of length size bytes (Default and
minimum size is 1; maximum size is 2,000.)
NUMBER [(p,s)] Number having precision p and scale s (Precision is the total
number of decimal digits and scale is the number of digits to
the right of the decimal point; precision can range from 1 to
38, and 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.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Data Type h G r a bl
a Description
r i jes ransfeEnables storage of time as a date with fractional seconds. It stores the
B n-t
TIMESTAMP
year, month, day, hour, minute, and the second value of the DATE data
no type, as well as the fractional seconds value.
There are several variations of this data type such as WITH TIMEZONE
and WITH LOCALTIMEZONE.
INTERVAL YEAR TO Enables storage of time as an interval of years and months; used to
MONTH represent the difference between two datetime values in which the only
significant portions are the year and month
INTERVAL DAY TO Enables storage of time as an interval of days, hours, minutes, and
SECOND seconds; used to represent the precise difference between two datetime
values
Note: These datetime data types are available with Oracle9i and later releases. The datetime
data types are discussed in detail in the lesson titled “Managing Data in Different Time Zones”
in the Oracle Database: SQL Workshop II course.
Also, for more information about the datetime data types, see the sections on “TIMESTAMP
Datatype,” “INTERVAL YEAR TO MONTH Datatype,” and “INTERVAL DAY TO SECOND
Datatype” in Oracle Database SQL Language Reference for 12c database.
DEFAULT Option
table.
... hire_date DATE DEFAULT SYSDATE, ...
Note: In SQL Developer, click the Run Script icon or press F5 to run the DDL statements. The
feedback messages will be shown on the Script Output tabbed page.
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• CREATE TABLE statement
• Data types
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Including Constraints
Constraint Guidelines
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a inathe
All constraints are stored
G r bldata dictionary. Constraints are easy to reference if you give
sh name.
them a meaningful
s fe Constraint names must follow the standard object-naming rules,
rijethe tname
exceptBthat r a n cannot be the same as another object owned by the same user. If you
do not nameo -
nyour constraint, the Oracle server generates a name with the format SYS_Cn,
n
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 creation of the table. You
can define a constraint at the column or table level. Functionally, a table-level constraint is the
same as a column-level constraint.
For more information, see the section on “Constraints” in Oracle Database SQL Language
Reference for 12c database.
Defining Constraints
• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Defining Constraints
Ensures that null values are not permitted for the column:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
Absence of NOT NULL @ gm ent
constraint
NOT NULL constraint
i
(Any row can contain 5 7 a null value
S t ud
(Primary Key enforces NOT
NULL constraint.) constraint u t am this
NOT NULL for this column.)
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The NOT NULL constraint
G a ensures
r a bl that the column contains no null values. Columns without
the NOT NULL hconstraint
escolumn s fecan contain null values by default. NOT NULL constraints must be
r
defined at i jthe r a n level. In the EMPLOYEES table, the EMPLOYEE_ID column inherits a
B - t
n n
NOT NULL o constraint because it is defined as a primary key. Otherwise, the LAST_NAME,
EMAIL, HIRE_DATE, and JOB_ID columns have the NOT NULL constraint enforced on them.
UNIQUE Constraint
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
UNIQUE constraint
EMPLOYEES
…
INSERT INTO
Allowed s a
h a
m)
Not allowed: already exists
co uideฺ
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
A UNIQUE key integrity
G r a bl requires that every value in a column or a set of columns
a constraint
i sh nsis,feno two rows of a table can have duplicate values in a specified
(key) be unique—that
jaeset
columnB r
or
tof
r acolumns. The column (or set of columns) included in the definition of the
UNIQUE key o -
nconstraint is called the unique key. If the UNIQUE constraint comprises more
n
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 the 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 the 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.
UNIQUE Constraint
PRIMARY KEY
DEPARTMENTS
Not allowed
(null value) INSERT INTO s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
Not allowed i 5 7
S t ud
(50 already exists)
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a acreates
A PRIMARY KEY constraint
G r bl a primary key for the table. Only one primary key can be
created for each h table.sfThe
e PRIMARY KEY constraint is a column or a set of columns that
uniquely r i jes raeach
identifies n row in a table. This constraint enforces the uniqueness of the column
B
or column o n - t
combination, and ensures that no column that is part of the primary key can contain
n
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.
…
EMPLOYEES
FOREIGN
KEY
s a
)h ฺa
… m
oallowedide
INSERT INTO
a i(9lฺcdoes
Not
u
Gnot
g m nexist) t
7@ tudAllowed e
i 5
m his S
t a
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The FOREIGN KEY (or
G r a bl integrity) constraint designates a column or a combination of
a referential
h skey,
columns as asforeign fe and establishes a relationship with a primary key or a unique key in
the same r i je orraandifferent
table table.
B n-t
no in the slide, DEPARTMENT_ID has been defined as the foreign key in the
In the example
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.
The foreign key can also be defined at the column level, provided that the constraint is based
on a single column. The syntax differs in that the keywords FOREIGN KEY do not appear.
Example:
CREATE TABLE employees
(...
department_id NUMBER(4) CONSTRAINT emp_deptid_fk
REFERENCES departments(department_id),
...
)
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
• ON DELETE SET NULL: Converts dependent foreign key
values to null
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a inathe
The foreign key is defined
G r bl child table and the table containing the referenced column is
i j esh Thensforeign
the parent table. fe key is defined using a combination of the following keywords:
• B r
FOREIGNtrKEY a is used to define the column in the child table at the table-constraint
n -
no
level.
• REFERENCES identifies the table and the column in the parent table.
• ON DELETE CASCADE indicates that when a row in the parent table is deleted, the
dependent rows in the child table are also deleted.
• ON DELETE SET NULL indicates that when a row in the parent table is deleted, the
foreign key values are set to null.
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. And these keyword cannot be
used in column-level syntax.
CHECK Constraint
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The CHECK constraint
G a defines
r a bal condition that each row must satisfy. To satisfy the constraint,
each row in the
r i j eshtablen s fe make the condition either TRUE or unknown (due to a null).
must
B ncan
The condition - trause the same constructs as the query conditions except the queries that
no values in other rows.
refer to other
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),
...
Violating Constraints
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
UPDATE employees
SET department_id = 55
WHERE department_id = 110;
s a
a
)h ฺ
o m
Department 55 does not exist.
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a ainbplace
When you have constraints
G l on columns, an error is returned if you try to violate the
h example, r
fe if you try to update a record with a value that is tied to an
r i jes For
constraint rule.
n s
B n-tra
integrity constraint, an error is returned.
no in the slide, department 55 does not exist in the parent table, DEPARTMENTS,
In the example
and so you receive the “parent key not found” violation ORA-02291.
Violating Constraints
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a a record
If you attempt to delete
r a bl with a value that is tied to an integrity constraint, an error is
returned.
r i j esh ansfe
B nin-tthe
The example r slide tries to delete department 60 from the DEPARTMENTS table, but it
results innano 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, you
receive the “child record found” violation ORA-02292.
The following statement works because there are no employees in department 70:
DELETE FROM departments
WHERE department_id = 70;
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• Data types
• CREATE TABLE statement
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
A second method foracreatingbal table is to apply the AS subquery clause, which both creates
h G rowserreturned
a
the table andsinserts
i j e ans f from the subquery.
r
syntax: -tr
In the B
table
n on 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. Note that only the explicit NOT NULL constraint will be inherited. The PRIMARY
KEY column will not pass the NOT NULL feature to the new column. Any other constraint
rules are not passed to the new table. However, you can add constraints in the column
definition.
Oracle Database 12c: SQL Workshop I 11 - 31
M/sฺSeed Infotech Ltdฺ
DESCRIBE dept80 s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
m lic
The example in thea utacreates
slide b le a table named DEPT80, which contains details of all the
G er a
h insfdepartment
employees working 80. Notice that the data for the DEPT80 table comes from
j es
Bri n-tratable.
the EMPLOYEES n
o the existence of a database table and check the column definitions by using
You can verify
n
the DESCRIBE command.
However, 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:
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• Data types
• CREATE TABLE statement
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a youamay
After you create a table,
G r bl need to change the table structure for any of the following
reasons:
i j esh nsfe
r
B omitted
• You traa column.
n -
• Your nocolumn definition or its name needs to be changed.
• You need to remove columns.
• You want to put the table into read-only mode
You can do this by using the ALTER TABLE statement.
columns:
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
Adding a Column
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Guidelines for Adding
G a a Column
r a bl
h sfe columns.
• You can
r i jesaddraornmodify
B cannot
• You
n -t specify where the column is to appear. The new column becomes the last
n
column.o
The example in the slide adds a column named JOB_ID to the DEPT80 table. The JOB_ID
column becomes the last column in the table.
Note: If a table already contains rows when a column is added, the new column is initially null
or takes the default value for all the rows. You can add a mandatory NOT NULL column to a
table that contains data in the other columns only if you specify a default value. You can add a
NOT NULL column to an empty table without the default value.
Modifying a Column
value.
ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a definition
You can modify a column
r a bl by using the ALTER TABLE statement with the MODIFY
value.Brij
eshmodification
clause. Column
n s fe can include changes to a column’s data type, size, and default
n - tra
no
Guidelines
• You can increase the width or precision of a numeric column.
• You can increase the width of character columns.
• You can decrease the width of a column if:
- The column contains only null values
- The table has no rows
- The decrease in column width is not less than the existing values in that column
• You can change the data type if the column contains only null values. The exception to
this is CHAR-to-VARCHAR2 conversions, which can be done with data in the columns.
• You can convert a CHAR column to the VARCHAR2 data type or convert a VARCHAR2
column to the CHAR data type only if the column contains null values or if you do not
change the size.
• A change to the default value of a column affects only subsequent insertions to the
table.
Dropping a Column
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can drop a column
G l by using the ALTER TABLE statement with the DROP
a fromaba table
r
r i j esh ansfe
COLUMN clause.
B n-tr
Guidelines
• Then o may or may not contain data.
column
• Using the ALTER TABLE DROP COLUMN statement, only one column can be dropped at a
time.
• The table must have at least one column remaining in it after it is altered.
• After a column is dropped, it cannot be recovered.
• A primary key that is referenced by another column cannot be dropped, unless the
cascade option is added.
• Dropping a column can take a while if the column has a large number of values. In this
case, it may be better to set it to be unused and drop it when there are fewer users on the
system to avoid extended locks.
Note: Certain columns can never be dropped, such as columns that form part of the
partitioning key of a partitioned table or columns that form part of the PRIMARY KEY of an
index-organized table. For more information about index-organized tables and partitioned
tables, refer to Oracle Database Concepts and Oracle Database Administrator’s Guide.
columns as unused.
• You use the DROP UNUSED COLUMNS option to remove the
columns that are marked as unused.
• You can specify the ONLINE keyword to indicate that DML
operations on the table will be allowed while marking the
column or columns UNUSED.
ALTER TABLE <table_name>
SET UNUSED(<column_name> [ , <column_name>]);
OR s a
ALTER TABLE <table_name> a
)h ฺ
UNUSED COLUMN <column_name> [ , <column_name>];
o m
ilฺc Guide
SET
a
@ gm ent
ALTER TABLE <table_name>
i 5 7
S t ud
DROP UNUSED COLUMNS;
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The SET UNUSED option
G a marks
r a blone or more columns as unused so that they can be dropped
sh onnssystem
when the demand
i jetarget fe resources is lower. Specifying this clause does not actually
remove
B r
the
t r a
columns from each row in the table (that is, it does not restore the disk
space used -
n these columns). Therefore, the response time is faster than if you executed the
noby
DROP clause. Unused columns are treated as if they were dropped, even though their column
data remains in the table’s rows. After a column has been marked as unused, you have no
access to that column. A SELECT * query will not retrieve data from unused columns. In
addition, the names and types of columns marked as unused will not be displayed during a
DESCRIBE statement, and you can add to the table a new column with the same name as an
unused column. The SET UNUSED information is stored in the USER_UNUSED_COL_TABS
dictionary view.
You can specify the ONLINE keyword to indicate that DML operations on the table will be
allowed while marking the column or columns UNUSED. The code example shows the use of
SET UNUSED COLUMN that sets a column unused forever using the ONLINE keyword.
ALTER TABLE dept80 SET UNUSED(hire_date)ONLINE;
Note: The guidelines for setting a column to be UNUSED are similar to those for dropping a
column.
Note: A subsequent DROP UNUSED COLUMNS will physically remove all unused columns from a
table, similar to a DROP COLUMN.
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Read-Only Tables
s a
ALTER TABLE employees READ WRITE; a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can specify READ
G a ONLYatoblplace a table in read-only mode. When the table is in READ
ONLY mode, s h cannot
you f r any DML statements that affect the table or any SELECT ...
eissue
j e
ri statements. s
an You can issue DDL statements as long as they do not modify any
B
FOR UPDATE
- t r
n Operations on indexes associated with the table are allowed when the table
data in theotable.
n ONLY
is in READ mode.
Specify READ/WRITE to return a read-only table to read/write mode.
Note: You can drop a table that is in READ ONLY mode. The DROP command is executed only
in the data dictionary, so access to the table contents is not required. The space used by the
table will not be reclaimed until the tablespace is made read/write again, and then the
required changes can be made to the block segment headers, and so on.
For information about the ALTER TABLE statement, see the course titled Oracle Database
12c: SQL Workshop II.
Lesson Agenda
• Database objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
– Naming rules
• Data types
• CREATE TABLE statement
• Overview of constraints: NOT NULL, UNIQUE, PRIMARY
KEY, FOREIGN KEY, CHECK constraints
• Creating a table using a subquery
• ALTER TABLE statement
a
• DROP TABLE statement has )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Dropping a Table
• Removes the table and all its data entirely if the PURGE
clause is specified
• Invalidates dependent objects and removes object
privileges on the table
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The DROP TABLE statement
G a amoves
r bl a table to the recycle bin or removes the table and all its
r
statement i e hnotanresult
data from thesdatabase
jdoes e
sfentirely.
in space
Unless you specify the PURGE clause, the DROP TABLE
being released back to the tablespace for use by other
B
objects, and - t r
nthe space continues to count toward the user’s space quota. Dropping a table
n o
invalidates the dependent objects and removes object privileges on the table.
When you drop a table, the database loses all the data in the table and all the indexes
associated with it.
Syntax
DROP TABLE table [PURGE]
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: Use the FLASHBACK TABLE statement to restore a dropped table from the recycle bin.
This is discussed in detail in the course titled Oracle Database 12c: SQL Workshop II.
Quiz
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Answer: a, b, d Ga
r a bl
h
r i jes ransfe
B n-t
no
Summary
In this lesson, you should have learned how to use the CREATE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Table Descriptions
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Schema Description
Overall Description
The Oracle Database sample schemas portray a sample company that operates worldwide to
fill orders for several different products. The company has three divisions:
• Human Resources: Tracks information about employees and facilities
• Order Entry: Tracks product inventories and sales through various channels
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
HR DEPARTMENTS
department_id
LOCATIONS
location_id
department_name street_address
manager_id postal_code
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
location_id city
state_province
JOB_HISTORY
employee_id
start_date EMPLOYEES
end_date employee_id
job_id first_name COUNTRIES
department_id last_name country_id
email country_name
phone_number region_id
hire_date
JOBS
job_id
s a
job_id
salary
commission_pct ) h a
job_title manager_id o m
c uideฺ
min_salary i l ฺ
REGIONS
max_salary
department_id
g ma region_name
n t G
region_id
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
. . .
M/sฺSeed Infotech Ltdฺ
DESCRIBE job_history
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
SQL Developer
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Oracle SQL Developer
G r bl graphical tool designed to improve your productivity and
a is aafree
sh nsfeof everyday database tasks. With just a few clicks, you can easily
simplify the development
createB rijedebug
and
t r astored procedures, test SQL statements, and view optimizer plans.
-
on which is the visual tool for database development, simplifies the following
SQL Developer,
tasks:
n
• Browsing and managing database objects
• Executing SQL statements and scripts
• Editing and debugging PL/SQL statements
• Creating reports
You can connect to any target Oracle database schema by using standard Oracle database
authentication. When connected, you can perform operations on objects in the database.
SQL Developer is the interface to administer the Oracle Application Express Listener. The
new interface enables you to specify global settings and multiple database settings with
different database connections for the Application Express Listener. SQL Developer provides
the option to drag and drop objects by table or column name onto the worksheet. It provides
improved DB Diff comparison options, GRANT statement support in the SQL editor, and DB
Doc reporting. Additionally, SQL Developer includes support for Oracle Database 12c
features.
• Is developed in Java
• Supports Windows, Linux, and Mac OS X platforms
• Enables default connectivity using the JDBC Thin driver
• Connects to Oracle Database version 9.2.0.1 and later
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Oracle SQL Developer
G r a bl along with Oracle Database 12c Release 1 by default. SQL
a is shipped
Developer is s h sfein Java, leveraging the Oracle JDeveloper integrated development
developed
r i
environment je (IDE).r anTherefore, it is a cross-platform tool. The tool runs on Windows, Linux,
B - t
on system (OS) X platforms.
and Mac operating
n
The default connectivity to the database is through the Java Database Connectivity (JDBC)
Thin driver, and therefore, no Oracle Home is required. SQL Developer does not require an
installer and you need to simply unzip the downloaded file. With SQL Developer, users can
connect to Oracle Databases 9.2.0.1 and later, and all Oracle database editions, including
Express Edition.
Note: For Oracle Database 12c Release 1, you will have to download and install SQL
Developer. SQL Developer is freely downloadable from the following link:
http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html
For instructions on how to install SQL Developer, see the website at:
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
SQL Developer.
• You can create and test connections for:
– Multiple databases
– Multiple schemas
• SQL Developer automatically imports any connections
defined in the tnsnames.ora file on your system.
• You can export connections to an Extensible Markup
Language (XML) file. s a
a
) hin ฺ
• Each additional database connection created is olisted
m e
c
the Connections Navigator hierarchy. ailฺ Guid
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a Developer
A connection is a SQL
r a bl object that specifies the necessary information for
connecting tosahspecificfe
database as a specific user of that database. To use SQL Developer,
r
you must ihave n s one
je atraleast database connection, which may be existing, created, or imported.
B n-t
You can n o and test connections for multiple databases and for multiple schemas.
create
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 open the Database Connections dialog
box, SQL Developer automatically imports any connections defined in the tnsnames.ora file
on your system.
Note: On Windows, if the tnsnames.ora file exists, but its connections are not being used
by SQL Developer, define TNS_ADMIN as a system environment variable.
You can export connections to an XML file so that you can reuse it.
You can create additional connections as different users to the same database or to connect
to the different databases.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
To create a database
G r a bl perform the following steps:
aconnection,
h sfe tabbed page, right-click Connections and select New Connection.
1. On the
r i jesConnections
n
2. InBthe New - t r/a
Select Database Connection window, enter the connection name. Enter the
non and password of the schema that you want to connect to.
username
a. From the Role drop-down list, you can select either default or SYSDBA. (You
choose SYSDBA for the sys user or any user with database administrator
privileges.)
b. You can select the connection type as:
Basic: In this type, enter host name and SID for the database that you want to
connect to. Port is already set to 1521. You can also choose to enter the Service
name directly if you use a remote database connection.
TNS: You can select any one of the database aliases imported from the
tnsnames.ora file.
LDAP: You can look up database services in Oracle Internet Directory, which is a
component of Oracle Identity Management.
Advanced: You can define a custom Java Database Connectivity (JDBC) URL to
connect to the database.
after you close the SQL Developer connection and open it again, you are not prompted
for the password.
3. The connection gets added in the Connections Navigator. You can expand the
connection to view the database objects and view object definitions (dependencies,
details, statistics, and so on).
Note: From the same New/Select Database Connection window, you can define connections
to non-Oracle data sources using the Access, MySQL, and SQL Server tabs. However, these
connections are read-only connections that enable you to browse objects and data in that
data source.
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G r bl
a aconnection,
After you create a database you can use the Connections Navigator to browse
h sinfea database schema, including Tables, Views, Indexes, Packages,
through manysobjects
i jeTriggers,
B n-tran and Types.
r
Procedures,
SQL Developer
n o 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, details about columns,
constraints, grants, statistics, triggers, and so on are displayed on an easy-to-read tabbed
page.
If you want to see the definition of the EMPLOYEES table as shown in the slide, perform the
following steps:
1. Expand the Connections node in the Connections Navigator.
2. Expand Tables.
3. Click EMPLOYEES. By default, the Columns tab is selected. It shows the column
description of the table. Using the Data tab, you can view the table data and also enter
new rows, update data, and commit these changes to the database.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a canaalso
In SQL Developer, you
G r bl display the structure of a table using the DESCRIBE
command. The shresult of e
nsf a column must contain data.
the command is a display of column names and data types, as well
as an B rije trofawhether
indication
-
non
Browsing Files
Use the File Navigator to explore the file system and open
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
system files.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/ort o u
r i
Copyright © 2014, Oracle its affiliates. All rights reserved.
i (b ense
u t am e lic
Browsing Database G aObjects
r a bl
h Navigator
fe to browse and open system files.
You can use
r i jestherFile
n s
B viewnthe
• To - t aFile Navigator, click the View tab and select Files, or select View > Files.
• To n
o
view the contents of a file, double-click a file name to display its contents in the SQL
Worksheet area.
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 the
many context-sensitive menus.
• View the data definition language (DDL) for adjustments
such as creating a new object or editing an existing
schema object. s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
SQL Developer supports
G l
a theabcreation of any schema object by executing a SQL statement in
r
h sfe you can create objects by using the context menus. When
created,r i
youjescanrAlternatively,
SQL Worksheet.
an objects using an edit dialog box or one of the many context-sensitive
edit
B
menus. on - t
n
As new objects are created or existing objects are edited, the DDL for those adjustments is
available for review. An Export DDL option is available if you want to create the full DDL for
one or more objects in the schema.
The slide shows how to create a table using the context menu. To open a dialog box for
creating a new table, right-click Tables and select New Table. The dialog boxes to create and
edit database objects have multiple tabs, each reflecting a logical grouping of properties for
that type of object.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a box,
In the Create Table dialog
r a blif you do not select the Advanced check box, you can create a
table quickly s
r i j e byhspecifying
a n s fe columns and some frequently used features.
If you B
select the
n - trAdvanced check box, the Create Table dialog box changes to one with
o in which you can specify an extended set of features while you create the
multiple options,
n
table.
The example in the slide shows how to create the DEPENDENTS table by selecting the
Advanced check box.
To create a new table, perform the following steps:
1. In the Connections Navigator, right-click Tables and select Create TABLE.
2. In the Create Table dialog box, select Advanced.
3. Specify the column information.
4. Click OK.
Although it is not required, you should also specify a primary key by using the Primary Key tab
in the dialog box. Sometimes, you may want to edit the table that you have created; to do so,
right-click the table in the Connections Navigator and select Edit.
2 4 6 8 10
1 3 5 7 9 11
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You may want to useathe shortcut
G r a bl keys or icons to perform certain tasks such as executing a
r
executed. i eshcan
SQL statement,
jYou runningfe
a n
use
s a script, and viewing the history of the SQL statements that you have
the SQL Worksheet toolbar that contains icons to perform the
B - t r
on
following tasks:
n
1. Run Statement: Executes the statement where the cursor is located in the Enter SQL
Statement box. You can use bind variables in the SQL statements, but not substitution
variables.
2. Run Script: Executes all the 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. Autotrace: Generates trace information for the statement
4. Explain Plan: Generates the execution plan, which you can see by clicking the Explain
tab
5. SQL Tuning Advisory: Analyzes high-volume SQL statements and offers tuning
recommendations
6. Commit: Writes any changes to the database and ends the transaction
7. Rollback: Discards any changes to the database, without writing them to the database,
and ends the transaction
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
Enter SQL
statements.
s a
a
)h ฺ
o m
a ilฺc Guide
Results
@ gmare ent
i 5 7 here.
shown
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
When you connect to
G r a bl a SQL Worksheet window for that connection automatically
aa database,
i shusenthe
opens. You can
jeAll s feSQL Worksheet to enter and execute SQL, PL/SQL, and SQL*Plus
B r
statements. SQL
t r a PL/SQL commands are supported as they are passed directly from
and
n -
the SQL Worksheet
o to the Oracle database. The SQL*Plus commands that are used in SQL
n
Developer must be interpreted by the SQL Worksheet before being passed to the database.
The SQL Worksheet currently supports a number of SQL*Plus commands. Commands that
are not supported by the SQL Worksheet are ignored and not sent to the Oracle database.
Through the SQL Worksheet, you can execute the SQL statements and some of the
SQL*Plus commands.
SQL statements.
F9 F5
F5
F9
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a shows
The example in the slide
r a bl the difference in output for the same query when the F9 key
h
r i jes ransisfeused versus the output when F5 or Run Script is used.
or Execute Statement
B n-t
no
1
To run the code, click either: 2
• Execute Script (F9), or
• Run Script (F5) Select a connection from
3 the drop-down list.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
To open a script file a
G and display
r a bl the code in the SQL Worksheet area, perform the following
steps:
i j esh nsfe
r
Bthe files
1. In a
trnavigator, select (or navigate to) the script file that you want to open.
n -
no
2. Double-click the file to open it. The code of the script file is displayed in the SQL
Worksheet area.
3. Select a connection from the connection drop-down list.
4. To run the code, click the Run Script (F5) icon on the SQL Worksheet toolbar. If you
have not selected a connection from the connection drop-down list, a connection dialog
box will appear. Select the connection that you want to use for the script execution.
Alternatively, you can also do the following:
1. Select File > Open. The Open dialog box is displayed.
2. In the Open dialog box, select (or navigate to) the script file that you want to open.
3. Click Open. The code of the script file is displayed in the SQL Worksheet area.
4. Select a connection from the connection drop-down list.
5. To run the code, click the Run Script (F5) icon on the SQL Worksheet toolbar. If you
have not selected a connection from the connection drop-down list, a connection dialog
box will appear. Select the connection that you want to use for the script execution.
Before
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
formatting
s a
a
)h ฺ
m
a i l ฺco uide
After
g m nt G
formatting
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You may want to format
G r bl
a theaindentation, spacing, capitalization, and line separation of the
SQL code. SQL
r i j eshDeveloper
n s fe has a feature for formatting SQL code.
B thenSQL
To format - tracode, right-click in the statement area and select Format.
no in the slide, before formatting, the SQL code has the keywords not capitalized
In the example
and the statement not properly indented. After formatting, the SQL code is beautified with the
keywords capitalized and the statement properly indented.
Using Snippets
examples.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You may want to useacertain b
G a l fragments when you use the SQL Worksheet or create or
code
r
h sforeprocedure. SQL Developer has a feature called Snippets. Snippets
edit a PL/SQL
are code r i jes function
fragmentsr ansuch as SQL functions, optimizer hints, and miscellaneous PL/SQL
B - t
programming
n ontechniques. You can drag snippets to 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.
Inserting a
snippet
Editing the
snippet a
a s
m )h ฺ
o
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
To insert a Snippet into
G a youracode
r bl in a SQL Worksheet or in a PL/SQL function or procedure,
h sthe feSnippets window to the desired place in your code. Then you can
edit the r i jes sorfrom
drag the snippet
syntax a n
that the SQL function is valid in the current context. To see a brief
B
descriptionoof - t
na SQL function in a tool tip, place the cursor over the function name.
n
The example in the slide shows that CONCAT(char1, char2)is dragged from the Character
Functions group in the Snippets window. Then the CONCAT function syntax is edited and the
rest of the statement is added as in the following:
SELECT CONCAT(first_name, last_name)
FROM employees;
4
Select the operations
from the drop-down
Actions list.
1
3
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
t am etable
The recycle bin is a dataudictionary lic containing information about dropped objects. Dropped
a
G eobjects
tables and any associated a l
b such as indexes, constraints, nested tables, and the likes are
h r
not removedje
r i and
a sf space. They continue to count against user space quotas, until
s still noccupy
B purged
specifically
o
database because n -troffrom the recycle bin or the unlikely situation where they must be purged by the
tablespace space constraints.
n
To use the recycle bin, perform the following steps:
1. In the Connections navigator, select (or navigate to) the recycle bin.
2. Expand Recycle Bin and click the object name. The object details are displayed in the
SQL Worksheet area.
3. Click the Actions drop-down list and select the operation that you want to perform on the
object.
Database Reporting
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
SQL Developer provides
G a many
r a blreports about the database and its objects. These reports can
i j eshthenfollowing
be grouped into
s fe categories:
r
B Your
• About traDatabase reports
• Database n -
o Administration reports
n
• Table reports
• PL/SQL reports
• Security reports
• XML reports
• Jobs reports
• Streams reports
• All Objects reports
• Data Dictionary reports
• User-Defined reports
To display reports, click the Reports tab on the left of the window. Individual reports are
displayed in tabbed panes on the right of the window; for each report, you can select (using a
drop-down list) the database connection for which to display the report. For reports about
objects, the objects shown are only those visible to the database user associated with the
selected database connection, and the rows are usually ordered by Owner. You can also
create your own user-defined reports.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
Organize reports i 5 7in folders.
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
User-defined reportsaare reports
G r a bl created by SQL Developer users. To create a user-defined
report, perform
i j eshthe following
n s fe steps:
r
B n-trthe
1. Right-click a User Defined Reports node under Reports and select Add Report.
noCreate Report dialog box, specify the report name and the SQL query to retrieve
2. In the
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 in the directory for user-specific information.
Shortcut to switch
between connections 2
s a
a
)h ฺ
Links to popular search
o m
engines and discussion
a ilฺc Guide
forums
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a aofbldevelopers, SQL Developer has added quick links to popular
To enhance the productivity
G
search engines
j es s f er forums such as AskTom, Google, and so on. Also, you have
hand discussion
shortcut
B i torsome
ricons an of the frequently used tools such as Notepad, Microsoft Word, and
- t
on available to you.
Dreamweaver,
n
You can add external tools to the existing list or even delete shortcuts to the tools that you do
not use frequently. To do so, perform the following steps:
1. From the Tools menu, select External Tools.
2. In the External Tools dialog box, select New to add new tools. Select Delete to remove
any tool from the list.
Setting Preferences
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can customize many
G a aspects
r a bl of the SQL Developer interface and environment by
hDeveloperfe preferences according to your needs. To modify SQL Developer
r i jesselect
modifying SQL
n s
B n-tra
preferences, Tools, and then Preferences.
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
While working with SQL
G r a bl if the Connections Navigator disappears or if you cannot
a Developer,
h sinfeits original place, perform the following steps to fix the problem:
dock the Logswindow
e
r i j r an
B SQL
1. Exit
-Developer.
t
2. Opennoanterminal window and use the locate command to find the location of
windowinglayout.xml.
3. Go to the directory that has windowinglayout.xml and delete it.
4. Restart SQL Developer.
s a
The File > Data The View > Data a
)h ฺ
Modeler menu options Modeler menu
o m
allow you to open,
save, and print design a ilฺc Guide
options provide
navigation and view
models.
@ gm ent
options.
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Using the integratedaversion of
G r a blthe SQL Developer Data Modeler, you can:
h import,fe and save a database design
• Create,
r i jesopen, n s
B nmodify,
• Create, - tra and delete Data Modeler objects
noData Modeler in a pane, click Tools, and then Data Modeler. The Data Modeler
To display
menu under Tools includes additional commands, for example, that enable you to specify
design rules and preferences.
Summary
Developer to do:
• Browse, create, and edit database objects
• Execute SQL statements and scripts in SQL Worksheet
• Create and save custom reports
• Browse the Data Modeling options in SQL Developer
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
SQL Developer is a a
G r a bl tool to simplify database development tasks. Using SQL
free graphical
Developer, youshcannbrowse,
s fe create, and edit database objects. You can use SQL Worksheet
to runB rijestatements
SQL
t r a and scripts. SQL Developer enables you to create and save your own
-
special setoofnreports for repeated use.
n
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Using SQL*Plus
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
following:
• Log in to SQL*Plus
• Edit SQL commands
• Format the output by using SQL*Plus commands
• Interact with script files
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a SELECT
You might want to create
r a bl statements that can be used repeatedly. This appendix
shof SQL*Plus
covers the use
s fe commands to execute SQL statements. You learn how to format
outputB rije SQL*Plus
using
t r n
a commands, edit SQL commands, and save scripts in SQL*Plus.
-
non
SQL statements
Server
SQL*Plus
Query results
Buffer
s a
a
)h ฺ
o m
a ilฺc Guide
SQL
@ gm ent
scripts
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
SQL and SQL*Plus G a abl
es
SQL is a command
j
h language
s f er that is used for communication with the Oracle server from any
tool orB ri traOracle
application.
n SQL contains many extensions. When you enter a SQL statement,
-
noinna part of the memory called the SQL buffer and remains there until you enter a
it is stored
new SQL statement. SQL*Plus is an Oracle tool that recognizes and submits SQL statements
to the Oracle 9i 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 12c: SQL Workshop I C - 3
M/sฺSeed Infotech Ltdฺ
SQL SQL*Plus
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• A language • An environment
• ANSI-standard • Oracle-proprietary
• Keywords cannot be • Keywords can be
abbreviated. abbreviated.
• Statements manipulate • Commands do not
data and table definitions allow manipulation of
in the database. values in the database.
s a
) h a
m
c uideฺ
o
i l ฺ
SQL SQL SQL*Plus
g ma SQL*Plus n t G
statements buffer commands
i 5 7@ tude buffer
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a abSQL
The following table compares
G l and SQL*Plus:
r
SQLBrij
esh ansfe SQL*Plus
- t r
n for communicating with the Recognizes SQL statements and sends
n o
Is a language
Oracle server to access data them to the server
Is based on American National Standards Is the Oracle-proprietary interface for
Institute (ANSI)–standard SQL executing SQL statements
Manipulates data and table definitions in the Does not allow manipulation of values in the
database database
Is entered into the SQL buffer on one or Is entered one line at a time, not stored in
more lines the SQL buffer
Does not have a continuation character Uses a dash (–) as a continuation character
if the command is longer than one line
Cannot be abbreviated Can be abbreviated
Uses a termination character to execute Does not require termination characters;
commands immediately executes commands immediately
Uses functions to perform some formatting Uses commands to format data
SQL*Plus: Overview
• Log in to SQL*Plus.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
Category Purpose
Environment Affect the general behavior of SQL statements for the session
Format Format query results
File manipulation Save, load, and run script files
Execution Send SQL statements from the SQL buffer to the Oracle server
Edit Modify SQL statements in the buffer
Interaction Create and pass variables to SQL statements, print variable
values, and print messages to the screen
Miscellaneous Connect to the database, manipulate the SQL*Plus environment,
and display column definitions
Logging In to SQL*Plus
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
sqlplus [username[/password[@database]]]
s a
2 a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a adepends
How you invoke SQL*Plus
G r bl on the type of operating system that you are running
r i j esh aon.nsfe
Oracle Database
To logB r environment, perform the following steps:
in from -atLinux
n
no your Linux desktop and select terminal.
1. Right-click
2. Enter the sqlplus command shown in the slide.
3. Enter the username, password, and database name.
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.
of a table:
DESC[RIBE] tablename
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In SQL*Plus, you can
G a displaya l structure of a table by using the DESCRIBE command. The
bthe
r
h sisfea display of column names and data types, as well as an indication if
jes contain
result of the command
i
B n-tran data.
a column r must
no
In the syntax:
tablename The name of any existing table, view, or synonym that is accessible to
the user
To describe the DEPARTMENTS table, use the following command:
SQL> DESCRIBE DEPARTMENTS
Name Null Type
----------------------- -------- ---------------
DESCRIBE departments
• A[PPEND] text
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
SQL*Plus commands
G r a bl one line at a time and are not stored in the SQL buffer.
a are entered
h
Command
r i jes ransfe Description
B n-text
A[PPEND] t Adds text to the end of the current line
n
C[HANGE] o / old / new Changes old text to new in the current line
C[HANGE] / text / Deletes text from the current line
CL[EAR] BUFF[ER] Deletes all lines from the SQL buffer
DEL Deletes current line
DEL n Deletes line n
DEL m n Deletes 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 appears.
• I[NPUT]
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• I[NPUT] text
• L[IST]
• L[IST] n
• L[IST] m n
• R[UN]
• n
• n text a
h a s
• 0 text )
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a abl
Command h G r
Description
eInserts
i j es n s f an indefinite number of lines
B r
I[NPUT]
t r a
-
non
I[NPUT] text Inserts a line consisting of text
L[IST] Lists all lines in the SQL buffer
L[IST] n Lists one line (specified by n)
L[IST] m n Lists a range of lines (m to n) inclusive
R[UN] Displays and runs the current SQL statement in the buffer
n Specifies the line to make the current line
n text Replaces line n with text
0 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 (-).
LIST
1 SELECT last_name
2* FROM employees
1
1* SELECT last_name
A , job_id
s a
1* SELECT last_name, job_id a
)h ฺ
o m
a ilฺc Guide
LIST g m nt
1 SELECT last_name, job_id
i 5 7 @ t u de
2* FROM employees
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
• Use the L[IST]
G a command
r a bl to display the contents of the SQL buffer. The asterisk (*)
beside s h 2 in the
line
s febuffer indicates that line 2 is the current line. Any edits that you
r i jeapply n
B n-tra current line.
made to the
•
no the number of the current line by entering the number (n) of the line that you
Change
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.
LIST
1* SELECT * from employees
c/employees/departments
1* SELECT * from departments
s a
a
)h ฺ
m
LIST
a i l ฺco uide
1* SELECT * from departments
g m nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
• Use L[IST] toadisplay b
G a thel contents of the buffer.
• Use the sC[HANGE] r
h sfecommand to alter the contents of the current line in the SQL buffer.
r i j e n the employees table with the departments table. The new
areplace
Bthis case,
In
- t r
nonline is displayed.
current
• Use the L[IST] command to verify the new contents of the buffer.
• SAVE filename
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• GET filename
• START filename
• @ filename
• EDIT filename
• SPOOL filename
• EXIT
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a ablwith the Oracle server. SQL*Plus commands control the
SQL statements communicate
G
h query
environment,sformat
j e s f erresults, and manage files. You can use the commands described
in the B ri ttable:
following r an
on -
Command
n Description
SAV[E] filename [.ext] Saves the current contents of the SQL buffer to a file.
[REP[LACE]APP[END]] Use APPEND to add to an existing file; use REPLACE to
overwrite an existing file. The default extension is
.sql.
GET filename [.ext] Writes the contents of a previously saved file to the
SQL buffer. The default extension for the file name is
.sql.
STA[RT] filename [.ext] 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]] Invokes the editor to edit the contents of a saved file
SPO[OL] [filename[.ext]| Stores query results in a file. OFF closes the spool file.
OFF|OUT] OUT closes the spool file and sends the file results to
the printer.
EXIT Quits SQL*Plus
LIST
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
SAVE my_query
Created file my_query
START my_query
SERVEROUTPUT Command
Option Description
APP[END] Adds the contents of the buffer to the end of the file s a
that you specify
a
)h ฺ
o m
OFF Stops spooling
a ilฺc Guide
g m nt
OUT Stops spooling and sends
i 5 7 @ t u deyour computer’s
the file to
standard (default)
t a mprinterhis S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The SPOOL command
G l results in a file or optionally sends the file to a printer. The
a storesabquery
SPOOL command h hassbeen r
fe enhanced. You can now append to, or replace an existing file,
r i jes rayou
where previously n could use SPOOL only to create (and replace) a file. REPLACE is the
B
default. on-
t
n
To spool the output generated by commands in a script without displaying the output on
screen, use SET TERMOUT OFF. SET TERMOUT OFF does not affect the output from
commands that run interactively.
You must use quotation marks around file names that contain white space. To create a valid
HTML file using SPOOL APPEND commands, you must use PROMPT or a similar command to
create the HTML page header and footer. The SPOOL APPEND command does not parse
HTML tags. SET SQLPLUSCOMPAT[IBILITY] to 9.2 or earlier to disable the CREATE,
APPEND, and SAVE parameters.
s a
a
)h ฺ
SET AUTOTRACE ON
m
-- The AUTOTRACE report includes both the optimizer
a i lฺco uide
-- execution path and the SQL statement execution
g m nt G
-- statistics
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
EXPLAIN shows theaquery execution
G r a bl path by performing an EXPLAIN PLAN. STATISTICS
h sfestatistics. The formatting of your AUTOTRACE report may vary
displays SQLsstatement
r
depending i jeon theraversion
n of the server to which you are connected and the configuration of
B - t
n n
the server.oThe DBMS_XPLAN package provides an easy way to display the output of the
EXPLAIN PLAN command in several predefined formats.
Notes
• For additional information about the package and subprograms, refer to Oracle
Database PL/SQL Packages and Types Reference 12c.
• For additional information about the EXPLAIN PLAN, refer to Oracle Database SQL
Reference 12c.
• For additional information about Execution Plans and the statistics, refer to Oracle
Database Performance Tuning Guide 12c.
Summary
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G r a bl
a environment
SQL*Plus is an execution that you can use to send SQL commands to the
h and tosfedit
e and save SQL commands. You can execute commands from the
r i jesor from
database server
n
B n-tra
SQL prompt a script file.
no
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no
M/sฺSeed Infotech Ltdฺ
Objectives
s a
h a
SELECT {*|[DISTINCT] column|expression [alias],...}
FROM table; m) ฺ o
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In its simplest form, a
G a SELECT
a l
bstatement must include the following:
r
• A SELECT
r i j eshclause,
n s e specifies the columns to be displayed
fwhich
• AB FROM clause,
n - tra which identifies the table containing the columns that are listed in the
no clause
SELECT
In the syntax:
SELECT Is a list of one or more columns
* Selects all columns
DISTINCT Suppresses duplicates
column|expression Selects the named column or the expression
alias Gives different headings to the selected columns
FROM table Specifies the table containing the columns
Note: Throughout this course, the words keyword, clause, and statement are used as follows:
• A keyword refers to an individual SQL element—for example, SELECT and FROM are
keywords.
• A clause is a part of a SQL statement (for example, SELECT employee_id,
last_name).
• A statement is a combination of two or more clauses (for example, SELECT * FROM
employees).
Oracle Database 12c: SQL Workshop I D - 3
M/sฺSeed Infotech Ltdฺ
SELECT Statement
SELECT *
FROM job_history;
WHERE Clause
• Example: a
a s
SELECT location_id from departments
m )h ฺ
o
ilฺc Guide
WHERE department_name = 'Marketing';
a
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The WHERE clause specifies
G r bl
a aacondition to filter rows, producing a subset of the rows in the
eshspecifies
table. A condition
operators.rItijreturns a
a n s fea combination of one or more expressions and logical (Boolean)
value of TRUE, FALSE, or NULL. The example in the slide retrieves the
B - t r
location_id
n onof the marketing department.
The WHERE clause can also be used to update or delete data from the database.
Example:
UPDATE departments
SET department_name = 'Administration'
WHERE department_id = 20;
and
DELETE from departments
WHERE department_id =20;
ORDER BY Clause
• Syntax:
SELECT * FROM table
[WHERE condition]
[ORDER BY {<column>|<position> } [ASC|DESC] [, ...] ];
• Example:
SELECT last_name, department_id, salary
FROM employees
s a
ORDER BY department_id ASC, salary DESC; a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The ORDER BY clause
G r a bl the order in which the rows should be displayed. The rows
a specifies
can be sortedsin h sfe or descending fashion. By default, the rows are displayed in
i jeorder.rascending
B n-t an
ascendingr
no in the slide retrieves rows from the employees table ordered first by ascending
The example
order of department_id, and then by descending order of salary.
GROUP BY Clause
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
DDL statements enable
G l the attributes of an object without altering the applications
a you toabalter
h You r
that access thesobject.
database r i
users n sfecanwork
je areraperforming also use DDL statements to alter the structure of objects while
in the database. These statements are most frequently
B - t
used to:
n on
• Create, alter, and drop schema objects and other database structures, including the
database itself and database users
• Delete all the data in schema objects without removing the structure of these objects
• Grant and revoke privileges and roles
Oracle Database implicitly commits the current transaction before and after every DDL
statement.
database.
• Syntax:
CREATE TABLE tablename (
{column-definition | Table-level constraint}
[ , {column-definition | Table-level constraint} ] * )
• Example:
CREATE TABLE teach_dept (
s a
department_id NUMBER(3) PRIMARY KEY, a
)h ฺ
o m
ilฺc Guide
department_name VARCHAR2(10));
a
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Use the CREATE TABLE
G a statement
r a bl to create a table in the database. To create a table, you
must have the s h sTABLE
e CREATE fe privilege and a storage area in which to create objects.
r i j n
The table Bowner n - trathe database owner automatically gain the following privileges on the table
and
no
after it is created:
• INSERT
• SELECT
• REFERENCES
• ALTER
• UPDATE
The table owner and the database owner can grant the preceding privileges to other users.
• Example 2:
Example 1 in the slide adds a new column called location_id to the teach_dept table.
Example 2 updates the existing department_name column from VARCHAR2(10) to
VARCHAR2(30), and adds a NOT NULL constraint to it.
• The DROP TABLE statement removes the table and all its
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• DROP TABLE with the PURGE clause drops the table and
releases the space that is associated with it.
DROP TABLE teach_dept PURGE;
s a
• a
The CASCADE CONSTRAINTS clause drops all referential
) h
m
integrity constraints from the table. ฺc o deฺ a il Gui
DROP TABLE teach_dept CASCADE CONSTRAINTS;
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The DROP TABLE statement
G a allows
r a bl you to remove a table and its contents from the database,
h recycle fe bin. Dropping a table invalidates dependent objects and removes
r i jes the
and pushes it to
n s
B n-tra
object privileges on the table.
no clause along with the DROP TABLE statement to release back to the tablespace
Use the PURGE
the space allocated for the table. You cannot roll back a DROP TABLE statement with the PURGE
clause, nor can you recover the table if you have dropped it with the PURGE clause.
The CASCADE CONSTRAINTS clause allows you to drop the reference to the primary key and
unique keys in the dropped table.
GRANT Statement
following operations:
– Insert or delete data.
– Create a foreign key reference to the named table or to a
subset of columns from a table.
– Select data, a view, or a subset of columns from a table.
– Create a trigger on a table.
– Execute a specified function or procedure.
• Example: s a
) h a
GRANT SELECT any table to PUBLIC;
o m
c uideฺ
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
You can use the GRANT
G r a bl to:
a statement
• Assign e h sftoea specific user or role, or to all users, to perform actions on
sprivileges
r i j ran
B n-tobjects
database
noa role to a user, to PUBLIC, or to another role
• Grant
Before you issue a GRANT statement, check that the derby.database.sql authorization
property is set to True. This property enables SQL Authorization mode. You can grant
privileges on an object if you are the owner of the database.
You can grant privileges to all users by using the PUBLIC keyword. When PUBLIC is specified,
the privileges or roles affect all current and future users.
Privilege Types
• ALL PRIVILEGES
• DELETE
• INSERT
• REFERENCES
• SELECT
• UPDATE
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Oracle Database provides
G a a variety
r a bl of privilege types to grant privileges to a user or role:
• Use the
i j sh PRIVILEGES
eALL n s fe privilege type to grant all privileges to the user or role for the
r
B ntable.
specified tra
-
noDELETE privilege type to grant permission to delete rows from the specified table.
• Use the
• Use the INSERT privilege type to grant permission to insert rows into the specified table.
• Use the REFERENCES privilege type to grant permission to create a foreign key reference
to the specified table.
• Use the SELECT privilege type to grant permission to perform SELECT statements on a
table or view.
• Use the UPDATE privilege type to grant permission to use the UPDATE statement on the
specified table.
REVOKE Statement
REVOKE dw_manager
FROM sh;
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The REVOKE statement
G aremoves
r a blprivileges from a specific user (or users) or role to perform
r i j esh aobjects.
actions on database
n sfe It performs the following operations:
B anrole
• Revokes
- trfrom a user, from PUBLIC, or from another role
• Revokes noprivileges for an object if you are the owner of the object or the database owner
Note: To revoke a role or system privilege, you must have been granted the privilege with the
ADMIN OPTION.
schema objects.
• A DML statement is executed when:
– New rows are added to a table by using the INSERT
statement
– Existing rows in a table are modified using the UPDATE
statement
– Existing rows are deleted from a table by using the DELETE
statement
s a
• A transaction consists of a collection of DML statements a
)h ฺ
o m
that form a logical unit of work.
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a a(DML)
Data Manipulation Language
G r bl statements enable you to query or change the contents of
r i j esh aobject.
an existing schema
n sfeThese statements are most frequently used to:
• Add B newnrows- tr of data to a table or view by specifying a list of column values or using a
no to select and manipulate existing data
subquery
• Change column values in the existing rows of a table or view
• Remove rows from tables or views
A collection of DML statements that forms a logical unit of work is called a transaction. Unlike
DDL statements, DML statements do not implicitly commit the current transaction.
INSERT Statement
• Example:
INSERT INTO departments
VALUES (200,'Development',104,1400);
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The INSERT statement
G aaddsarows
r bl to a table. Make sure to insert a new row containing values
h to slistfethe values in the default order of the columns in the table. Optionally,
r i jelists and
for each column
n
you can also
B n-the tracolumns in the INSERT statement.
Example: no
INSERT INTO job_history (employee_id, start_date, end_date,
job_id)
VALUES (120,'25-JUL-06','12-FEB_08','AC_ACCOUNT');
The syntax discussed in the slide allows you to insert a single row at a time. The VALUES
keyword assigns the values of expressions to the corresponding columns in the column list.
table.
• Update more than one row at a time (if required).
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];
• Example:
UPDATE copy_emp
SET s a
a
)h ฺ
o m
• Specify SET column_name= NULL to update a ilฺc Guide
a column value to NULL. @ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The UPDATE statement
G amodifies
r a blthe existing values in a table. Confirm the update operation by
i sh to display
querying the table
jeWHERE n s fe the updated rows. You can modify a specific row or rows by
specifyingrthe
B n-tra clause.
Example: no
UPDATE employees
SET salary = 17500
WHERE employee_id = 102;
In general, use the primary key column in the WHERE clause to identify the row to update. For
example, to update a specific row in the employees table, use employee_id to identify the
row instead of employee_name, because more than one employee may have the same name.
DELETE Statement
a table.
• Syntax:
DELETE [FROM] table
[WHERE condition];
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a ofabSQL
A transaction is a sequence
G l statements that Oracle Database treats as a single unit.
h statements r
fe are used in a database to manage the changes made by DML
r i jesto rgroup
Transaction control
n s
B n-t a these statements into transactions.
statements and
o is assigned a unique transaction_id and it groups SQL statements so that
Each transaction
n
they are either all committed, which means they are applied to the database, or all rolled back,
which means they are undone from the database.
COMMIT Statement
ROLLBACK Statement
SAVEPOINT Statement
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The SAVEPOINT statement
G a identifies
r a bl a point in a transaction to which you can later roll back.
h sfename for each savepoint. If you create a second savepoint with the
jesasaranadistinct
You must specify
i
B n-t nearlier savepoint, the earlier savepoint is erased.
r
same identifier
o has been created, you can either continue processing, commit your work, roll
After a savepoint
n
back the entire transaction, or roll back to the savepoint.
A simple rollback or commit erases all savepoints. When you roll back to a savepoint, any
savepoints marked after that savepoint are erased. The savepoint to which you have rolled
back is retained.
When savepoint names are reused within a transaction, the Oracle Database moves (overrides)
the savepoint from its old position to the current point in the transaction.
Joins
Types of Joins
• Natural join
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
• Equijoin
• Nonequijoin
• Outer join
• Self-join
• Cross join
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
To join tables, you can
G r bl join syntax.
a useaOracle’s
Note: Before h Oracle
esthe s fe9i release, the join syntax was proprietary. The SQL:1999–compliant
r i j n
a offer any performance benefits over the Oracle-proprietary join syntax.
B does
join syntax
n - trnot
no
multiple tables.
• Use table prefixes to improve performance.
• Use table aliases instead of full table name prefixes.
• Table aliases give a table a shorter name.
– This keeps SQL code smaller and uses less memory.
• Use column aliases to distinguish columns that have
identical names but reside in different tables.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
When joining two or a
G r a bl you need to qualify the names of the columns with the table
more tables,
name to avoid
i shambiguity.
jecould n s feWithout the table prefixes, the DEPARTMENT_ID column in the
SELECTrlist r a
be from either the DEPARTMENTS table or the EMPLOYEES table. Therefore,
B - t
n to add the table prefix to execute your query. If there are no common column
it is necessary
n o
names between the two tables, there is no need to qualify the columns. However, using a
table prefix improves performance, because you tell the Oracle server exactly where to find
the columns.
Qualifying column names with table names can be very time consuming, particularly if table
names are lengthy. Therefore, you can use table aliases, instead of table names. Just as a
column alias gives a column another name, a table alias gives a table another name. Table
aliases help to keep SQL code smaller, thereby using less memory.
The table name is specified in full, followed by a space, and then the table alias. For example,
the EMPLOYEES table can be given an alias of e, and the DEPARTMENTS table 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, that table alias
must be substituted for the table name throughout the SELECT statement.
• Table aliases should be meaningful.
• A table alias is valid only for the current SELECT statement.
Oracle Database 12c: SQL Workshop I D - 26
M/sฺSeed Infotech Ltdฺ
Natural Join
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
a abl based on the columns in the two tables that have matching
You can join tables automatically
G
data types and
j es er do this by using the NATURAL JOIN keywords.
hnames.sfYou
Note:B ri join can
The t r n
ahappen only on those columns that have the same names and data types
n -
no If the columns have the same name but different data types, the NATURAL
in both tables.
JOIN syntax causes an error.
In the example in the slide, the COUNTRIES table is joined to the LOCATIONS table by the
COUNTRY_ID column, which is the only column of the same name in both tables. If other
common columns were present, the join would have used them all.
Equijoins
EMPLOYEES DEPARTMENTS
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
…
s a
Primary key a
)h ฺ
o m
Foreign key
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
An equijoin is a joinawith a join
G r a blcondition containing an equality operator. An equijoin
combines rows
i shthatnhave
jedepartments feequivalent values for the specified columns. To determine an
B r
employee’s
t r a name, you compare the values in the DEPARTMENT_ID column in the
-
ntable with the DEPARTMENT_ID values in the DEPARTMENTS table. The
nobetween
EMPLOYEES
relationship the EMPLOYEES and DEPARTMENTS tables is an equijoin; that is, values
in the DEPARTMENT_ID column in both tables must be equal. Often, this type of join involves
primary and foreign key complements.
Note: Equijoins are also called simple joins.
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
… i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In the example in theaslide: bl
h G era
• The SELECT
r i s sf specifies the column names to retrieve:
je raclause
n
B- Employee
n -t lasttable
name, employee ID, and department ID, which are columns in the
n oEMPLOYEES
- Department ID 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:
e.department_id = d.department_id
Because the DEPARTMENT_ID column is common to both tables, it must be prefixed with the
table alias to avoid ambiguity. Other columns that are not present in both the tables need not
be qualified by a table alias, but it is recommended for better performance.
Note: When you use the Execute Statement icon to run the query, SQL Developer suffixes a
“_1” to differentiate between the two DEPARTMENT_IDs.
s a
SELECT d.department_id, d.department_name, l.city h
) a
FROM departments d JOIN locations l o m
c uideฺ
i l ฺ
ma nt G
ON d.location_id = l.location_id
g
7@ tude
WHERE d.department_id IN (20, 50);
i 5
m his S
t a
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
In addition to the join, a
G you may b
a l criteria for your WHERE clause to restrict the rows in
have
hone orsmore r
fe tables in the join. The example in the slide performs a join on the
r i jesand
consideration for
r a n tables and, in addition, displays only those departments with
B
DEPARTMENTS
- t LOCATIONS
non
ID equal to 20 or 50. To add additional conditions to the ON clause, you can add AND clauses.
Alternatively, you can use a WHERE clause to apply additional conditions.
Both queries produce the same output.
s a
a
)h ฺ
o m
a ilฺc Guide
… gm ent
5 7 @ t ud
i S
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
G a creates
The example in the slide
r a bl a nonequijoin to evaluate an employee’s salary grade. The
salary must be
i j eshbetween
n s feany pair of the low and high salary ranges.
r
B nto-trnote
It is important a that all employees appear exactly once when this query is executed. No
employee o is repeated in the list. There are two reasons for this:
n
• 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 the BETWEEN
condition. The Oracle server translates the BETWEEN condition to a pair of AND conditions.
Therefore, using BETWEEN has no performance benefits, but should be used only for logical
simplicity.
Table aliases have been specified in the example in the slide for performance reasons, not
because of possible ambiguity.
• You can use the USING clause to match only one column
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
This query retrieves allathe rowsbin
G a l the COUNTRIES table, which is the left table, even if there is
h r
je ransfe
no match in thesLOCATIONS table.
r i
B n-t
no
s a
a
)h ฺ
o m
…
a ilฺc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
This query retrievesa
G all the rows
r a bl in the DEPARTMENTS table, which is the table at the right,
ishno match in the EMPLOYEES table.
je ransfe
even if there s
r
B n-ti
no
s a
) h a
… m
co uideฺ
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
This query retrieves allathe rowsbin
G a l the EMPLOYEES table, even if there is no match in the
DEPARTMENTSstable. h It salso r
fe retrieves all the rows in the DEPARTMENTS table, even if there is no
r i jeEMPLOYEES
n
B n-tra table.
match in the
no
Self-Join: Example
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
… i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
Sometimes you need
G l to itself. To find the name of each employee’s manager,
ato joinaabtable
you need to join fe r
h the EMPLOYEES table to itself, or perform a self-join. The example in the slide
i jes ranstable
joins therEMPLOYEES to itself. To simulate two tables in the FROM clause, there are two
B n-tworker and manager, for the same table, EMPLOYEES.
aliases, namely
no
In this example, the WHERE clause contains the join that means “where a worker’s manager ID
matches the employee ID for the manager.”
Cross Join
s a
a
)h ฺ
o m
a ilฺc Guide
@ gm ent
… i 5 7
S t ud
u t am this
h g a se
j es and/or
Copyright © 2014,iOracle t o u
r
(b ense
its affiliates. All rights reserved.
i
u t am e lic
The CROSS JOIN syntax
G a specifies
r a bl the cross product. It is also known as a Cartesian product. A
h thescross
fe product of two relations, and is essentially the same as the
r i jes Oracle
cross join produces
n
B n-tra Database notation.
comma-delimited
no any WHERE condition between the two tables in the CROSS JOIN.
You do not specify
Summary
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no