You are on page 1of 91

Course Topics:

1.Introducing Oracle Database 11g


List the features of Oracle Database 11g
Discuss the basic design, theoretical and physical aspects of a relational database
Categorize the different types of SL state!ents
Describe the data set used by the course
Log onto the database using the SL De"eloper en"iron!ent
Sa"e #ueries to files and use script files in SL De"eloper
$.%etrie"ing Data &sing the SL S'L'CT State!ent
List the capabilities of SL S'L'CT state!ents
(enerate a report of data fro! the output of a basic S'L'CT state!ent
Select )ll Colu!ns
Select Specific Colu!ns
&se Colu!n *eading Defaults
&se )rith!etic Operators
&nderstand Operator +recedence
Learn the D'SC%I,' co!!and to display the table structure
-.%estricting and Sorting Data
.rite #ueries that contain a .*'%' clause to li!it the output retrie"ed
List the co!parison operators and logical operators that are used in a .*'%' clause
Describe the rules of precedence for co!parison and logical operators
&se character string literals in the .*'%' clause
.rite #ueries that contain an O%D'% ,/ clause sort the output of a S'L'CT
state!ent
Sort output in descending and ascending order
0.&sing Single1%o2 3unctions to Custo!ize Output
Describe the differences bet2een single ro2 and !ultiple ro2 functions
4anipulate strings 2ith character function in the S'L'CT and .*'%' clauses
4anipulate nu!bers 2ith the %O&5D, T%&5C and 4OD functions
+erfor! arith!etic 2ith date data
4anipulate dates 2ith the date functions
6.&sing Con"ersion 3unctions and Conditional '7pressions
Describe i!plicit and e7plicit data type con"ersion
&se the TO8C*)%, TO85&4,'%, and TO8D)T' con"ersion functions
5est !ultiple functions
)pply the 59L, 5&LLI3, and CO)L'SC' functions to data
&se conditional I3 T*'5 'LS' logic in a S'L'CT state!ent
Page | 1
:.%eporting )ggregated Data &sing the (roup 3unctions
&se the aggregation functions in S'L'CT state!ents to produce !eaningful reports
Create #ueries that di"ide the data in groups by using the (%O&+ ,/ clause
Create #ueries that e7clude groups of date by using the *)9I5( clause
;.Displaying Data 3ro! 4ultiple Tables &sing <oins
.rite S'L'CT state!ents to access data fro! !ore than one table
9ie2 data that generally does not !eet a =oin condition by using outer =oins
<oin a table by using a self =oin
>.&sing Sub1#ueries to Sol"e ueries
Describe the types of proble! that sub1#ueries can sol"e
Define sub1#ueries
List the types of sub1#ueries
.rite single1ro2 and !ultiple1ro2 sub1#ueries
?.&sing the S'T Operators
Describe the S'T operators
&se a S'T operator to co!bine !ultiple #ueries into a single #uery
Control the order of ro2s returned 2hen using the S'T operators
1@.4anipulating Data
Describe each D4L state!ent
Insert ro2s into a table 2ith the I5S'%T state!ent
&se the &+D)T' state!ent to change ro2s in a table
Delete ro2s fro! a table 2ith the D'L'T' state!ent
Sa"e and discard changes 2ith the CO44IT and %OLL,)CA state!ents
'7plain read consistency
11.&sing DDL State!ents to Create and 4anage Tables
Categorize the !ain database ob=ects
%e"ie2 the table structure
List the data types a"ailable for colu!ns
Create a si!ple table
Decipher ho2 constraints can be created at table creation
Describe ho2 sche!a ob=ects 2orB
1$.Creating Other Sche!a Ob=ects
Create a si!ple and co!ple7 "ie2
%etrie"e data fro! "ie2s
Create, !aintain, and use se#uences
Create and !aintain inde7es
Page | 2
Create pri"ate and public synony!s
1-.Controlling &ser )ccess
Differentiate syste! pri"ileges fro! ob=ect pri"ileges
Creating &sers
(ranting Syste! +ri"ileges
Creating and (ranting +ri"ileges to a %ole
Changing /our +ass2ord
(ranting Ob=ect +ri"ileges
+assing On /our +ri"ileges
%e"oBing Ob=ect +ri"ileges
10.4anaging Sche!a Ob=ects
)dding, 4odifying and Dropping a Colu!n
)dding, Dropping and Deferring a Constraint
'nabling and Disabling a Constraint
Creating and %e!o"ing Inde7es
Creating a 3unction1,ased Inde7
+erfor!ing 3lashbacB Operations
Creating an '7ternal Table by &sing O%)CL'8LO)D'% and by &sing
O%)CL'8D)T)+&4+
uerying '7ternal Tables
16.4anaging Ob=ects 2ith Data Dictionary 9ie2s
'7plain the data dictionary
&sing the Dictionary 9ie2s
&S'%8O,<'CTS and )LL8O,<'CTS 9ie2s
Table and Colu!n Infor!ation
uerying the dictionary "ie2s for constraint infor!ation
uerying the dictionary "ie2s for "ie2, se#uence, inde7 and synony! infor!ation
)dding a co!!ent to a table
uerying the dictionary "ie2s for co!!ent infor!ation
1:.4anipulating Large Data Sets
&sing Sub#ueries to 4anipulate Data
%etrie"ing Data &sing a Sub#uery as Source
Inserting &sing a Sub#uery as a Target
&sing the .IT* C*'CA O+TIO5 Aey2ord on D4L State!ents
Types of 4ultitable I5S'%T State!ents
&sing 4ultitable I5S'%T State!ents
4erging ro2s in a table
TracBing Changes in Data o"er a period of ti!e
Page | 3
1;.4anaging Data in Different Ti!e Cones
Ti!e Cones
C&%%'5T8D)T', C&%%'5T8TI4'ST)4+, and LOC)LTI4'ST)4+
Co!paring Date and Ti!e in a SessionDs Ti!e Cone
D,TI4'CO5' and S'SSIO5TI4'CO5'
Difference bet2een D)T' and TI4'ST)4+
I5T'%9)L Data Types
&sing 'ET%)CT, TC8O33S'T and 3%O48TC
&sing TO8TI4'ST)4+,TO8/4I5T'%9)L and TO8DSI5T'%9)L
1>.%etrie"ing Data &sing Sub1#ueries
4ultiple1Colu!n Sub#ueries
+air2ise and 5onpair2ise Co!parison
&sing Scalar Sub#uery '7pressions
Sol"ing proble!s 2ith Correlated Sub#ueries
&pdating and Deleting %o2s &sing Correlated Sub#ueries
&sing the 'EISTS and 5OT 'EISTS operators
&sing the .IT* clause
&sing the %ecursi"e .IT* clause
1?.%egular '7pression Support
&sing the %egular '7pressions 3unctions and Conditions in SL
&sing 4eta Characters 2ith %egular '7pressions
+erfor!ing a ,asic Search using the %'('E+8LIA' function
3inding patterns using the %'('E+8I5ST% function
'7tracting Substrings using the %'('E+8S&,ST% function
%eplacing +atterns &sing the %'('E+8%'+L)C' function
&sing Sub1'7pressions 2ith %egular '7pression Support
&sing the %'('E+8CO&5T function
Page | 4
Relational Database Concept
The prncpes of the reatona mode were rst outned by Dr. E. F.
Codd n a |une 1970 paper tted "A Reatona Mode of Data for Large
Shared Data Banks." In ths paper, Dr. Codd proposed the reatona
mode for database systems.
The common modes used at that tme were herarchca and network,
or even smpe at-e data structures. Reatona database
management systems (RDBMS) soon became very popuar, especay
for ther ease of use and exbty n structure. In addton, a number of
nnovatve vendors, such as Orace, suppemented the RDBMS wth a
sute of powerfu, appcaton deveopment and user-nterface products,
thereby provdng a tota souton.
Components of the Relational Model
Coectons of ob|ects or reatons that store the data
A set of operators that can act on the reatons to produce other
reatons
Data ntegrty for accuracy and consstency
Defnition of a Relational Database
A reatona database uses reatons or two-dmensona tabes to
store nformaton.
For exampe, you mght want to store nformaton about a the empoyees
n your company. In a reatona database, you create severa tabes to
store dherent peces of nformaton about your empoyees, such as an
empoyee tabe, a department tabe, and a saary tabe.
Relating Multiple Tables
Each tabe contans data that descrbes exacty one entty. For
exampe, the EMPLOYEES tabe contans nformaton about empoyees.
Categores of data are sted across the top of each tabe, and
ndvdua cases are sted beow. By usng a tabe format, you can
ready vsuaze, understand, and use nformaton.
Because data about dherent enttes s stored n dherent tabes, you
may need to combne two or more tabes to answer a partcuar
queston. For exampe, you may want to know the ocaton of the
department where an empoyee works. In ths scenaro, you need
nformaton from the EMPLOYEES tabe (whch contans data about
empoyees) and the DEPARTMENTS tabe (whch contans nformaton
about departments). Wth an RDBMS, you can reate the data n one
tabe to the data n another by usng the foregn keys. A foregn key s a
Page | 5
coumn (or a set of coumns) that refers to a prmary key n the same
tabe or another tabe.
You can use the abty to reate data n one tabe to data n another to
organze nformaton n separate, manageabe unts. Empoyee data
can be kept ogcay dstnct from the department data by storng t n
a separate tabe.
Relational Database Terminology
A reatona database can contan one or many tabes. A table s the
basc storage structure of an RDBMS. A tabe hods a the data
necessary about somethng n the rea word, such as empoyees,
nvoces, or customers.
A snge row (or tuple) representng a the data requred for a
partcuar empoyee. Each row n a tabe shoud be dented by a
prmary key, whch permts no dupcate rows. The order of rows s
nsgncant; specfy the row order when the data s retreved.
A column or attrbute contanng the empoyee number. The
empoyee number dentes a unique empoyee n the EMPLOYEES
tabe. In ths exampe, the empoyee number coumn s desgnated
as the primary key. A prmary key must contan a vaue and the
vaue must be unque.
A coumn that s not a key vaue. A coumn represents one knd of
data n a tabe; n ths exampe, the data s the saares of a the
empoyees. Coumn order s nsgncant when storng data; specfy
the coumn order when the data s retreved.
A coumn contanng the department number, whch s aso a
foreign key. A foregn key s a coumn that denes how tabes
reate to each other. A foregn key refers to a prmary key or a
unque key n the same tabe or n another tabe. In the exampe,
DEPARTMENT_ID unquey dentes a department n the
DEPARTMENTS tabe.
A feld can be found at the ntersecton of a row and a coumn. There
can be ony one vaue n t.
A ed may have no vaue n t. Ths s caed a nu vaue. In the
EMPLOYEES tabe, ony those empoyees who have the roe of saes
representatve have a vaue n the COMMISSION_PCT (commsson)
ed.
Using SQL to Query Your Database
Structured query anguage (SOL) s: The ANSI standard anguage for
operatng reatona databases Emcent, easy to earn, and use
functonay compete (Wth SOL, you can dene, retreve, and manpuate
data n the tabes.)
Page | 6
The Human Resources (HR) Schema Descrpton - The tabes used n ths
course
The Human Resources (HR) schema s a part of the Orace Sampe
Schemas that can be nstaed n an Orace database. The practce
sessons n ths course use data from the HR schema.
Table Descriptions
R!"#$S contans rows that represent a regon such as Amerca, Asa,
and so on.
C#U$TR"S contans rows for countres, each of whch s assocated
wth a regon.
L#C%T"#$S contans the specc address of a specc omce,
warehouse, or producton ste of a company n a partcuar country.
D&%RTM$TS shows detas about the departments n whch the
empoyees work. Each department may have a reatonshp
representng the department manager n the EMPLOYEES tabe.
M&L#YS contans detas about each empoyee workng for a
department. Some empoyees may not be assgned to any department.
'#(S contans the |ob types that can be hed by each empoyee.
'#()*"ST#RY contans the |ob hstory of the empoyees. If an
empoyee changes departments wthn a |ob or changes |obs wthn a
department, then a new row s nserted nto ths tabe wth the earer
|ob nformaton of the empoyee.
To extract data from the database, you need to use the SOL SLCT
statement.
Capabilities of SQL SLCT Statements
Page | 7
U$"T+, Retrie-ing Data Using the SQL SLCT
Statement
A SELECT statement retreves nformaton from the database. Wth a
SELECT statement, you can use the foowng capabtes:
&ro.ection: Seect the coumns n a tabe that are returned by a query.
Seect as few or as many of the coumns as requred.
Selection: Seect the rows n a tabe that are returned by a query.
Varous crtera can be used to restrct the rows that are retreved.
'oining: Brng together data that s stored n dherent tabes by
specfyng the nk between them. SOL |ons are covered n more deta
n the esson tted "Dspayng Data from Mutpe Tabes."
(asic SLCT Synta/: SELECT *|{|DISTINCT| column|expression
|alias|,...} FROM table;
SELECT dentes the coumns to be dspayed.
FROM dentes the tabe contanng those coumns.
Selecting %ll Columns
Dspays a coumns and a rows of the DEPARTMENTS tabe:
Exampe: SOL>SELECT *FROM departments;
Selecting Specifc Columns
You can use the SELECT statement to dspay specc coumns of the tabe
by specfyng the coumn names, separated by commas.
Exampe: SOL>SELECT department_d, ocaton_d FROM departments;
Note: coumn headngs are dspayed n uppercase and are eft-agned You
can overrde the coumn headng dspay wth an aas
0riting SQL Statements
SOL statements are not case-senstve.
SOL statements can be entered on one or more nes.
Keywords cannot be abbrevated or spt across nes.
Causes are usuay paced on separate nes.
Indents are used to enhance readabty.
In SOL Deveoper, SOL statements can optonay be termnated by a
semcoon (;). Semcoons are requred when you execute mutpe SOL
statements.
In SOL*Pus, you are requred to end each SOL statement wth a
semcoon (;).
/ecuting SQL Statements
In SOL Deveoper, cck the Run Scrpt con or press |F5| to run the
command or commands n the SOL Worksheet. You can aso cck the
Execute Statement con or press |F9| to run a SOL statement n the
SOL Worksheet. The Execute Statement con executes the statement at
the mouse ponter n the Enter SOL Statement box whe the Run Scrpt
con executes a the statements n the Enter SOL Statement box. The
Page | 8
Execute Statement con dspays the output of the query on the Resuts
tabbed page whe the Run Scrpt con emuates the SOL*Pus dspay
and shows the output on the Scrpt Output tabbed page.
In SOL*Pus, termnate the SOL statement wth a semcoon, and then
press |Enter| to run the command.
%rithmetic /pressions
An arthmetc expresson can contan coumn names, constant numerc
vaues, and the arthmetc operators. Create expressons wth number and
date data by usng arthmetc operators.

Exampes:
SOL>SELECT ast_name, saary, saary + 300 FROM empoyees;
SOL>SELECT ast_name, saary, 12*saary+100 FROM empoyees;
SOL>SELECT ast_name, saary, 12*(saary+100) FROM empoyees;
Note: Use parentheses to renforce the standard order of precedence and
to mprove carty. For exampe, the expresson n the sde can be wrtten
as (12*saary)+100 wth no change n the resut.
Defning a $ull 1alue
Nu s a vaue that s unavaabe, unassgned, unknown, or
nappcabe.
Nu s not the same as zero or a bank space.
Arthmetc expressons contanng a nu vaue evauate to nu.
Exampes:
SOL>SELECT ast_name, |ob_d, saary, commsson_pct FROM
empoyees;
SOL>SELECT ast_name, 12*saary*commsson_pct FROM empoyees;
Defning a Column %lias
A coumn aas renames a coumn headng
A coumn aas s usefu wth cacuatons
A coumn aas mmedatey foows the coumn name (There can aso
be the optona AS keyword between the coumn name and aas.)
A coumn aas requres doube quotaton marks f t contans spaces or
speca characters, or f t s case-senstve
Exampes:
SOL>SELECT ast_name AS name, commsson_pct comm FROM
empoyees;
Page | 9
SOL>SELECT ast_name "Name", saary*12 "Annua Saary" FROM
empoyees;
Concatenation #perator
A concatenaton operator Lnks coumns or character strngs to other
coumns
A concatenaton operator Is represented by two vertca bars (||)
A concatenaton operator Creates a resutant coumn that s a
character expresson
Exampe:
SOL>SELECT ast_name|||ob_d AS "Empoyees" FROM empoyees;
Literal Character Strings
A tera s a character, a number, or a date that s ncuded n the
SELECT statement.
Date and character tera vaues must be encosed wthn snge
quotaton marks.
Each character strng s output once for each row returned
Exampe:
SOL> SELECT ast_name ||' s a '|||ob_d AS "Empoyee Detas" FROM
empoyees;
SOL> SELECT department_name || ' Department' || q'|'s Manager Id: |' ||
manager_d AS "Department and Manager" FROM departments;
%lternati-e Quote 234 #perator
If the tera tsef contans a snge quotaton mark, you can use the quote
(q) operator and seect your own quotaton mark demter.
You can choose any convenent demter, snge-byte or mutbyte, or any
of the foowng character pars: | |, { }, ( ), or < >.
In the exampe shown, the strng contans a snge quotaton mark, whch
s normay nterpreted as a demter of a character strng. By usng the q
operator, however, brackets || are used as the quotaton mark demters.
The strng between the brackets demters s nterpreted as a tera
character strng
Duplicate Ro5s
To emnate dupcate rows n the resut, ncude the D"ST"$CT keyword n
the SELECT cause mmedatey after the SELECT keyword
Exampes: SOL>SELECT DISTINCT department_d FROM empoyees;
Displaying the Table Structure
Use the DSCR"( command to dspay the structure of a tabe.Or, seect
the tabe n the Connectons tree and use the Coumns tab to vew the
tabe structure.
Page | 10
Syntax: SOL>DESC|RIBE| tablename
Restrict the ro5s of data that are displayed
Syntax: SELECT *|{|DISTINCT| column|expression |alias|,...} FROM table
|WHERE condition(s)|;
The 0*R clause follo5s the 6R#M clause7
Note: You can restrct the rows that are returned from the query by usng
the WHERE cause. A WHERE cause contans a condton that must be met
and t drecty foows the FROM cause. If the condton s true, the row
meetng the condton s returned.
Exampes:
SOL>SELECT empoyee_d, ast_name, |ob_d, department_d FROM
empoyees
WHERE department_d = 90 ;
Note: You cannot use coumn aas n the WHERE cause
Character Strings and Dates
Character strngs and date vaues are encosed wth snge quotaton
marks.
Character vaues are case-senstve and date vaues are format-
senstve.
The defaut date dspay format s DD-MON-RR.
Exampes: SOL>SELECT ast_name, |ob_d, department_d FROM
empoyees WHERE
ast_name = 'Whaen';
SOL>SELECT ast_name FROM empoyees WHERE hre_date =
'17-FEB-96;
Page | 11
U$"T+8 Restricting and
Sorting Data
Comparison #perators
Comparson operators are used n condtons that compare one expresson
to another vaue or expresson. They are used n the WHERE cause n the
foowng format:
Syntax : .. WHERE expr operator value
Note: The symbos != and = can aso represent the not equal to
condton.
Exampes: SOL> SELECT ast_name, saary FROM empoyees WHERE
saary <= 3000;
SOL> SELECT ast_name, saary FROM empoyees WHERE
saary BETWEEN 2500 AND 3500;
SOL> SELECT empoyee_d, ast_name, saary, manager_d
FROM empoyees
WHERE manager_d IN (100, 101, 201);
SOL> SELECT rst_name FROM empoyees WHERE rst_name
LIKE 'S%';
Combining 0ildcard Characters
You can combne the two wdcard characters (%, _) wth tera characters
for pattern matchng:
Exampe: SOL>SELECT ast_name FROM empoyees WHERE ast_name
LIKE '_o%' ;
Using the $ULL Conditions
Test for nus wth the IS NULL operator.
SOL>SELECT ast_name, manager_d FROM empoyees WHERE
manager_d IS NUL;
Defning Conditions Using the Logical #perators
%$D requres both the component condtons to be true
Exampe: SOL>SELECT empoyee_d, ast_name, |ob_d, saary FROM
empoyees WHERE saary >= 10000 AND |ob_d LIKE '%MAN%';
#R requres ether component condton to be true:
Exampe: SOL>SELECT empoyee_d, ast_name, |ob_d, saary FROM
empoyees WHERE saary >= 10000 OR |ob_d LIKE '%MAN%';
Note: The NOT operator can aso be used wth other SOL operators, such
as BETWEEN, LIKE, and NULL.
... WHERE |ob_d NOT IN ('AC_ACCOUNT', 'AD_VP')
Page | 12
... WHERE saary NOT BETWEEN 10000 AND 15000
... WHERE ast_name NOT LIKE '%A%'
... WHERE commsson_pct IS NOT NULL
SOL>SELECT ast_name, |ob_d FROM empoyees WHERE |ob_d NOT IN
('IT_PROG', 'ST_CLERK', 'SA_REP')
Rules of &recedence
Exampe: SOL>SELECT ast_name, |ob_d, saary FROM empoyees WHERE
|ob_d = SA_REP' OR |ob_d = 'AD_PRES' AND saary > 15000;
In ths exampe, there are two condtons:
The rst condton s that the |ob ID s AD_PRES and the saary s
greater than $15,000.
The second condton s that the |ob ID s SA_REP.
Therefore, the SELECT statement reads as foows:
"Seect the row f an empoyee s a presdent and earns more than
$15,000, or f the empoyee s a saes representatve."
Using &arentheses
SOL>SELECT ast_name, |ob_d, saary FROM empoyees WHERE (|ob_d
= 'SA_REP' OR |ob_d = 'AD_PRES') AND saary > 15000;
In ths exampe, there are two condtons:
The rst condton s that the |ob ID s AD_PRES or SA_REP.
The second condton s that the saary s greater than $15,000.
Therefore, the SELECT statement reads as foows:
"Seect the row f an empoyee s a presdent or a saes representatve,
and f the empoyee earns more than $15,000."
Page | 13
Using the #RDR (Y Clause
Sort retreved rows wth the ORDER BY cause:
ASC: Ascendng order, defaut
DESC: Descendng order
The ORDER BY cause comes ast n the SELECT statement:
SOL>SELECT ast_name, |ob_d, department_d, hre_date FROM
empoyees ORDER BY hre_date;
Sorting in descending order
SOL>SELECT ast_name, |ob_d, department_d, hre_date FROM
empoyees ORDER BY hre_date DESC;
Sorting by column alias9
SOL>SELECT empoyee_d, ast_name, saary*12 annsa FROM empoyees
ORDER BY annsa ;
Sorting by using the column:s numeric position9
SOL>SELECT ast_name, |ob_d, department_d, hre_date FROM
empoyees ORDER BY 3;
Sorting by multiple columns
SOL>SELECT ast_name, department_d, saary FROM empoyees ORDER
BY department_d, saary DESC;
$ote9 The default sort order is ascending9
Numerc vaues are dspayed wth the owest vaues rst (for exampe,
1 to 999).
Date vaues are dspayed wth the earest vaue rst (for exampe, 01-
|AN-92 before
01-|AN-95).
Character vaues are dspayed n the aphabetca order (for exampe,
"A" rst and "Z" ast).
Nu vaues are dspayed ast for ascendng sequences and rst for
descendng sequences.
You can aso sort by a coumn that s not n the SELECT st.
Substitution 1ariables
Use substtuton varabes to Temporary store vaues wth snge-
ampersand (&) and doube-ampersand (&&) substtuton
Use substtuton varabes to suppement the foowng:
WHERE condtons
ORDER BY causes
Coumn expressons
Tabe names
Entre SELECT statements
Page | 14
SOL>SELECT empoyee_d, ast_name, saary, department_d FROM
empoyees WHERE empoyee_d = &empoyee_num ;
In Ths Exampe user w get a PROMPT for an empoyee number and then
dspays the empoyee number, ast name, saary, and department
number for that empoyee.
Wth the snge ampersand, the user s prompted every tme the command
s executed f the varabe does not exst.
Note: Use snge quotaton marks for date and character vaues
SOL>SELECT ast_name, department_d, saary*12 FROM empoyees
WHERE |ob_d = '&|ob_tte' ;
Using the Double+%mpersand Substitution 1ariable
Use doube ampersand (&&) f you want to reuse the varabe vaue
wthout promptng the user each tme:
You can use the doube-ampersand (&&) substtuton varabe f you want
to reuse the varabe vaue wthout promptng the user each tme. The
user sees the prompt for the vaue ony once. In the exampe n the sde,
the user s asked to gve the vaue for the varabe, coumn_name, ony
once. The vaue that s supped by the user (department_d) s used for
both dspay and orderng of data. If you run the query agan, you w not
be prompted for the vaue of the varabe.
SOL Deveoper stores the vaue that s supped by usng the DEFINE
command; t uses t agan whenever you reference the varabe name.
After a user varabe s n pace, you need to use the UNDEFINE command
to deete t:
UNDEFINE coumn_name
SOL>SELECT empoyee_d, ast_name, |ob_d, &&coumn_name FROM
empoyees ORDER BY &coumn_name ;
Using the D6"$ Command
Use the DEFINE command to create and assgn a vaue to a varabe.
Use the UNDEFINE command to remove a varabe.
DEFINE empoyee_num = 200
SOL>SELECT empoyee_d, ast_name, saary, department_d FROM
empoyees WHERE empoyee_d = &empoyee_num ;
UNDEFINE empoyee_num
Using the 1R"6Y Command
Use the VERIFY command to togge the dspay of the substtuton
varabe, both before and after SOL Deveoper repaces substtuton
varabes wth vaues:
Page | 15
SET VERIFY ON
SOL>SELECT empoyee_d, ast_name, saary FROM empoyees WHERE
empoyee_d = &empoyee_num;
SQL 6unctions
Functons are a very powerfu feature of SOL. They can be used to do the
foowng:
Perform cacuatons on data
Modfy ndvdua data tems
Manpuate output for groups of rows
Format dates and numbers for dspay
Convert coumn data types
SOL functons sometmes take arguments and aways return a vaue.
There are two types of functons:
Snge-row functons
Mutpe-row functons
Single+Ro5 6unctions
Features of snge-row functons ncude:
Actng on each row that s returned n the query
Returnng one resut per row
Possby returnng a data vaue of a dherent type than the one that s
referenced
Possby expectng one or more arguments
Can be used n SELECT, WHERE, and ORDER BY causes; can be nested
These functons operate on snge rows ony and return one resut per
row.
There are dherent types of snge-row functons.:
Character functions: Accept character nput and can return both
character and number vaues. Character functons can be dvded nto the
foowng:
Case+Con-ersion 6unctions
LOWER, UPPER, and INITCAP are the three case-converson functons.
LOWER: Converts mxed-case or uppercase character strngs to
owercase
UPPER: Converts mxed-case or owercase character strngs to
uppercase
Page | 16
U$"T+; Using Single+Ro5 6unctions to
Customi<e #utput
INITCAP: Converts the rst etter of each word to uppercase and the
remanng etters to owercase
Exampe: SOL> SELECT 'The |ob d for '||UPPER(ast_name)||' s '||
LOWER(|ob_d) AS "EMPLOYEE DETAILS" FROM empoyees;
Exampe: SOL>SELECT empoyee_d, ast_name, department_d FROM
empoyees WHERE LOWER(ast_name) = 'hggns';
Character+Manipulation 6unctions9 These functons manpuate
character strngs
CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD, and TRIM are the
character-manpuaton functons that are covered n ths esson.
C#$C%T: |ons vaues together (You are mted to usng two
parameters wth CONCAT.)
SU(STR: Extracts a strng of determned ength
L$!T*: Shows the ength of a strng as a numerc vaue
"$STR: Fnds the numerc poston of a named character
L&%D: Returns an expresson eft-padded to the ength of n characters
wth a character expresson
R&%D: Returns an expresson rght-padded to the ength of n
characters wth a character expresson
TR"M: Trms eadng or trang characters (or both) from a character
strng (If trim_character or trim_source s a character tera, you must
encose t wthn snge quotaton marks.)
Note: You can use functons such as UPPER and LOWER wth ampersand
substtuton. For exampe, use UPPER ('&|ob_tte')so that the user does
not have to enter the |ob tte n a specc case
$umber functions: Accept numerc nput and return numerc vaues
R#U$D: Rounds vaue to a speced decma
Using the R#U$D 6unction
The ROUND functon rounds the coumn, expresson, or vaue to n decma
paces.
If the second argument s 0 or s mssng, the vaue s rounded to zero
decma paces.
Page | 17
If the second argument s 2, the vaue s rounded to two decma paces.
Conversey, f the second argument s -2, the vaue s rounded to two
decma paces to the eft (rounded to the nearest unt of 100).
The ROUND functon can aso be used wth date functons. You w see
exampes ater n ths esson.
DU%L Table
The DUAL tabe s owned by the user SYS and can be accessed by a
users. It contans one coumn, DUMMY, and one row wth the vaue X. The
DUAL tabe s usefu when you want to return a vaue ony once (for
exampe, the vaue of a constant, pseudocoumn, or expresson that s not
derved from a tabe wth user data). The DUAL tabe s generay used for
competeness of the SELECT cause syntax, because both SELECT and
FROM causes are mandatory, and severa cacuatons do not need to
seect from the actua tabes.
DUAL s a dummy tabe that you can use to vew resuts from functons
and cacuatons.
SOL> SELECT ROUND (45.923,2), ROUND(45.923,0), ROUND(45.923,-1)
FROM DUAL;
TRU$C: Truncates vaue to a speced decma
SOL> SELECT TRUNC(45.923,2), TRUNC(45.923),TRUNC(45.923,-1) FROM
DUAL;
The TRUNC functon truncates the coumn, expresson, or vaue to n
decma paces.
The TRUNC functon works wth arguments smar to those of the ROUND
functon.
If the second argument s 0 or s mssng, the vaue s truncated to zero
decma paces.
If the second argument s 2, the vaue s truncated to two decma paces.
Conversey, f the second argument s -2, the vaue s truncated to two
decma paces to the eft.
If the second argument s -1, the vaue s truncated to one decma pace
to the eft.
Lke the ROUND functon, the TRUNC functon can be used wth date
functons.
M#D: Returns remander of dvson
For a empoyees wth the |ob tte of Saes Representatve, cacuate the
remander of the saary after t s dvded by 5,000
SOL>SELECT ast_name, saary, MOD(saary, 5000) FROM empoyees
WHERE |ob_d = 'SA_REP';
Page | 18
Using the M#D 6unction
The MOD functon nds the remander of the rst argument dvded by the
second argument. The sde exampe cacuates the remander of the
saary after dvdng t by 5,000 for a empoyees whose |ob ID s SA_REP.
Note: The MOD functon s often used to determne whether a vaue s odd
or even.
Date functions9 Operate on vaues of the DATE data type (A date
functons return a vaue of the DATE data type except the
MONTHS_BETWEEN functon, whch returns a number.)
0or=ing 5ith Dates
The Orace database stores dates n an nterna numerc format: century,
year, month, day, hours, mnutes, and seconds.
The defaut date dspay format s DD-MON-RR.
Enabes you to store 21st-century dates n the 20th century
by specfyng ony the ast two dgts of the year.
Enabes you to store 20th-century dates n the
21st century n the same way.
SOL>SELECT ast_name, hre_date FROM empoyees WHERE
hre_date < '01-FEB-88';
The Orace database stores dates n an nterna numerc format,
representng the century, year, month, day, hours, mnutes, and seconds.
The defaut dspay and nput format for any date s DD-MON-RR. Vad
Orace dates are between |anuary 1, 4712 B.C., and December 31, 9999
A.D.
In the exampe n the sde, the HIRE_DATE coumn output s dspayed n
the defaut format DD-MON-RR. However, dates are not stored n the
database n ths format. A the components of the date and tme are
stored. So, athough a HIRE_DATE such as 17-|UN-87 s dspayed as day,
month, and year, there s aso time and century nformaton assocated
wth the date. The compete data mght be |une 17, 1987, 5:10:43 PM.
Usng the SYSDATE Functon
SYSDATE s a functon that returns:Date and Tme
SOL>SELECT sysdate FROM dua;
Arthmetc wth Dates
Add or subtract a number to or from a date for a resutant
date vaue.
Subtract two dates to nd the number of days between those
dates.
Add hours to a date by dvdng the number of hours by 24.
SOL> SELECT ast_name, (SYSDATE-hre_date)/7 AS WEEKS FROM
empoyees WHERE department_d =90;
Date+Manipulation 6unctions
Page | 19
Date functons operate on Orace dates. A date functons return a vaue
of the DATE data type except MONTHS_BETWEEN, whch returns a numerc
vaue.
M#$T*S)(T0$2date1, date249 Fnds the number of months
between date1 and date2. The resut can be postve or negatve. If
date1 s ater than date2, the resut s postve; f date1 s earer than
date2, the resut s negatve. The nonnteger part of the resut
represents a porton of the month.
%DD)M#$T*S2date, n49 Adds n number of caendar months to date.
The vaue of n must be an nteger and can be negatve.
$>T)D%Y2date, ?char?49 Fnds the date of the next speced day of
the week ('char') foowng date. The vaue of char may be a number
representng a day or a character strng.
L%ST)D%Y2date49 Fnds the date of the ast day of the month that
contans date
The above st s a subset of the avaabe date functons. ROUND and
TRUNC number functons can aso be used to manpuate the date
vaues as shown beow:
R#U$D2date@A?fmt?B49 Returns date rounded to the unt that s
speced by the format mode fmt If the format mode fmt s omtted,
date s rounded to the nearest day.
TRU$C2date@A ?fmt?B49 Returns date wth the tme porton of the day
truncated to the unt that s speced by the format mode fmt. If the
format mode fmt s omtted, date s truncated to the nearest day.
Exampe: dspay the empoyee number, hre date, number of months
empoyed, sx-month revew date, rst Frday after hre date, and the ast
day of the hre month for a empoyees who have been empoyed for
fewer than 100 months.
SOL>SELECT empoyee_d, hre_date, MONTHS_BETWEEN (SYSDATE,
hre_date) TENURE, ADD_MONTHS (hre_date, 6) REVIEW,NEXT_DAY
(hre_date, 'FRIDAY'), LAST_DAY(hre_date) FROM empoyees
WHERE MONTHS_BETWEEN (SYSDATE, hre_date) < 100;
%rithmetic 5ith Dates
Add or subtract a number to or from a date for a resutant date vaue.
Subtract two dates to nd the number of days between those dates.
Add hours to a date by dvdng the number of hours by 24.
Because the database stores dates as numbers, you can perform
cacuatons usng arthmetc operators such as addton and
subtracton. You can add and subtract number constants as we as
dates.
Page | 20
Con-ersion 6unctions
In some cases, the Orace server receves data of one data type where t
expects data of a dherent data type. When ths happens, the Orace
server can automatcay convert the data to the expected data type.
Ths data type converson can be done implicitly by the Orace server or
explicitly by the user.
Impct data type conversons work accordng to the rues expaned n the
next two sdes.
Expct data type conversons are done by usng the converson functons.
Converson functons convert a vaue from one data type to another.
Generay, the form of the functon names foows the conventon data
type TO data type. The rst data type s the nput data type and the
second data type s the output.
Note: Athough mpct data type converson s avaabe, t s
recommended that you do the expct data type converson to ensure the
reabty of your SOL statements.
"mplicit Data Type Con-ersion9 Orace server can automatcay
perform data type converson n an expresson. For exampe, the
expresson hre_date > '01-|AN-90' resuts n the mpct converson from
the strng '01-|AN-90' to a date. Therefore, a VARCHAR2 or CHAR vaue
can be mpcty converted to a number or date data type n an
expresson.
In genera, the Orace server uses the rue for expressons when a data
type converson s needed. For exampe, the expresson grade = 2 resuts
n the mpct converson of the number 20000 to the strng "2" because
grade s a CHAR(2) coumn.
Note: CHAR to NUMBER conversons succeed ony f the character strng
represents a vad number
/plicit Data Type Con-ersion
Page | 21
Unt-5 Using Con-ersion 6unctions and Conditional
/pressions
Using the T#)C*%R 6unction 5ith Dates
T#)C*%R2date, ?format_model?4
TO_CHAR converts a datetme data type to a vaue of VARCHAR2
data type n the format speced by the format_model
A format mode s a character tera that descrbes the format of
datetme stored n a character strng.
For exampe, the datetme format mode for the strng '11-Nov-1999'
s 'DD-Mon-YYYY'. You can use the TO_CHAR functon to convert a
date from ts defaut format to the one that you specfy.
The format mode:
Must be encosed wth snge quotaton marks
Is case-senstve
Can ncude any vad date format eement
Has an fm eement to remove padded banks or suppress eadng
zeros
Is separated from the date vaue by a comma
Exampe: SOL>SELECT empoyee_d, TO_CHAR(hre_date, 'MM/YY')
Month_Hred
FROM empoyees WHERE ast_name = 'Hggns';
lements of the Date 6ormat Model
Page | 22
Exampe: Dspay the dates n a format that appears as "Seventeenth of
|une 1987 12:00:00 AM."
SOL> SELECT ast_name,TO_CHAR(hre_date, 'fmDdspth "of" Month YYYY
fmHH:MI:SS AM') HIREDATE FROM empoyees;
Using the T#)C*%R 6unction 5ith $umbers
When workng wth number vaues, such as character strngs, you shoud
convert those numbers to the character data type usng the TO_CHAR
functon, whch transates a vaue of NUMBER data type to VARCHAR2
data type. Ths technque s especay usefu wth concatenaton
These are some of the format eements that you can use wth the
TO_CHAR functon to dspay a number vaue as a character:
When workng wth number vaues, such as character strngs, you shoud
convert those numbers to the character data type usng the TO_CHAR
functon, whch transates a vaue of NUMBER data type to VARCHAR2
data type. Ths technque s especay usefu wth concatenaton.
Exampe: SOL>SELECT TO_CHAR(saary, '$99,999.00') SALARY FROM
empoyees WHERE ast_name = 'Ernst';
Note: The Orace server dspays a strng of number sgns (#) n pace
of a whoe number whose dgts exceed the number of dgts provded
n the format mode.
The Orace server rounds the stored decma vaue to the number of
decma paces provded n the format mode.
The RR Datetme Format Eement
The RR datetme format eement s smar to the YY datetme format
eement, but t provdes addtona exbty for storng date vaues n
other centures. The RR datetme format eement ets you store 20th
century dates n the 21st century by specfyng ony the ast two dgts of
the year.
If you use the TO_DATE functon wth the YY datetme format eement,
then the year returned aways has the same rst 2 dgts as the current
year. If you use the RR datetme format eement nstead, then the century
Page | 23
of the return vaue vares accordng to the speced two-dgt year and the
ast two dgts of the current year.
That s:
If the speced two-dgt year s 00 to 49, then
o If the ast two dgts of the current year are 00 to 49, then the
returned year has the same rst two dgts as the current year.
o If the ast two dgts of the current year are 50 to 99, then the
rst 2 dgts of the returned year are 1 greater than the rst 2
dgts of the current year.
If the speced two-dgt year s 50 to 99, then
o If the ast two dgts of the current year are 00 to 49, then the
rst 2 dgts of the returned year are 1 ess than the rst 2
dgts of the current year.
o If the ast two dgts of the current year are 50 to 99, then the
returned year has the same rst two dgts as the current year.
Usng the TO_CHAR and TO_DATE Functon wth RR Date Format
To nd empoyees hred before 1990, use the RR date format, whch
produces the same resuts whether the command s run n 1999 or now:
SOL>SELECT ast_name, TO_CHAR(hre_date, 'DD-Mon-YYYY') FROM
empoyees WHERE hre_date < TO_DATE('01-|an-90','DD-Mon-RR');
To nd empoyees who were hred before 1990, the RR format can be
used. Because the current year s greater than 1999, the RR format
nterprets the year porton of the date from 1950 to 1999.
The foowng command, on the other hand, resuts n no rows beng
seected because the YY format nterprets the year porton of the date n
the current century (2090).
Exampe:
SOL>SELECT ast_name, TO_CHAR(hre_date, 'DD-Mon-yyyy') FROM
empoyees WHERE TO_DATE(hre_date, 'DD-Mon-yy') < '01-|an-1990';
Nestng Functons
Exampe:
Dspays the ast names of empoyees n department 60
SOL>SELECT ast_name, UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8),
'_US')) FROM empoyees
WHERE department_d = 60;
The evauaton of the SOL statement nvoves three steps:
1. The nner functon retreves the rst eght characters of the ast
name.
Resut1 = SUBSTR (LAST_NAME, 1, 8)
2. The outer functon concatenates the resut wth _US.
Page | 24
Resut2 = CONCAT(Resut1, '_US')
3. The outermost functon converts the resuts to uppercase.
The entre expresson becomes the coumn headng because no coumn
aas was gven.
Genera functons:
The foowng functons work wth any data type and pertan to usng nus:
NVL (expr1, expr2)
NVL2 (expr1, expr2, expr3)
NULLIF (expr1, expr2)
COALESCE (expr1, expr2, ..., exprn)
NVL
Converts a nu vaue to an actua vaue.Data types that can be used are
date, character, and number.
Exampes: NVL(commsson_pct,0), NVL(hre_date,'01-|AN-97'),
NVL(|ob_d,' No |ob Yet')
Note: Data types must matc
SOL>SELECT ast_name, saary, NVL(commsson_pct, 0), (saary*12) +
(saary*12*NVL(commsson_pct, 0)) AN_SAL FROM empoyees;
NVL2
The NVL2 functon examnes the rst expresson. If the rst expresson s
not nu, then the NVL2 functon returns the second expresson. If the rst
expresson s nu, then the thrd expresson s returned.
Exampe:
SOL>SELECT ast_name, saary, commsson_pct, NVL2(commsson_pct,
'SAL+COMM', 'SAL') ncome
FROM empoyees WHERE department_d IN (50, 80);
The COMMISSION_PCT coumn s examned. If a vaue s detected, the
second expresson of SAL+COMM s returned. If the COMMISSION_PCT
coumn hods a nu vaue, the thrd expresson of SAL s returned.
$ULL"69 Usng the NULLIF Functon
The NULLIF functon compares two expressons. If they are equa, the
functon returns a nu. If they are not equa, the functon returns the rst
expresson. However, you cannot specfy the tera NULL for the rst
expresson.
Syntax: NULLIF (expr1, expr2)
Exampe:
SOL>SELECT rst_name, LENGTH(rst_name) "expr1", ast_name,
LENGTH(ast_name) "expr2",
NULLIF(LENGTH(rst_name), LENGTH(ast_name)) resut FROM
empoyees;
The ength of the rst name n the EMPLOYEES tabe s compared to the
ength of the ast name n the EMPLOYEES tabe. When the engths of the
Page | 25
names are equa, a nu vaue s dspayed. When the engths of the names
are not equa, the ength of the rst name s dspayed.
C#%LSC
The advantage of the COALESCE functon over the NVL functon s that the
COALESCE functon can take mutpe aternate vaues.
If the rst expresson s not nu, the COALESCE functon returns that
expresson; otherwse, t does a COALESCE of the remanng expressons.
Exampe:
SOL>SELECT ast_name,
empoyee_d,COALESCE(TO_CHAR(commsson_pct),TO_CHAR(manager_d
),
'No commsson and no manager') FROM empoyees;
If the manager_d vaue s not nu, t s dspayed. If the manager_d vaue
s nu, then the commsson_pct s dspayed. If the manager_d and
commsson_pct vaues are nu, then "No commsson and no manager" s
dspayed
Conditional /pressions
Provde the use of the IF-THEN-ELSE ogc wthn a SOL statement
Use two methods: CASE expresson , DECODE functon

C%S e/pression
Factates condtona nqures by dong the work of an IF-THEN-ELSE
statement
SOL>SELECT ast_name, |ob_d, saary, CASE |ob_d WHEN 'IT_PROG'
THEN 1.10*saary
WHEN 'ST_CLERK' THEN 1.15*saary
WHEN 'SA_REP' THEN 1.20*saary
ELSE saary END "REVISED_SALARY" FROM empoyees;
The vaue of |OB_ID s decoded. If |OB_ID s IT_PROG, the saary ncrease s
10%; f |OB_ID s ST_CLERK, the saary ncrease s 15%; f |OB_ID s
SA_REP, the saary ncrease s 20%. For a other |ob roes, there s no
ncrease n saary.
DC#D 6unction
The DECODE functon decodes an expresson n a way smar to the
IF-THEN-ELSE ogc that s used n varous anguages. The DECODE
functon decodes expression after comparng t to each search
vaue. If the expresson s the same as search, result s returned.
If the defaut vaue s omtted, a nu vaue s returned where a
search vaue does not match any of the resut vaues.
Exampe: SOL>SELECT ast_name, |ob_d, saary,
DECODE(|ob_d, 'IT_PROG', 1.10*saary, 'ST_CLERK',
1.15*saary, 'SA_REP', 1.20*saary, saary)REVISED_SALARY
FROM empoyees;
Page | 26
The vaue of |OB_ID s tested. If |OB_ID s IT_PROG, the saary ncrease s
10%; f |OB_ID s ST_CLERK, the saary ncrease s 15%; f |OB_ID s
SA_REP, the saary ncrease s 20%. For a other |ob roes, there s no
ncrease n saary.
The same statement can be expressed n pseudocode as an IF-THEN-ELSE
statement:
IF |ob_d = 'IT_PROG' THEN saary = saary*1.10
IF |ob_d = 'ST_CLERK' THEN saary = saary*1.15
IF |ob_d = 'SA_REP' THEN saary = saary*1.20
ELSE saary = saary
Aggregate functons return a snge resut row based on groups of rows,
rather than on snge rows.
Aggregate functons can appear n seect sts and n ORDER BY and
HAVING causes. They are commony used wth the GROUP BY cause n
a SELECT statement, where Orace Database dvdes the rows of a
quered tabe or vew nto groups.
In a query contanng a GROUP BY cause, the eements of the seect
st can be aggregate functons, GROUP BY expressons, constants, or
expressons nvovng one of these.
Orace appes the aggregate functons to each group of rows and
returns a snge resut row for each group.
If you omt the GROUP BY cause, then Orace appes aggregate
functons n the seect st to a the rows n the quered tabe or vew.
You use aggregate functons n the HAVING cause to emnate groups
from the output based on the resuts of the aggregate functons, rather
than on the vaues of the ndvdua rows of the quered tabe or vew.
Types of Group Functons
AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
!roup 6unctions9 Synta/
SELECT !roup_function(column)"
FROM table
|WHERE condition|
|ORDER BY column|;
Page | 27
Unt-6 Reporting Aggregated Data Using the Group Functions
Using the %1! and SUM 6unctions
You can use the AVG, SUM, MIN, and MAX functons aganst the coumns
that can store numerc data.
Exampe: Dspays the average, hghest, owest, and sum of monthy
saares for a saes representatves.
SOL>SELECT AVG(saary), MAX(saary), MIN(saary), SUM(saary) FROM
empoyees WHERE |ob_d LIKE '%REP%';
Exampe: Dspays the empoyee ast name that s rst and the empoyee
ast name that s ast n an aphabetc st of a empoyees:
SOL>SELECT MIN(ast_name), MAX(ast_name) FROM empoyees;
Note: The AVG, SUM, VARIANCE, and STDDEV functons can be used ony
wth numerc data types. MAX and MIN cannot be used wth LOB or LONG
data types.
Using the C#U$T 6unction9
COUNT(*) returns the number of rows n a tabe that satsfy the crtera
of the SELECT statement, ncudng dupcate rows and rows contanng
nu vaues n any of the coumns.
If a WHERE cause s ncuded n the SELECT statement, COUNT(*)
returns the number of rows that satsfy the condton n the WHERE
cause.
The COUNT functon has three formats:
COUNT(*)
COUNT(expr)
COUNT(DISTINCT expr)
Exampe: Dspays the number of empoyees n department 50.
SOL> SELECT COUNT(*) FROM empoyees WHERE department_d = 50;
Usng the DISTINCT Keyword to suppress the countng of any dupcate
vaues n a coumn.
Exampe: Dspays the number of dstnct department vaues that are n
the EMPLOYEES tabe.
SOL> SELECT COUNT(DISTINCT department_d) FROM empoyees;
!roup 6unctions and $ull 1alues9
A group functons gnore nu vaues n the coumn.
However, the NVL functon forces group functons to ncude nu vaues.
Exampes:
1. The average s cacuated based on only those rows n the tabe n
whch a vad vaue s stored n the COMMISSION_PCT coumn. The
average s cacuated as the tota commsson that s pad to a empoyees
dvded by the number of empoyees recevng a commsson (four).
SOL> SELECT AVG(commsson_pct) FROM empoyees;
Page | 28
2. The average s cacuated based on all rows n the tabe, regardess of
whether nu vaues are stored n the COMMISSION_PCT coumn. The
average s cacuated as the tota commsson that s pad to a empoyees
dvded by the tota number of empoyees n the company (20).
SOL> SELECT AVG(NVL(commsson_pct, 0)) FROM
empoyees;
Creating !roups of Data9
GROUP BY Cause Syntax
SOL>SELECT column, !roup_function(column) FROM table |WHERE
condition| |GROUP BY !roup_by_expression| |ORDER BY column|;
Note:
If you ncude a group functon n a SELECT cause, you cannot
seect ndvdua resuts as we, unless the ndvdua coumn
appears n the GROUP BY cause. You receve an error message f
you fa to ncude the coumn st n the GROUP BY cause.
Usng a WHERE cause, you can excude rows before dvdng
them nto groups.
You must ncude the columns n the GROUP BY cause.
You cannot use a coumn aas n the GROUP BY cause.
Using the !R#U& (Y Clause
Exampe: SOL>SELECT department_d, AVG(saary) FROM empoyees
GROUP BY department_d ;
When usng the GROUP BY cause, make sure that a coumns n the
SELECT st that are not group functons are ncuded n the GROUP
BY cause. The exampe n the sde dspays the department number
and the average saary for each department. Here s how ths
SELECT statement, contanng a GROUP BY cause, s evauated:
The SELECT cause speces the coumns to be retreved, as foows:
Department number coumn n the EMPLOYEES tabe
The average of a saares n the group that you speced n the
GROUP BY cause
The FROM cause speces the tabes that the database must
access: the EMPLOYEES tabe
The WHERE cause speces the rows to be retreved. Because there
s no WHERE cause, a rows are retreved by defaut.
The GROUP BY cause speces how the rows shoud be grouped.
The rows are grouped by department number, so the AVG functon
that s apped to the saary coumn cacuates the average saary for
each department.
The GROUP BY coumn does not have to be n the SELECT st.
Exampe:
SOL> SELECT AVG(saary) FROM empoyees GROUP BY
department_d ;
Using the !roup (y Clause on Multiple Columns
Page | 29
You can return summary resuts for groups and subgroups by stng more
than one GROUP BY coumn. You can determne the defaut sort order of
the resuts by the order of the coumns n the GROUP BY cause. In the
exampe n the sde, the SELECT statement contanng a GROUP BY cause
s evauated as foows:
F The SELECT cause speces the coumn to be retreved:
F Department number n the EMPLOYEES tabe
F |ob ID n the EMPLOYEES tabe
F The sum of a saares n the group that you speced n
the GROUP BY cause
F The FROM cause speces the tabes that the database must
access: the EMPLOYEES tabe
F The GROUP BY cause speces how you must group the rows:
F Frst, the rows are grouped by the department number.
F Second, the rows are grouped by |ob ID n the
department number groups.
So the SUM functon s apped to the saary coumn for a |ob IDs n each
department number group.
Restricting !roup Results 5ith the *%1"$! Clause
Syntax: SELECT column, !roup_function FROM table |WHERE
condition|
|GROUP BY !roup_by_expression| |HAVING
!roup_condition| |ORDER BY column|;
Exampe: SOL> SELECT department_d, MAX(saary) FROM empoyees
GROUP BY department_d HAVING MAX(saary)>10000 ;
Note: You can use the GROUP BY cause wthout usng a group functon n
the SELECT st. If you restrct rows based on the resut of a group
functon, you must have a GROUP BY cause as we as the HAVING cause.
Exampe: Dspays the department numbers and average saares for
those departments wth a maxmum saary greater than $10,000:
SOL>SELECT department_d, AVG(saary) FROM empoyees
GROUP BY department_d HAVING max(saary)>10000;
$esting !roup 6unctions
Group functons can be nested to a depth of two functons
Exampe: cacuates the average saary for each department_d and then
dspays the maxmum average saary.
Exampe: Dspay the maxmum average saary
SOL> SELECT MAX(AVG(saary)) FROM empoyees
GROUP BY department_d;
Note: Note that GROUP BY cause s mandatory when nestng group functons.
Page | 30
Usng a Subquery to Sove a Probem
Suppose you want to wrte a query to nd out who earns a saary greater
than Abes saary.
To sove ths probem, you need two queres: one to nd how much Abe
earns, and a second query to nd who earns more than that amount.
You can sove ths probem by combnng the two queres, pacng one
query inside the other query.
The nner query (or subquery) returns a vaue that s used by the outer
query (or main query). Usng a subquery s equvaent to performng two
sequenta queres and usng the resut of the rst query as the search
vaue n the second query.
Syntax:
SELECT select_list FROM table WHERE expr operator (SELECT select_list
FROM table);
Subquery Syntax
A subquery s a SELECT statement that s embedded n the cause of
another SELECT statement.
You can bud powerfu statements out of smpe ones by usng subqueres.
They can be very usefu
when you need to seect rows from a tabe wth a condton that depends
on the data n the tabe
tsef. You can pace the subquery n a number of SOL causes, ncudng
the foowng:
WHERE cause
HAVING cause
FROM cause
In the syntax:
operator ncudes a comparson condton such as >, =, or IN
Note: Comparson condtons fa nto two casses: snge-row operators (>,
=, >=, <, <>, <=) and mutpe-row operators (IN, ANY, ALL).The
subquery s often referred to as a nested SELECT, sub-SELECT, or nner
Page | 31
Unit +C Using Sub+3ueries to
Sol-e Queries
SELECT statement.The subquery generay executes rst, and ts output s
used to compete the query condton for the man (or outer) query.
Exampe:
SOL>SELECT ast_name, saary FROM empoyees WHERE saary >
(SELECT saary
FROM empoyees WHERE ast_name = 'Abe');
Note:The nner query determnes the saary of empoyee Abe. The outer
query takes the resut
of the nner query and uses ths resut to dspay a the empoyees who
earn more than empoyee Abe.
Gudenes for Usng Subqueres
1. Encose subqueres n parentheses.
2. Pace subqueres on the rght sde of the comparson
condton for readabty (However, the subquery can appear
on ether sde of the comparson operator.).

3.Use snge-row operators wth snge-row subqueres and
mutpe-row operators wth mutpe-row subqueres
Types of Subqueres
Snge-row subqueres:
o Oueres that return ony one row from the nner SELECT
statement
o A snge-row subquery s one that returns one row from the
nner SELECT statement. Ths type of subquery uses a snge-
row operator.
Exampe:
1.Dspay the empoyees whose |ob ID s the same as that of empoyee
141:
SOL>SELECT ast_name, |ob_d
FROM empoyees
WHERE |ob_d =
(SELECT |ob_d
FROM empoyees
WHERE empoyee_d = 141);
Page | 32
2.Dspays empoyees who do the same |ob as "Tayor," but earn more
saary than hm.
SOL>SELECT ast_name, |ob_d, saary
FROM empoyees
WHERE |ob_d =
(SELECT |ob_d
FROM empoyees
WHERE ast_name = Tayor)
AND saary >
(SELECT saary
FROM empoyees
WHERE ast_name = Tayor);
Note: The outer and nner queres can get data from dherent tabes.
Usng Group Functons n a Subquery
You can dspay data from a man query by usng a group functon n a
subquery to return a snge row. The subquery s n parentheses and s
paced after the comparson condton.
Exampe:
Dspays the empoyee ast name, |ob ID, and saary of a empoyees
whose saary s equa to the mnmum saary.
SOL>SELECT ast_name, |ob_d, saary
FROM empoyees
WHERE saary =
(SELECT MIN(saary)
FROM empoyees);
The HAVING Cause wth Subqueres
The Orace server executes the subqueres rst.
The Orace server returns resuts nto the HAVING cause of
the man query.
Exampe:
Dspays a the departments that have a mnmum saary greater
than that of department 50.
SOL>SELECT department_d, MIN(saary) FROM empoyees
GROUP BY department_d
HAVING MIN(saary) > (SELECT MIN(saary) FROM empoyees
WHERE department_d = 50);
You can use subqueres not ony n the WHERE cause, but aso n
the HAVING cause. The Orace server executes the subquery and the
resuts are returned nto the HAVING cause of the man query
Page | 33
Mutpe-row subqueres: Oueres that return more than one row
from the nner SELECTstatement Use mutpe-row
comparson operators
Exampe:
Fnd the empoyees who earn the same saary as the mnmum
saary for each department.
SOL>SELECT ast_name, saary, department_d FROM empoyees
WHERE saary IN (SELECT MIN(saary) FROM empoyees GROUP BY
department_d);
Subqueres that return more than one row are caed mutpe-row
subqueres. You use a mutpe-row operator, nstead of a snge-row
operator, wth a mutpe-row subquery. The mutpe-row operator
expects one or more vaues:
Note:
There are aso mutpe-coumn subqueres, whch are queres that
return more than one coumn from the nner SELECT
statement.
Subqueres that return more than one row are caed mutpe-row
subqueres. You use a mutpe-row operator, nstead of a snge-row
operator, wth a mutpe-row subquery. The mutpe-row operator
expects one or more vaues:
Usng the ANY Operator n Mutpe-Row Subqueres
The ANY operator (and ts synonym, the SOME operator) compares a
vaue to each vaue returned by a subquery. The sde exampe
dspays empoyees who are not IT programmers and whose saary s ess
than that of any IT programmer.<ANY means ess than the maxmum.
>ANY means more than the mnmum. =ANY s equvaent to IN.
Exampe:
Dspays empoyees who are not IT programmers and whose saary
s ess than that of any IT programmer.
SOL>SELECT empoyee_d, ast_name, |ob_d, saary FROM
empoyees WHERE saary < ANY
Page | 34
(SELECT saary FROM empoyees WHERE |ob_d =
'IT_PROG') AND |ob_d <> 'IT_PROG';
Usng the ALL Operator n Mutpe-Row Subqueres
The ALL operator compares a vaue to every vaue returned by a
subquery
Exampe:
Dspays empoyees whose saary s ess than the saary of a
empoyees wth a |ob ID of IT_PROG and whose |ob s not IT_PROG.
SOL>SELECT empoyee_d, ast_name, |ob_d, saary FROM
empoyees WHERE saary < ALL
(SELECT saary FROM empoyees WHERE |ob_d = 'IT_PROG')
AND |ob_d <> 'IT_PROG';
Note: >ALL means more than the maxmum and <ALL means ess
than the mnmum.
The NOT operator can be used wth IN, ANY, and ALL operators.
Nu Vaues n a Subquery
Exampe:
Dspay a the empoyees who do not have any subordnates.
SOL>SELECT emp.ast_name FROM empoyees emp WHERE
emp.empoyee_d NOT IN (SELECT mgr.manager_d
FROM empoyees mgr);
Note:
Logcay, ths SOL statement shoud have returned 12 rows.
However, the SOL statement does not return any rows. One of the
vaues returned by the nner query s a nu vaue, and, therefore, the
entre query returns no rows.
The reason s that a condtons that compare a nu vaue resut n a
nu. So whenever nu vaues are key to be part of the resuts set
of a subquery, do not use the NOT IN operator. The NOT IN operator s
equvaent to <> ALL.Notce that the nu vaue as part of the resuts
set of a subquery s not a probem f you use the IN operator. The IN
operator s equvaent to =ANY
TRY: Dspay the empoyees who have subordnates
Page | 35
Set Operators
Set operators co!bine the results of t2o or !ore co!ponent #ueries into one result. ueries containing
set
operators are called compound queries.
/ou can co!bine !ultiple #ueries using the set operators &5IO5, &5IO5 )LL,
I5T'%S'CT, and 4I5&S. )ll set operators ha"e e#ual precedence. If a SL state!ent
contains !ultiple set operators, then Oracle Database e"aluates the! fro! the left to
right unless parentheses e7plicitly specify another order.
The corresponding e7pressions in the select lists of the co!ponent #ueries of a
co!pound #uery !ust !atch in nu!ber and !ust be in the sa!e datatype group
Gsuch as nu!eric or characterH.
&5IO5 Operator
The &5IO5 operator returns all ro2s that are selected by either #uery. &se the &5IO5 operator to
return all ro2s fro! !ultiple tables and eli!inate any duplicate ro2s.
'7a!ple:
Display the current and pre"ious =ob details of all e!ployees. Display each e!ployee only once.
Page | 36
&5IO5 %o2s fro! both #ueries after eli!inating duplications
&5IO5 )LL %o2s fro! both #ueries, including all duplications
I5T'%S'CT %o2s that are co!!on to both #ueries
4I5&S %o2s in the first #uery that are not present in the second #uery
Unit+9.Using the SET Operators
SLIS'L'CT e!ployee8id, =ob8id 3%O4 e!ployees
&5IO5
S'L'CT e!ployee8id, =ob8id 3%O4 =ob8historyJ
The &5IO5 operator eli!inates any duplicate records. If records that occur in both the '4+LO/''S
and the <O,8*ISTO%/ tables are identical, the records are displayed only once
&5IO5 )LL Operator
&se the &5IO5 )LL operator to return all ro2s fro! !ultiple #ueries.
5ote:
The guidelines for &5IO5 and &5IO5 )LL are the sa!e, 2ith the follo2ing t2o e7ceptions that
pertain to &5IO5 )LL: &nliBe &5IO5, duplicate ro2s are not eli!inated and the output is not sorted
by default.
'7a!ples:
Display the current and pre"ious depart!ents of all e!ployees.
SLIS'L'CT e!ployee8id, =ob8id, depart!ent8id
3%O4 e!ployees
&5IO5 )LL
S'L'CT e!ployee8id, =ob8id, depart!ent8id
3%O4 =ob8history
O%D'% ,/ e!ployee8idJ
&5IO5 )LL returns all ro2s selected by either #uery, including all duplicates
I5T'%S'CT Operator
&se the I5T'%S'CT operator to return all ro2s that are co!!on to !ultiple #ueries.
'7a!ple:
Display the e!ployee IDs and =ob IDs of those e!ployees 2ho currently ha"e a =ob title that is the
sa!e as their pre"ious one Gthat is, they changed =obs but ha"e no2 gone bacB to doing the sa!e =ob
they did pre"iouslyH.
SLIS'L'CT e!ployee8id, =ob8id 3%O4 e!ployees
I5T'%S'CT
S'L'CT e!ployee8id, =ob8id 3%O4 =ob8historyJ
5ote:The #uery returns only those records that ha"e the sa!e "alues in the selected colu!ns in both
tables.
4I5&S Operator
&se the 4I5&S operator to return all distinct ro2s selected by the first #uery, but not present in the
second #uery result set Gthe first S'L'CT state!ent 4I5&S the second S'L'CT state!entH.
5ote: The nu!ber of colu!ns !ust be the sa!e and the data types of the colu!ns being selected by the
S'L'CT state!ents in the #ueries !ust belong to the sa!e data type group in all the S'L'CT
state!ents used in the #uery. The na!es of the colu!ns, ho2e"er, need not be identical.
'7a!ple:
Display the e!ployee IDs of those e!ployees 2ho ha"e not changed their =obs e"en once
SLIS'L'CT e!ployee8id 3%O4 e!ployees
4I5&S
S'L'CT e!ployee8id 3%O4 =ob8historyJ
5ote:The empoyee IDs n the |OB_HISTORY tabe are subtracted from those n the
EMPLOYEES tabe. The resuts set dspays the empoyees remanng after the
Page | 37
subtracton; they are represented by rows that exst n the EMPLOYEES tabe, but
do not exst n the |OB_HISTORY tabe. These are the records of the empoyees
who have not changed ther |obs even once.
Set Operator (uidelines
o The e7pressions in the S'L'CT lists of the #ueries !ust !atch in nu!ber and data type. ueries
that use &5IO5, &5IO5 )LL, I5T'%S'CT, and 4I5&S operators in their .*'%' clause !ust
ha"e the sa!e nu!ber and data type of colu!ns in their S'L'CT list. The data type of the
colu!ns in S'L'CT list of the #ueries in the co!pound #uery !ay not be e7actly the sa!e. The
colu!n in second #uery !ust be in the sa!e data type group Gsuch as nu!eric or characterH as the
corresponding colu!n in the first #uery.
o Set operators can be used in sub#ueries.
o /ou should use parentheses to specify the order of e"aluation in #ueries that use the I5T'%S'CT
operator 2ith other set operators. This ensures co!pliance 2ith e!erging SL standards that 2ill
gi"e the I5T'%S'CT operator greater precedence than the other set operators.

The Oracle Ser"er and Set Operators
.hen a #uery uses set operators, the Oracle ser"er eli!inates duplicate ro2s auto!atically e7cept in
the case of the &5IO5 )LL operator. The colu!n na!es in the output are decided by the colu!n list
in the first S'L'CT state!ent. ,y default, the output is sorted in ascending order of the first colu!n of
the S'L'CT clause.
The corresponding e7pressions in the S'L'CT lists of the co!ponent #ueries of a co!pound #uery
!ust !atch in nu!ber and data type. If co!ponent #ueries select character data, the data type of the
return "alues is deter!ined as follo2s:
o If both #ueries select "alues of C*)% data type, of e#ual length, then the returned "alues ha"e the
C*)% data type of that length. If the #ueries select "alues of C*)% 2ith different lengths, then
the returned "alue is 9)%C*)%$ 2ith the length of the larger C*)% "alue.
o If either or both of the #ueries select "alues of 9)%C*)%$ data type, then the returned "alues
ha"e the 9)%C*)%$ data type.
If co!ponent #ueries select nu!eric data, then the data type of the return "alues is deter!ined by
nu!eric precedence. If all #ueries select "alues of the 5&4,'% type, then the returned "alues ha"e
the 5&4,'% data type. In #ueries using set operators, the Oracle ser"er does not perfor! i!plicit
con"ersion across data type groups. Therefore, if the corresponding e7pressions of co!ponent #ueries
resol"e to both character data and nu!eric data, the Oracle ser"er returns an error.
%estrictions on the Set Operators The set operators are sub=ect to the follo2ing
restrictions:
The set operators are not "alid on colu!ns of type ,LO,, CLO,, ,3IL', 9)%%)/,
or nested table.
o The &5IO5, I5T'%S'CT, and 4I5&S operators are not "alid on LO5( colu!ns.
o If the select list preceding the set operator contains an e7pression, then you !ust
pro"ide a colu!n alias for the e7pression in order to refer to it in the order_by_
clause.
o /ou cannot also specify the for_update_clause 2ith the set operators.
o /ou cannot specify the order_by_clause in the subquery of these operators.
o /ou cannot use these operators in S'L'CT state!ents containing T),L' collection
e7pressions.
&sing the O%D'% ,/ Clause in Set Operations
The O%D'% ,/ clause can be used only once in a co!pound #uery. If used, the O%D'% ,/ clause
!ust be placed at the end of the #uery. The O%D'% ,/ clause accepts the colu!n na!e or an alias.
,y default, the output is sorted in ascending order in the first colu!n of the first S'L'CT #uery.
5ote: The O%D'% ,/ clause does not recognize the colu!n na!es of the second S'L'CT #uery. To
a"oid confusion o"er colu!n na!es, it is a co!!on practice to O%D'% ,/ colu!n positions.
'7a!ple:
SLIS'L'CT e!ployee8id, =ob8id,salary 3%O4 e!ployees
&5IO5
S'L'CT e!ployee8id, =ob8id,@ 3%O4 =ob8history
O%D'% ,/ $J
Page | 38
5ote:
The output 2ill be sho2n in ascending order of the =ob8id
If you o!it the O%D'% ,/, then by default the output 2ill be sorted in the ascending order of
e!ployee8id. /ou cannot use the colu!ns fro! the second #uery to sort the output
Sorting uery %esults
&se the O%D'% ,/ clause to order the ro2s selected by a #uery. Sorting by position is
useful in the follo2ing cases:
o To order by a lengthy select list e7pression, you can specify its position in the
O%D'% ,/ clause rather than duplicate the entire e7pression.
o 3or co!pound #ueries containing set operators &5IO5, I5T'%S'CT, 4I5&S, or
&5IO5 )LL, the O%D'% ,/ clause !ust specify positions or aliases rather than
e7plicit e7pressions. )lso, the O%D'% ,/ clause can appear only in the last
co!ponent #uery. The O%D'% ,/ clause orders all ro2s returned by the entire
co!pound #uery.
The !echanis! by 2hich Oracle Database sorts "alues for the O%D'% ,/ clause is
specified either e7plicitly by the 5LS8SO%T initialization para!eter or i!plicitly by
the 5LS8L)5(&)(' initialization para!eter. /ou can change the sort !echanis!
dyna!ically fro! one linguistic sort se#uence to another using the )LT'% S'SSIO5
state!ent.
Page | 39
Data !anipulation language GD4LH state!ents to insert ro2s into a table, update e7isting ro2s in a table, and
delete e7isting ro2s fro! a table. /ou also learn ho2 to control transactions 2ith the CO44IT, S)9'+OI5T,
and %OLL,)CA state!ents.
Data 4anipulation Language
) D4L state!ent is e7ecuted 2hen you:
)dd ne2 ro2s to a table
4odify e7isting ro2s in a table
%e!o"e e7isting ro2s fro! a table
) transaction consists of a collection of D4L state!ents that for! a logical unit of 2orB.
Data 4anipulation Language
Data !anipulation language GD4LH is a core part of SL. .hen you 2ant to add, update, or delete data in the
database, you e7ecute a D4L state!ent. ) collection of D4L state!ents that for! a logical unit of 2orB is
called a transaction.
Consider a banBing database. .hen a banB custo!er transfers !oney fro! a sa"ings account to a checBing
account, the transaction !ight consist of three separate operations: decreasing the sa"ings account, increasing
the checBing account, and recording the transaction in the transaction =ournal. The Oracle ser"er !ust guarantee
that all the three SL state!ents are perfor!ed to !aintain the accounts in proper balance. .hen so!ething
pre"ents one of the state!ents in the transaction fro! e7ecuting, the other state!ents of the transaction !ust be
undone.
5ote: 4ost of the D4L state!ents in this lesson assu!e that no constraints on the table are "iolated.
Constraints are discussed later in this course.
5ote: In SL De"eloper, clicB the %un Script icon or press K36L to run the D4L state!ents. The feedbacB
!essages 2ill be sho2n on the Script Output tabbed page.
)dding a 5e2 %o2 to a Table
)dd ne2 ro2s to a table by using the I5S'%T state!ent
I5S'%T State!ent Synta7:
I5S'%T I5TO table KGcolumn K, column...LHL
9)L&'S (value K, value...LHJ
5ote: .ith this synta7, only one ro2 is inserted at a ti!e.
Inserting 5e2 %o2s:
Insert a ne2 ro2 containing "alues for each colu!n.
List "alues in the default order of the colu!ns in the table.
Optionally, list the colu!ns in the I5S'%T clause.
'nclose character and date "alues 2ithin single #uotation !arBs.
'7a!ple:
SLII5S'%T I5TO depart!entsGdepart!ent8id,
depart!ent8na!e, !anager8id, location8idH
9)L&'S G;@, M+ublic %elationsM, 1@@, 1;@@HJ
Page | 40
10. Manipulating
Data
Inserting %o2s 2ith 5ull 9alues
I!plicit !ethod: O!it the colu!n fro! the
colu!n list.
'7a!ple:
SLII5S'%T I5TO depart!ents Gdepart!ent8id,
depart!ent8na!eH
9)L&'S G-@, M+urchasingMHJ
'7plicit !ethod: Specify the 5&LL Bey2ord in the 9)L&'S clause.
'7a!ple:
SLII5S'%T I5TO depart!ents
9)L&'S G1@@, M3inanceM, 5&LL, 5&LLHJ
Inserting Special 9alues
'7a!ple:
SLII5S'%T I5TO e!ployees Ge!ployee8id,
first8na!e, last8na!e,
e!ail, phone8nu!ber,
hire8date, =ob8id, salary,
co!!ission8pct, !anager8id,
depart!ent8idH
9)L&'S G11-,
MLouisM, M+oppM,
ML+O++M, M616.1$0.06:;M,
S/SD)T', M)C8)CCO&5TM, :?@@,
5&LL, $@6, 11@HJ
5ote: The SYSDATE functon records the current date and tme.
The Oracle ser"er auto!atically enforces all data types, data ranges, and data integrity constraints. )ny colu!n
that is not listed e7plicitly obtains a null "alue in the ne2 ro2.
Co!!on errors that can occur during user input are checBed in the follo2ing order:
F 4andatory "alue !issing for a 5OT 5&LL colu!n
F Duplicate "alue "iolating any uni#ue or pri!ary Bey constraint
F )ny "alue "iolating a C*'CA constraint
F %eferential integrity !aintained for foreign Bey constraint
F Data type !is!atches or "alues too 2ide to fit in colu!n
Creating a Script
/ou can sa"e co!!ands 2ith substitution "ariables to a file and e7ecute the co!!ands in the file.
%un the script file and you are pro!pted for input for each of the a!persand GNH substitution "ariables. )fter
entering a "alue for the substitution "ariable, clicB the OA button. The "alues that you input are then substituted
into the state!ent. This enables you to run the sa!e script file o"er and o"er, but supply a different set of "alues
each ti!e you run it.
'7a!ple:
SLI I5S'%T I5TO depart!ents
Gdepart!ent8id, depart!ent8na!e, location8idH
9)L&'S GNdepart!ent8id, MNdepart!ent8na!eM,NlocationHJ
Copying %o2s fro! )nother Table
'7a!ple:
SLII5S'%T I5TO sales8repsGid, na!e, salary, co!!ission8pctH
Page | 41
S'L'CT e!ployee8id, last8na!e, salary, co!!ission8pct
3%O4 e!ployees
.*'%' =ob8id LIA' MO%'+OMJ
.rite your I5S'%T state!ent 2ith a sub#uery:
Do not use the 9)L&'S clause.
4atch the nu!ber of colu!ns in the I5S'%T clause to those in the sub#uery.
Inserts all the ro2s returned by the sub#uery in the table, sales8reps.
Changing Data in a Table
&+D)T' State!ent Synta7
&+D)T' table
S'T Column P value K, column P value, ...L
K.*'%' conditionLJ
4odify e7isting "alues in a table 2ith the &+D)T' state!ent:
&pdate !ore than one ro2 at a ti!e Gif re#uiredH.
5ote: In general, use the pri!ary Bey colu!n in the .*'%' clause to identify a single ro2 for update. &sing
other colu!ns can une7pectedly cause se"eral ro2s to be updated. 3or e7a!ple, identifying a single ro2 in the
'4+LO/''S table by na!e is dangerous, because !ore than one e!ployee !ay ha"e the sa!e na!e.
&pdating %o2s in a Table
'7a!ple:
SLI&+D)T' e!ployees
S'T depart!ent8id P 6@
.*'%' e!ployee8id P 11-J
9alues for a specific ro2 or ro2s are !odified if you specify the .*'%' clause:
'7a!ple:
SLIUPDATE copy_emp S'T depart!ent8id P 11@J
9alues for all the ro2s in the table are !odified if you o!it the .*'%' clause:
Specify S'T column_nameP 5&LL to update a colu!n "alue to 5&LL.
&pdating T2o Colu!ns 2ith a Sub#uery
'7a!ple:
SLIUPDATE empoyees S'T =ob8id P GS'L'CT =ob8id 3%O4 e!ployees
.*'%' e!ployee8id P $@6H, salary P GS'L'CT salary 3%O4 e!ployees
.*'%' e!ployee8id P $@6H .*'%' e!ployee8id P 11-J
In this uery 2e &pdate e!ployee 11-Ds =ob and salary to !atch those of e!ployee $@6.
&pdating %o2s ,ased on )nother Table
&se the sub#ueries in the &+D)T' state!ents to update ro2 "alues in a table based on "alues fro! another
table
Page | 42
'7a!ple:
SLIUPDATE copy_emp S'T depart!ent8id P GS'L'CT depart!ent8id 3%O4 e!ployees .*'%'
e!ployee8id P 1@@H .*'%' =ob8id P GS'L'CT =ob8id
3%O4 e!ployees .*'%' e!ployee8id P $@@HJ
updates the CO+/8'4+ table based on the "alues fro! the '4+LO/''S table. It changes the depart!ent
nu!ber of all e!ployees 2ith e!ployee $@@Ds =ob ID to e!ployee 1@@Ds current depart!ent nu!ber.
%e!o"ing a %o2 fro! a Table
/ou can re!o"e e7isting ro2s fro! a table by using the D'L'T' state!ent:
D'L'T' State!ent Synta7:
D'L'T' K3%O4L table K.*'%' conditionLJ
'7a!ple:
Specific ro2s are deleted if you specify the .*'%' clause
SLI DELETE FROM departments .*'%' depart!ent8na!e P Q3inanceMJ
SLI D'L'T' 3%O4 depart!ents .*'%' depart!ent8id I5 G-@, 0@HJ
)ll ro2s in the table are deleted if you o!it the .*'%' clause:
SLID'L'T' 3%O4 copy8e!pJ
Deleting %o2s ,ased on )nother Table
SLID'L'T' 3%O4 e!ployees .*'%' depart!ent8id P GS'L'CT depart!ent8id
3%O4 depart!ents .*'%' depart!ent8na!e LIA' MO+ublicOMHJ
&se the sub#ueries in the D'L'T' state!ents to re!o"e ro2s fro! a table based on "alues fro! another table:
T%&5C)T' State!ent
) !ore efficient !ethod of e!ptying a table is by using the T%&5C)T' state!ent.
/ou can use the T%&5C)T' state!ent to #uicBly re!o"e all ro2s fro! a table or cluster. %e!o"ing ro2s 2ith
the T%&5C)T' state!ent is faster than re!o"ing the! 2ith the D'L'T' state!ent for the follo2ing reasons:
1 The T%&5C)T' state!ent is a data definition language GDDLH state!ent and generates no rollbacB
infor!ation. %ollbacB infor!ation is co"ered later in this lesson.
1 Truncating a table does not fire the delete triggers of the table.
Synta7:
T%&5C)T' T),L' table_nameJ
'7a!ple:
SLIT%&5C)T' T),L' copy8e!pJ
%e!o"es all ro2s fro! a table, lea"ing the table e!pty and the table structure intact
Is a data definition language GDDLH state!ent rather than a D4L state!entJ cannot easily be undone
Database Transactions
) database transaction consists of one of the follo2ing:
D4L state!ents that constitute one consistent change to
the data
One DDL state!ent
One data control language GDCLH state!ent
Database Transaction: Start and 'nd
Page | 43
.hen does a database transaction start and endR
) transaction begins 2hen the first D4L state!ent is encountered and ends 2hen one of the follo2ing occurs:
F ) CO44IT or %OLL,)CA state!ent is issued.
F ) DDL state!ent, such as C%')T', is issued.
F ) DCL state!ent is issued.
F The user e7its SL De"eloper or SLS+lus.
F ) !achine fails or the syste! crashes.
)fter one transaction ends, the ne7t e7ecutable SL state!ent auto!atically starts the ne7t transaction.
) DDL state!ent or a DCL state!ent is auto!atically co!!itted and therefore i!plicitly ends a transaction.
)d"antages of CO44IT and %OLL,)CA State!ents
.ith CO44IT and %OLL,)CA state!ents, you can:
'nsure data consistency
+re"ie2 data changes before !aBing changes per!anent
(roup logically1related operations
'7plicit Transaction Control State!ents
/ou can control the logic of transactions by using the CO44IT, S)9'+OI5T, and %OLL,)CA state!ents.
%olling ,acB Changes to a 4arBer
/ou can create a !arBer in the current transaction by using the S)9'+OI5T state!ent, 2hich di"ides the
transaction into s!aller sections. /ou can then discard pending changes up to that !arBer by using the
%OLL,)CA TO S)9'+OI5T state!ent.
5ote, if you create a second sa"epoint 2ith the sa!e na!e as an earlier sa"epoint, the earlier sa"epoint is
deleted.
State of the Data ,efore CO44IT or %OLL,)CA
'"ery data change !ade during the transaction is te!porary until the transaction is co!!itted.
The state of the data before CO44IT or %OLL,)CA state!ents are issued can be described as follo2s:
F Data !anipulation operations pri!arily affect the database bufferJ therefore, the pre"ious state of the data
can be reco"ered.
F The current user can re"ie2 the results of the data !anipulation operations by #uerying the tables.
F Other users cannot "ie2 the results of the data !anipulation operations !ade by the current user. The
Oracle ser"er institutes read consistency to ensure that each user sees data as it e7isted at the last co!!it.
F The affected ro2s are locBedJ other users cannot change the data in the affected ro2s.
State of the Data )fter CO44IT
Page | 44
4aBe all pending changes per!anent by using the CO44IT state!ent. *ere is 2hat happens after a CO44IT
state!ent:
F Data changes are 2ritten to the database.
F The pre"ious state of the data is no longer a"ailable 2ith nor!al SL #ueries.
F )ll users can "ie2 the results of the transaction.
F The locBs on the affected ro2s are releasedJ the ro2s are no2 a"ailable for other users to perfor! ne2 data
changes.
F )ll sa"epoints are erased.
State of the Data )fter %OLL,)CA
Discard all pending changes by using the %OLL,)CA state!ent, 2hich results in the follo2ing:
F Data changes are undone.
F The pre"ious state of the data is restored.
F LocBs on the affected ro2s are released.
%ead Consistency
Database users access the database in t2o 2ays:
F %ead operations GS'L'CT state!entH
F .rite operations GI5S'%T, &+D)T', D'L'T' state!entsH
/ou need read consistency so that the follo2ing occur:
F The database reader and 2riter are ensured a consistent "ie2 of the data.
F %eaders do not "ie2 data that is in the process of being changed.
F .riters are ensured that the changes to the database are done in a consistent !anner.
F Changes !ade by one 2riter do not disrupt or conflict 2ith the changes being !ade by another 2riter.
The purpose of read consistency is to ensure that each user sees data as it e7isted at the last co!!it, before a
D4L operation started.
5ote: The sa!e user can login as different sessions. 'ach session !aintains read consistency in the !anner
described abo"e, e"en if they are the sa!e users.
I!ple!enting %ead Consistency
%ead consistency is an auto!atic i!ple!entation. It Beeps a partial copy of the database in the undo seg!ents.
The read1consistent i!age is constructed fro! the co!!itted data in the table and the old data that is being
changed and is not yet co!!itted fro! the undo seg!ent.
.hen an insert, update, or delete operation is !ade on the database, the Oracle ser"er taBes a copy of the data
before it is changed and 2rites it to an undo segment.
)ll readers, e7cept the one 2ho issued the change, see the database as it e7isted before the changes startedJ they
"ie2 the undo seg!entDs TsnapshotU of the data.
,efore the changes are co!!itted to the database, only the user 2ho is !odifying the data sees the database
2ith the alterations. '"eryone else sees the snapshot in the undo seg!ent. This guarantees that readers of the
data read consistent data that is not currently undergoing change.
.hen a D4L state!ent is co!!itted, the change !ade to the database beco!es "isible to anyone issuing a
S'L'CT state!ent after the co!!it is done. The space occupied by the old data in the undo seg!ent file is
freed for reuse.
If the transaction is rolled bacB, the changes are undone:
F The original, older "ersion of the data in the undo seg!ent is 2ritten bacB to the table.
F )ll users see the database as it e7isted before the transaction began.
Page | 45
11. Using DDL Statements to Create and anage Ta!"es
Database Ob=ects
The Oracle database can contain !ultiple data structures. 'ach structure should be outlined in the database
design so that it can be created during the build stage of database de"elop!ent.
F Table: Stores data
F 9ie2: Subset of data fro! one or !ore tables
F Se#uence: (enerates nu!eric "alues
F Inde7: I!pro"es the perfor!ance of so!e #ueries
F Synony!: (i"es alternati"e na!e to an ob=ect
Oracle Table Structures
F Tables can be created at any ti!e, e"en 2hen users are using the database.
F /ou do not need to specify the size of a table. The size is ulti!ately defined by the a!ount of space
allocated to the database as a 2hole. It is i!portant, ho2e"er, to esti!ate ho2 !uch space a table 2ill use
o"er ti!e.
F Table structure can be !odified online.
5a!ing %ules
/ou na!e database tables and colu!ns according to the standard rules for na!ing any Oracle database ob=ect:
F Table na!es and colu!n na!es !ust begin 2ith a letter and be 1V-@ characters long.
F 5a!es !ust contain only the characters )VC, aVz, @V?, 8 GunderscoreH, W, and X Glegal characters, but their
use is discouragedH.
F 5a!es !ust not duplicate the na!e of another ob=ect o2ned by the sa!e Oracle ser"er user.
F 5a!es !ust not be an Oracle ser"erVreser"ed 2ord.
F /ou !ay also use #uoted identifiers to represent the na!e of an ob=ect. ) #uoted identifier begins and ends
2ith double #uotation !arBs GTH. If you na!e a sche!a ob=ect using a #uoted identifier, then you !ust use
the double #uotation !arBs 2hene"er you refer to that ob=ect. uoted identifiers can be reser"ed 2ords,
although this is not reco!!ended.
To create a table, a user !ust ha"e the C%')T' T),L' pri"ilege and a storage area in 2hich to create ob=ects.
The database ad!inistrator GD,)H uses data control language GDCLH state!ents to grant pri"ileges to users.
Synta7:
C%')T' T),L' Kschema.L table
Gcolumn datatype KD'3)&LT exprLK, ...LHJ
In the synta7:
schema Is the sa!e as the o2nerDs na!e
table Is the na!e of the table
D'3)&LT expr Specifies a default "alue if a "alue is o!itted in the I5S'%T
state!ent
column Is the na!e of the colu!n
datatype Is the colu!nDs data type and length
D'3)&LT Option
Page | 46
.hen you define a table, you can specify that a colu!n should be gi"en a default "alue by using the D'3)&LT
option. This option pre"ents null "alues fro! entering the colu!ns 2hen a ro2 is inserted 2ithout a "alue for
the colu!n. The default "alue can be a literal, an e7pression, or a SL function Gsuch as S/SD)T' or &S'%H,
but the "alue cannot be the na!e of another colu!n or a pseudo colu!n Gsuch as 5'ET9)L or C&%%9)LH.
The default e7pression !ust !atch the data type of the colu!n.
Data Types

Gudenes
F ) LO5( colu!n is not copied 2hen a table is created using a sub#uery.
F ) LO5( colu!n cannot be included in a (%O&+ ,/ or an O%D'% ,/ clause.
F Only one LO5( colu!n can be used per table.
F 5o constraints can be defined on a LO5( colu!n.
F /ou !ight 2ant to use a CLO, colu!n rather than a LO5( colu!n.
Including Constraints
The Oracle ser"er uses constraints to pre"ent in"alid data entry into tables.
/ou can use constraints to do the follo2ing:
F 'nforce rules on the data in a table 2hene"er a ro2 is inserted, updated, or deleted fro! that table. The
constraint !ust be satisfied for the operation to succeed.
F +re"ent the deletion of a table if there are dependencies fro! other tables.
F +ro"ide rules for Oracle tools, such as Oracle De"eloper.
Defining Constraints
Synta7:
CREATE TABLE |schema.|table Gcolumn datatype
KD'3)&LT exprL
Kcolumn_constraintL, ... Ktable_constraintLK,...LHJ
The follo2ing constraint types are "alid:
o 5OT 5&LL
Page | 47
) 5OT 5&LL constraint prohibits a colu!n fro! containing nulls. The 5&LL Bey2ord
by itself does not actually define an integrity constraint, but you can specify it to
e7plicitly per!it a colu!n to contain nulls. /ou !ust define 5OT 5&LL and 5&LL
using inline specification. If you specify neither 5OT 5&LL nor 5&LL, then the default
is 5&LL.
'7a!ple:
SOL>CREATE TABLE empoyees( e!ployee8id 5&4,'%G:H, first8na!e
9)%C*)%$G$@H,
... =ob8id 9)%C*)%$G1@H 5OT 5&LL, CO5ST%)I5T e!p8e!p8id8pB
+%I4)%/ A'/ G'4+LO/''8IDHHJ
o &5I&'
A unque constrant desgnates a coumn as a unque key. A composte
unque key
desgnates a combnaton of coumns as the unque key. When you dene a
unque
constrant nne, you need ony the UNIQUE keyword. When you dene a
unque
constrant out of ne, you must aso specfy one or more coumns. You
must dene a
composte unque key out of ne.To satsfy a unque constrant, no two
rows n the tabe can have the same vaue for the unque key.
When you specfy a unque constrant on one or more coumns, Orace
mpcty
creates an ndex on the unque key. If you are denng unqueness for
purposes of
query performance, then Orace recommends that you nstead create the
unque ndex
expcty usng a CREATE UNIQUE INDEX statement.
'7a!ple:
SLIC%')T' T),L' e!ployeesG e!ployee8id 5&4,'%G:H, last8na!e
9)%C*)%$G$6H 5OT 5&LL, e!ail 9)%C*)%$G$6H, salary 5&4,'%G>,$H,
co!!ission8pct 5&4,'%G$,$H,hire8date D)T' 5OT 5&LL,... CO5ST%)I5T
e!p8e!ail8uB &5I&'Ge!ailHHJ
o +%I4)%/ A'/
) pri!ary Bey constraint designates a colu!n as the pri!ary Bey of a table or "ie2. )
co!posite pri!ary Bey designates a co!bination of colu!ns as the pri!ary Bey.
.hen you define a pri!ary Bey constraint inline, you need only the +%I4)%/ A'/
Bey2ords. .hen you define a pri!ary Bey constraint out of line, you !ust also
specify one or !ore colu!ns. /ou !ust define a co!posite pri!ary Bey out of line.
) pri!ary Bey constraint co!bines a 5OT 5&LL and uni#ue constraint in one
declaration. Therefore, to satisfy a pri!ary Bey constraint:
5o pri!ary Bey "alue can appear in !ore than one ro2 in the table.
5o colu!n that is part of the pri!ary Bey can contain a null.
'7a!ple:
SLI CREATE TABLE empoyees(e!ployee8id 5&4,'%G:H CO5ST%)I5T
e!p8e!p8id8pB +%I4)%/ A'/, first8na!e 9)%C*)%$G$@H,...HJ
%estrictions on +ri!ary Aey Constraints +ri!ary constraints are sub=ect to the
follo2ing restrictions:
Page | 48
) table or "ie2 can ha"e only one pri!ary Bey
None of the coumns n the prmary key can be LOB, LONG, LONG RAW,
VARRAY,
NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-
dened type.
However, the prmary key can contan a coumn of TIMESTAMP WITH
LOCAL
TIME ZONE.
The sze of the prmary key cannot exceed approxmatey one
database bock.
A composte prmary key cannot have more than 32 coumns.
You cannot desgnate the same coumn or combnaton of coumns as
both a
prmary key and a unque key.
o 3O%'I(5 A'/
A foregn key constrant (aso caed a referenta ntegrty constrant)
desgnates a
coumn as the foregn key and estabshes a reatonshp between that
foregn key and
a speced prmary or unque key, caed the referenced key. A
composte foregn key
desgnates a combnaton of coumns as the foregn key.The tabe or
vew contanng the foregn key s caed the chd ob|ect, and the tabe
or vew contanng the referenced key s caed the parent ob|ect. The
foregn key and the referenced key can be n the same tabe or vew
Exampe:
Dened at ether the tabe eve or the coumn eve:
SOL>CREATE TABLE empoyees( empoyee_d NUMBER(6),
ast_name VARCHAR2(25) NOT NULL, ema
VARCHAR2(25),saary NUMBER(8,2), commsson_pct
NUMBER(2,2), hre_date DATE NOT NULL,... department_d
NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY
(department_d)REFERENCES departments(department_d),
CONSTRAINT emp_ema_uk UNIOUE(ema));
references_clause
Foregn key constrants use the references_clause syntax.
When you specfy a foregn key constrant nne, you need ony the
references_
clause. When you specfy a foregn key constrant out of ne, you must
aso specfy
the FOREIGN KEY keywords and one or more coumns.
ON DELETE Cause The ON DELETE cause ets you determne how
Orace Database
automatcay mantans referenta ntegrty f you remove a referenced
prmary or
unque key vaue. If you omt ths cause, then Orace does not aow
you to deete
referenced key vaues n the parent tabe that have dependent rows n
the chd tabe.
Specfy CASCADE f you want Orace to remove dependent foregn key
vaues.
Page | 49
Specfy SET NULL f you want Orace to convert dependent foregn key
vaues to
NULL. You cannot specfy ths cause for a vrtua coumn, because the
vaues n a
vrtua coumn cannot be updated drecty. Rather, the vaues from
whch the
vrtua coumn are derved must be updated.
8 C*'CA
A check constrant requres a vaue n the database to compy wth a
speced condton.A snge coumn can have mutpe
CHECK constrants that refer to the coumn n t denton. There s no mt to
the number of CHECK constrants that you can dene on a coumn
SLI CREATE TABLE empoyees G... salary 5&4,'%G>,$H CO5ST%)I5T
e!p8salary8!in
C*'CA Gsalary I @H,

Constraint (uidelines
/ou can na!e a constraint, or the Oracle ser"er generates a na!e by using the S/S8Cn
for!at.
Create a constraint at either of the follo2ing ti!es:
)t the sa!e ti!e as the creation of the table
)fter the creation of the table
Define a constraint at the colu!n or table le"el.
9ie2 a constraint in the data dictionary.
9iolating Constraints
When you have constrants n pace on coumns, an error s returned f you try to
voate the constrant rue
Exampe:
You cannot deete a row that contans a prmary key that s used as a foregn key
n another tabe.
SOL>DELETE FROM departments WHERE department_d = 60;
Creatng a TabeUsng a Subquery
Page | 50
Syntax:
CREATE TABLE table |(column, column...)| AS subquery;
Create a tabe and nsert rows by combnng the CREATE TABLE statement
and the AS subquery opton.
Match the number of speced coumns to the number of subquery coumns.
Dene coumns wth coumn names and defaut vaues.
Gudenes
F The tabe s created wth the speced coumn names, and the rows retreved
by the SELECT statement are nserted nto the tabe.
F The coumn denton can contan ony the coumn name and defaut vaue.
F If coumn speccatons are gven, the number of coumns must equa the
number of coumns n the subquery SELECT st.
F If no coumn speccatons are gven, the coumn names of the tabe are the
same as the coumn names n the subquery.
F The coumn data type dentons and the NOT NULL constrant are passed to
the new tabe. Note that ony the expct NOT NULL constrant w be
nherted. The PRIMARY KEY coumn w not pass the NOT NULL feature to the
new coumn. Any other constrant rues are not passed to the new tabe.
However, you can add constrants n the coumn denton.
Exampe:
creates a tabe named DEPT80, whch contans detas of a the empoyees
workng n department 80. Notce that the data for the DEPT80 tabe comes from
the EMPLOYEES tabe.
SOL>CREATE TABLE dept80 AS SELECT empoyee_d, ast_name,
saary*12 ANNSAL, hre_date FROM empoyees WHERE
department_d = 80;
You can verfy the exstence of a database tabe and check the coumn dentons
by usng the DESCRIBE command.
SOL>DESCRIBE dept80
ALTER TABLE Statement
Use the ALTER TABLE statement to:
Add a new coumn
Modfy an exstng coumn denton
Dene a defaut vaue for the new coumn
Drop a coumn
Rename a coumn
Change tabe to read-ony status
Read-Ony Tabes
Wth Orace Database 11!" you can specfy READ ONLY to pace a tabe n
the read-ony mode. When the tabe s n the READ-ONLY mode, you
Page | 51
cannot ssue any DML statements that ahect the tabe or any SELECT ...
FOR UPDATE statements. You can ssue DDL statements as ong as they do
not modfy any data n the tabe. Operatons on ndexes assocated wth
the tabe are aowed when the tabe s n the READ ONLY mode.
Specfy READ/WRITE to return a read-ony tabe to the read/wrte mode.
Note: You can drop a tabe that s n the READ ONLY mode. The DROP
command s executed ony n the data dctonary, so access to the tabe
contents s not requred. The space used by the tabe w not be recamed
unt the tabespace s made read/wrte agan, and then the requred
changes can be made to the bock segment headers, and so on.
Exampe:
SOL>ALTER TABLE empoyees READ ONLY;
-- perform tabe mantenance and then
-- return tabe back to read/wrte mode
SOL>ALTER TABLE empoyees READ WRITE;
Droppng a Tabe
Syntax
DROP TABLE table |PURGE|
Moves a tabe to the recyce bn
Removes the tabe and a ts data entrey f the PURGE cause s speced
Invadates dependent ob|ects and removes ob|ect prveges on the tabe
Exampe:
SOL>DROP TABLE dept80;
Gudenes
F A the data s deeted from the tabe.
F Any vews and synonyms reman, but are nvad.
F Any pendng transactons are commtted.
F Ony the creator of the tabe or a user wth the DROP ANY TABLE prvege can
remove a tabe.
Page | 52
Database Ob|ects
What Is a Vew?
You can present ogca subsets or combnatons of data by creatng vews of
tabes. A vew s a ogca tabe based on a tabe or another vew. A vew contans
no data of ts own, but s ke a wndow through whch data from tabes can be
vewed or changed. The tabes on whch a vew s based are caed base tables.
The vew s stored as a SELECT statement n the data dctonary.
Advantages of Vews
F Vews restrct access to the data because t dspays seected coumns from
the tabe.
F Vews can be used to make smpe queres to retreve the resuts of
compcated queres. For exampe, vews can be used to query nformaton
from mutpe tabes wthout the user knowng how to wrte a |on statement.
F Vews provde data ndependence for ad hoc users and appcaton programs.
One vew can be used to retreve data from severa tabes.
F Vews provde groups of users access to data accordng to ther partcuar
crtera.
Smpe Vews and Compex Vews
There are two casscatons for vews: smpe and compex. The basc dherence
s reated to the DML (INSERT, UPDATE, and DELETE) operatons.
F A smpe vew s one that:
1 Derves data from ony one tabe
1 Contans no functons or groups of data
1 Can perform DML operatons through the vew
F A compex vew s one that:
1 Derves data from many tabes
1 Contans functons or groups of data
1 Does not aways aow DML operatons through the vew
Page | 53
U$"T+D, Creating #ther Schema
#b.ects
Creatng a Vew syntax:
CREATE |OR REPLACE| |FORCE|NOFORCE| VIEW view
|(alias|, alias|...)|
AS subquery
|WITH CHECK OPTION |CONSTRAINT constraint||
|WITH READ ONLY |CONSTRAINT constraint||;
Exampe:
Create the EMPVU80 vew, whch contans detas of the empoyees n
department 80
SOL>CREATE VIEW empvu80 AS SELECT empoyee_d, ast_name, saary FROM
empoyees
WHERE department_d = 80;
Descrbe the structure of the vew by usng the iSOL*Pus DESCRIBE command:
SOL>DESCRIBE empvu80
Gudenes
F The subquery that denes a vew can contan compex SELECT syntax,
ncudng |ons, groups, and subqueres.
F If you do not specfy a constrant name for the vew created wth the WITH
CHECK OPTION, the system assgns a defaut name n the SYS_Cn format.
F You can use the OR REPLACE opton to change the denton of the vew
wthout droppng and re-creatng t, or regrantng the ob|ect prveges
prevousy granted on t.
Create a vew by usng coumn aases n the subquery
SOL>CREATE VIEW savu50 AS SELECT empoyee_d ID_NUMBER, ast_name
NAME,
saary*12 ANN_SALARY FROM empoyees WHERE department_d =
50;
Retrevng Data from a Vew
You can retreve data from a vew as you woud from any tabe. You can dspay
ether the contents of the entre vew or |ust specc rows and coumns.
Modfyng a Vew
Modfy the EMPVU80 vew by usng a CREATE OR REPLACE VIEW cause. Add
an aas for each coumn name:
Coumn aases n the CREATE OR REPLACE VIEW cause are sted n the same
order as the coumns n the subquery.
SOL>CREATE OR REPLACE VIEW empvu80 (d_number, name, sa,
department_d) AS SELECT empoyee_d, rst_name || ' ' || ast_name,
saary, department_d FROM empoyees
WHERE department_d = 8
Page | 54
Create a compex vew that contans group functons to dspay vaues from two
tabes:
SOL>CREATE OR REPLACE VIEW dept_sum_vu (name, mnsa, maxsa, avgsa)
AS SELECT d.department_name, MIN(e.saary),
MAX(e.saary),AVG(e.saary)
FROM empoyees e |OIN departments d ON (e.department_d =
d.department_d) GROUP BY d.department_name;
Rues for Performng DML Operatons on a Vew
You can perform DML operatons on data through a vew f those operatons
foow certan rues.
You can remove a row from a vew uness t contans any of the foowng:
F Group functons
F A GROUP BY cause
F The DISTINCT keyword
F The pseudocoumn ROWNUM keyword
Rues for Performng DML Operatons on a Vew
You cannot modfy data n a vew f t contans:
Group functons
A GROUP BY cause
The DISTINCT keyword
The pseudocoumn ROWNUM keyword
Coumns dened by expressons
Usng the WITH CHECK OPTION Cause
You can ensure that DML operatons performed on the vew stay n the
doman of the vew by usng the WITH CHECK OPTION cause:
SOL>CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM empoyees
WHERE department_d = 20 WITH CHECK OPTION CONSTRAINT
empvu20_ck ;
Any attempt to INSERT a row wth a department_d other than 20, or to
UPDATE the department number for any row n the vew fas because t
voates the WITH CHECK OPTION constrant.
SOL>UPDATE empvu20 SET department_d = 10 WHERE empoyee_d = 201;
Note: No rows are updated because, f the department number were to change
to 10, the vew woud no onger be abe to see that empoyee. Wth the WITH
CHECK OPTION cause, therefore, the vew can see ony the empoyees n
department 20 and does not aow the department number for those empoyees
to be changed through the vew.
Page | 55
Denyng DML Operatons
SOL>CREATE OR REPLACE VIEW empvu10 (empoyee_number, empoyee_name,
|ob_tte)
AS SELECT empoyee_d, ast_name, |ob_d FROM empoyees WHERE
department_d = 10 WITH READ ONLY ;
Any attempt to remove a row from a vew wth a read-ony constrant resuts n
an error:
DELETE FROM empvu10
WHERE empoyee_number = 200;
Smary, any attempt to nsert a row or modfy a row usng the vew wth a read-
ony constrant resuts n the same error.
Removng a Vew
You use the DROP VIEW statement to remove a vew. The statement removes the
vew denton from the database. However, droppng vews has no ehect on the
tabes on whch the vew was based. On the other hand, vews or other
appcatons based on the deeted vews become nvad. Ony the creator or a
user wth the DROP ANY VIEW prvege can remove a vew.
Syntax:
DROP VIEW view;
SOL>DROP VIEW empvu80;
Sequences
A sequence s a database ob|ect that creates nteger vaues. You can create
sequences and then use them to generate numbers.
A sequence s a user-created database ob|ect that can be shared by mutpe
users to generate ntegers. You can dene a sequence to generate unque vaues
or to recyce and use the same numbers agan.A typca usage for sequences s
to create a prmary key vaue, whch must be unque for each row. A sequence s
generated and ncremented (or decremented) by an nterna Orace routne. Ths
can be a tme-savng ob|ect because t can reduce the amount of appcaton
code needed to wrte a sequence-generatng routne.
Sequence numbers are stored and generated ndependent of tabes. Therefore,
the same sequence can be used for mutpe tabes.
CREATE SEOUENCE Statement:
Syntax
CREATE SEOUENCE sequence
|INCREMENT BY n|
|START WITH n|
|{MAXVALUE n | NOMAXVALUE}|
|{MINVALUE n | NOMINVALUE}|
|{CYCLE | NOCYCLE}|
|{CACHE n | NOCACHE}|;
Exampe:
Page | 56
SOL>CREATE SEOUENCE dept_deptd_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
NEXTVAL and CURRVAL Pseudocoumns
After you create your sequence, t generates sequenta numbers for use n your
tabes. Reference the sequence vaues by usng the NEXTVAL and CURRVAL
pseudocoumns.
The NEXTVAL pseudocoumn s used to extract successve sequence numbers
from a speced sequence. You must quafy NEXTVAL wth the sequence name.
When you reference sequence.NEXTVAL, a new sequence number s generated
and the current sequence number s paced n CURRVAL.
The CURRVAL pseudocoumn s used to refer to a sequence number that the
current user has |ust generated. However, NEXTVAL must be used to generate a
sequence number n the current users sesson before CURRVAL can be
referenced. You must quafy CURRVAL wth the sequence name. When you
reference sequence.CURRVAL, the ast vaue returned to that users process s
dspayed.
Usng a Sequence
Insert a new department named "Support" n ocaton ID 2500:
SOL>INSERT INTO departments(department_d, department_name, ocaton_d)
VALUES (dept_deptd_seq.NEXTVAL, 'Support', 2500);
Vew the current vaue for the DEPT_DEPTID_SEO sequence
SOL>SELECT dept_deptd_seq.CURRVAL FROM dua;
Cachng Sequence Vaues
You can cache sequences n memory to provde faster access to those sequence
vaues. The cache s popuated the rst tme you refer to the sequence. Each
request for the next sequence vaue s retreved from the cached sequence. After
the ast sequence vaue s used, the next request for the sequence pus another
cache of sequences nto memory.
Gaps n the Sequence
Athough sequence generators ssue sequenta numbers wthout gaps, ths
acton occurs ndependent of a commt or roback. Therefore, f you ro back a
statement contanng a sequence, the number s ost.
Another event that can cause gaps n the sequence s a system crash. If the
sequence caches vaues n memory, then those vaues are ost f the system
crashes.
Because sequences are not ted drecty to tabes, the same sequence can be
used for mutpe tabes. However, f you do so, each tabe can contan gaps n
the sequenta numbers.
Indexes
Page | 57
Indexes are database ob|ects that you can create to mprove the performance of
some queres. Indexes can aso be created automatcay by the server when you
create a prmary key or a unque constrant.
An ndex:
Is a schema ob|ect
Can be used by the Orace server to speed up the retreva of rows by usng a
ponter
Can reduce dsk nput/output (I/O) by usng a rapd path access method to
ocate data qucky
Is ndependent of the tabe that t ndexes
Is used and mantaned automatcay by the Orace server
How Are Indexes Created?
You can create two types of ndexes.
Unque ndex: The Orace server automatcay creates ths ndex when you
dene a coumn n a tabe to have a PRIMARY KEY or a UNIOUE constrant. The
name of the ndex s the name that s gven to the constrant.
Nonunque ndex: Ths s an ndex that a user can create. For exampe, you can
create the FOREIGN KEY coumn ndex for a |on n a query to mprove the speed
of retreva.
Note: You can manuay create a unque ndex, but t s recommended that you
create a unque constrant, whch mpcty creates a unque ndex.
Creatng an Index
Create an ndex on one or more coumns:
CREATE |UNIOUE||BITMAP|INDEX index
ON table (column|, column|...);
Improve the speed of query access to the LAST_NAME coumn n the EMPLOYEES
tabe:
CREATE INDEX emp_ast_name_dx
ON empoyees(ast_name);
When to Create an Index
Therefore, you shoud create ndexes ony f:
F The coumn contans a wde range of vaues
F The coumn contans a arge number of nu vaues
F One or more coumns are frequenty used together n a WHERE cause or |on
condton
F The tabe s arge and most queres are expected to retreve ess than 2% to
4% of the rows
Remember that f you want to enforce unqueness, you shoud dene a unque
constrant n the tabe denton. A unque ndex s then created automatcay.
Removng an Index
Remove an ndex from the data dctonary by usng the DROP INDEX command:
Page | 58
DROP INDEX index;
To drop an ndex, you must be the owner of the ndex or have the DROP ANY
INDEX prvege
Synonyms
Synonyms are database ob|ects that enabe you to ca a tabe by another name.
You can create synonyms to gve an aternatve name to a tabe.
To refer to a tabe that s owned by another user, you need to prex the tabe
name wth the name of the user who created t, foowed by a perod. Creatng a
synonym emnates the need to quafy the ob|ect name wth the schema and
provdes you wth an aternatve name for a tabe, vew, sequence, procedure, or
other ob|ects. Ths method can be especay usefu wth engthy ob|ect names,
such as vews.
Syntax:
CREATE |PUBLIC| SYNONYM synonym
FOR ob#ect;
Exampe:
Create a shortened name for the DEPT_SUM_VU vew
SOL>CREATE SYNONYM d_sum FOR dept_sum_vu;
Drop a synonym:
SOL>DROP SYNONYM d_sum;
Creatng a Pubc Synonym
The database admnstrator can create a pubc synonym that s accessbe to a
users. The foowng exampe creates a pubc synonym named DEPT for Aces
DEPARTMENTS tabe:
SOL>CREATE PUBLIC SYNONYM dept for DEPARTMENTS
Page | 59
In a mutpe-user envronment, you want to mantan securty of the database
access and use. Wth Orace server database securty, you can do the foowng:
F Contro database access.
F Gve access to specc ob|ects n the database.
F Conrm gven and receved prveges wth the Orace data dctonary.
Database securty can be cassed nto two categores: system securty and data
securty. System securty covers access and use of the database at the system
eve, such as the username and password, the dsk space aocated to users, and
the system operatons that users can perform. Database securty covers access
and use of the database ob|ects and the actons that those users can perform on
the ob|ects.
Prveges
A prvege s the rght to execute partcuar SOL statements. The database
admnstrator (DBA) s a hgh-eve user wth the abty to create users and grant
users access to the database and ts ob|ects. Users requre system privile!es to
gan access to the database and ob#ect privile!es to manpuate the content of
the ob|ects n the database. Users can aso be gven the prvege to grant
addtona prveges to other users or to roles, whch are named groups of
reated prveges.
Schemas
A schema s a coecton of ob|ects such as tabes, vews, and sequences. The
schema s owned by a database user and has the same name as that user.
A system prvege s the rght to perform a partcuar acton, or to perform an
acton on any schema ob|ects of a partcuar type. An ob|ect prvege provdes
the user the abty to perform a partcuar acton on a specc schema ob|ect.
System Prveges
More than 100 dstnct system prveges are avaabe for users and roes.
Typcay, system prveges are provded by the DBA.
The database admnstrator has hgh-eve system prveges for tasks such as:
Creatng new users
Removng users
Removng tabes
Backng up tabes
Typca DBA Prveges
System Prvege Operatons Authorzed
CREATE USER Grantee can create other Orace users.
DROP USER Grantee can drop another user.
DROP ANY TABLE Grantee can drop a tabe n any schema.
BACKUP ANY TABLE Grantee can back up any tabe n any schema
wth the export utty.
SELECT ANY TABLE Grantee can query tabes, vews, or materazed
vews n any schema.
Page | 60
Unit+D; Controlling User
%ccess
CREATE ANY TABLE Grantee can create tabes n any schema.
Creatng Users
The DBA creates the user by executng the CREATE USER statement. The user
does not have any prveges at ths pont. The DBA can then grant prveges to
that user. These prveges determne what the user can do at the database eve.
Typca User Prveges
After the DBA creates a user, the DBA can assgn prveges to that user.
System Prvege Operatons Authorzed
CREATE SESSION Connect to the database.
CREATE TABLE Create tabes n the users schema.
CREATE SEOUENCE Create a sequence n the users schema.
CREATE VIEW Create a vew n the users schema.
CREATE PROCEDURE Create a stored procedure, functon, or package n the
users schema.
Exampe:
SOL>GRANT create sesson, create tabe, create sequence, create vew TO
demo;
What Is a Roe?
A roe s a named group of reated prveges that can be granted to the user. Ths
method makes t easer to revoke and mantan prveges.
A user can have access to severa roes, and severa users can be assgned the
same roe. Roes are typcay created for a database appcaton.
Creatng and Assgnng a Roe
Frst, the DBA must create the roe. Then the DBA can assgn prveges to the
roe and assgn the roe to users.
Syntax
CREATE ROLE role;
After the roe s created, the DBA can use the GRANT statement to assgn the roe
to users as we as assgn prveges to the roe.
Changng Your Password
The DBA creates an account and ntazes a password for every user. You can
change your password by usng the ALTER USER statement
Syntax
ALTER USER user IDENTIFIED BY password;
In the syntax:
Athough ths statement can be used to change your password, there are many
other optons. You must have the ALTER USER prvege to change any other
opton.
Changng Your Password
The DBA creates your user account and ntazes your password.
You can change your password by usng the ALTER USER statement.

SOL>ALTER USER demo IDENTIFIED BY empoy;


Page | 61

The DBA creates an account and ntazes a password for every user. You can
change your password by usng the ALTER USER statement.
Ob|ect Prveges
An ob#ect privile!e s a prvege or rght to perform a partcuar acton on a
specc tabe, vew, sequence, or procedure. Each ob|ect has a partcuar set
of grantabe prveges. The tabe n the sde sts the prveges for varous
ob|ects. Note that the ony prveges that appy to a sequence are SELECT
and ALTER. UPDATE, REFERENCES, and INSERT can be restrcted by specfyng
a subset of updatabe coumns.
A SELECT prvege can be restrcted by creatng a vew wth a subset of
coumns and grantng the SELECT prvege ony on the vew. A prvege
granted on a synonym s converted to a prvege on the base tabe
referenced by the synonym.
Note: Wth the REFERENCES prvege, you can ensure that other users can
create FOREIGN KEY constrants that reference your tabe.
Grantng Ob|ect Prveges
Exampe:
Grant query prveges on the EMPLOYEES tabe
SOL>GRANT seect ON empoyees TO demo;
Grant prveges to update specc coumns to users and roes:
SOL>GRANT update (department_name, ocaton_d)ON departmentsTO
demo, Manager;
Revokng Ob|ect Prveges
You use the REVOKE statement to revoke prveges granted to other users.
Prveges granted to others through the WITH GRANT OPTION cause are aso
revoked.
Syntax:
REVOKE {prvege |, prvege...||ALL}
ON ob|ect
FROM {user|, user...||roe|PUBLIC}
|CASCADE CONSTRAINTS|;
Note: If a user s granted a prvege wth the WITH GRANT OPTION cause, that
user can aso grant the prvege wth the WITH GRANT OPTION cause, so that a
ong chan of grantees s possbe, but no crcuar grants (grantng to a grant
ancestor) are permtted. If the owner revokes a prvege from a user who
granted the prvege to other users, then the revokng cascades to a the
prveges granted.
For exampe, f user A grants a SELECT prvege on a tabe to user B ncudng
the WITH GRANT OPTION cause, user B can grant to user C the SELECT prvege
wth the WITH GRANT OPTION cause as we, and user C can then grant to user D
the SELECT prvege. If user A revokes prveges from user B, then the prveges
granted to users C and D are aso revoked.
Page | 62
Page | 63
Unit DE + Managing
Schema #b.ects
Managng schema ob|ects contans nformaton about creatng ndexes and
constrants, and aterng exstng ob|ects. You aso earn about externa tabes,
and the provson to name the ndex at the tme of creatng a prmary key
constrant.
ALTER TABLE Statement
Use the ALTER TABLE statement to add, modfy, or drop coumns:
Syntax:
Addng a Coumn
You can add or modfy coumns.
You cannot specfy where the coumn s to appear. The new coumn becomes the
ast coumn.
1.ALTER TABLE table
ADD (column datatype |DEFAULT expr|
|, column datatype|...);
Modfyng a Coumn
You can change a coumns data type, sze, and defaut vaue.
A change to the defaut vaue ahects ony subsequent nsertons to the tabe.
2.ALTER TABLE table
MODIFY (column datatype |DEFAULT expr|
|, column datatype|...);
You can drop a coumn from a tabe by usng the ALTER TABLE statement wth the
DROP COLUMN cause.
3.ALTER TABLE table
DROP (column);
Gudenes For DROP COLUMNS
F The coumn may or may not contan data.
F Usng the ALTER TABLE DROP COLUMN statement, ony one coumn can be
dropped at a tme.
F The tabe must have at east one coumn remanng n t after t s atered.
F After a coumn s dropped, t cannot be recovered.
F A coumn cannot be dropped f t s part of a constrant or part of an ndex key
uness the cascade opton s added.
F Droppng a coumn can take a whe f the coumn has a arge number of
vaues. In ths case, t may be better to set t to be unused and drop t when
there are fewer users on the system to avod extended ocks.
F Note: Certan coumns can never be dropped, such as coumns that form part
of the parttonng key of a parttoned tabe or coumns that form part of the
prmary key of an ndex-organzed tabe.
F SET UNUSED Opton
F The SET UNUSED opton marks one or more coumns as unused so that they
can be dropped when the demand on system resources s ower. Specfyng
ths cause does not actuay remove the target coumns from each row n the
tabe (that s, t does not restore the dsk space used by these coumns).
Therefore, the response tme s faster than f you executed the DROP cause.
Unused coumns are treated as f they were dropped, even though ther
coumn data remans n the tabes rows. After a coumn has been marked as
Page | 64
unused, you have no access to that coumn. A SELECT * query w not
retreve data from unused coumns. In addton, the names and types of
coumns marked unused w not be dspayed durng a DESCRIBE statement,
and you can add to the tabe a new coumn wth the same name as an
unused coumn. The SET UNUSED nformaton s stored n the
USER_UNUSED_COL_TABS dctonary vew.
Syntax:
You use the SET UNUSED opton to mark one or more coumns as unused.
ALTER TABLE <table_name$
SET UNUSED(<column_name$);
ALTER TABLE %table_name$
SET UNUSED COLUMN %column_name$;
You use the DROP UNUSED COLUMNS opton to remove the coumns that are
marked as unused.
ALTER TABLE <table_name$
DROP UNUSED COLUMNS;
Addng a Constrant Syntax
Add or drop a constrant, but not modfy ts structure
Enabe or dsabe constrants
Add a NOT NULL constrant by usng the MODIFY cause
Syntax:
ALTER TABLE <table_name$
ADD |CONSTRAINT <constraint_name$|
type (<column_name$);
Gudenes
F You can add, drop, enabe, or dsabe a constrant, but you cannot modfy ts
structure.
F You can add a NOT NULL constrant to an exstng coumn by usng the
MODIFY cause of the ALTER TABLE statement.
Exampes:
SOL> ALTER TABLE emp2 modfy empoyee_d Prmary Key;
SOL> ALTER TABLE emp2 ADD CONSTRAINT emp_mgr_fk FOREIGN
KEY(manager_d)
REFERENCES emp2(empoyee_d);
ON DELETE CASCADE
The ON DELETE CASCADE acton aows parent key data that s referenced from
the chd tabe to be deeted, but not updated. When data n the parent key s
deeted, a rows n the chd tabe that depend on the deeted parent key vaues
are aso deeted. To specfy ths referenta acton, ncude the ON DELETE
CASCADE opton n the denton of the FOREIGN KEY constrant.
Exampe:
Page | 65
SOL> ALTER TABLE Emp2 ADD CONSTRAINT emp_dt_fk
FOREIGN KEY (Department_d)
REFERENCES departments(department_d) ON DELETE CASCADE;
Deferrng Constrants
You can defer checkng constrants for vadty unt the end of the transacton. A
constrant s deferred f the system checks that t s satsed ony on commt. If a
deferred constrant s voated, then commt causes the transacton to ro back. If
a constrant s mmedate (not deferred), then t s checked at the end of each
statement. If t s voated, the statement s roed back mmedatey. If a
constrant causes an acton (for exampe, DELETE CASCADE), that acton s
aways taken as part of the statement that caused t, whether the constrant s
deferred or mmedate. Use the SET CONSTRAINTS statement to specfy, for a
partcuar transacton, whether a deferrabe constrant s checked foowng each
DML statement or when the transacton s commtted. To create deferrabe
constrants, you must create a nonunque ndex for that constrant.
You can dene constrants as ether deferrabe or not deferrabe, and ether
ntay deferred or ntay mmedate. These attrbutes can be dherent for each
constrant.
Deferrng constrant on creaton
Exampes:
SOL>ALTER TABLE dept2
ADD CONSTRAINT dept2_d_pk
PRIMARY KEY (department_d)
DEFERRABLE INITIALLY DEFERRED
Changng a specc constrant attrbute
SET CONSTRAINTS dept2_d_pk IMMEDIATE
Changng a constrants for a sesson
ALTER SESSION
SET CONSTRAINTS= IMMEDIATE
Dherence Between INITIALLY DEFERRED and INITIALLY IMMEDIATE
INITIALLY DEFERRED Wats to check the constrant
unt the transacton ends
INITIALLY IMMEDIATE Checks the constrant at the
end of the statement
executon
Droppng a Constrant
To drop a constrant, you can dentfy the constrant name from the
USER_CONSTRAINTS and USER_CONS_COLUMNS data dctonary vews. Then use
the ALTER TABLE statement wth the DROP cause. The CASCADE opton of the
DROP cause causes any dependent constrants aso to be dropped.
Page | 66
Syntax
ALTER TABLE table
DROP PRIMARY KEY | UNIOUE (column) |
CONSTRAINT constraint |CASCADE|;
Dsabng Constrants
You can dsabe a constrant wthout droppng t or re-creatng t by usng the
ALTER TABLE statement wth the DISABLE cause.
Syntax
ALTER TABLE table
DISABLE CONSTRAINT constraint |CASCADE|;
Gudenes
F You can use the DISABLE cause n both the CREATE TABLE statement and the
ALTER TABLE statement.
F The CASCADE cause dsabes dependent ntegrty constrants.
F Dsabng a unque or prmary key constrant removes the unque ndex.
Enabng Constrants
You can enabe a constrant wthout droppng t or re-creatng t by usng the
ALTER TABLE statement wth the ENABLE cause.
Actvate an ntegrty constrant currenty dsabed n the tabe denton by usng
the ENABLE cause.
Syntax
ALTER TABLE tabe
ENABLE CONSTRAINT constrant;
CREATE INDEX wth the CREATE TABLE Statement
CREATE INDEX cause s used wth the CREATE TABLE statement to create a
prmary key ndex expcty. You can name your ndexes at the tme of prmary
key creaton to be dherent from the name of the PRIMARY KEY constrant.
SOL>CREATE TABLE NEW_EMP(empoyee_d NUMBER(6) PRIMARY KEY USING
INDEX
(CREATE INDEX emp_d_dx ON NEW_EMP(empoyee_d)),rst_name
VARCHAR2(20),
ast_name VARCHAR2(25));
You can query the USER_INDEXES data dctonary vew for nformaton about your
ndexes.
FLASHBACK TABLE Statement
Orace Fashback Tabe enabes you to recover tabes to a speced pont n tme
wth a snge statement. You can restore tabe data aong wth assocated
ndexes, and constrants, whe the database s onne, undong changes to ony
the speced tabes.
The Fashback Tabe feature s smar to a sef-servce repar too. For exampe, f
a user accdentay deeted mportant rows from a tabe and then wanted to
Page | 67
recover the deeted rows, you can use the FLASHBACK TABLE statement to
restore the tabe to the tme before the deeton and see the mssng rows n the
tabe.
When usng the FLASHBACK TABLE statement, you can revert the tabe and ts
contents to a certan tme or to an SCN.
Note: The system change number (SCN) s an nteger vaue assocated wth each
change to the database. It s a unque ncrementa number n the database.
Every tme you commt a transacton, a new SCN s recorded.
Sef-Servce Repar Facty
Orace Database provdes a SOL data denton anguage (DDL) command,
FLASHBACK TABLE, to restore the state of a tabe to an earer pont n tme n
case t s nadvertenty deeted or moded. The FLASHBACK TABLE command s
a sef-servce repar too to restore data n a tabe aong wth assocated
attrbutes such as ndexes or vews. Ths s done whe the database s onne by
rong back ony the subsequent changes to the gven tabe. Compared to
tradtona recovery mechansms, ths feature ohers sgncant benets such as
ease of use, avaabty, and faster restoraton. It aso takes the burden oh the
DBA to nd and restore appcaton-specc propertes. The ashback tabe
feature does not address physca corrupton caused because of a bad dsk.
Syntax:
FLASHBACK TABLE|schema.|tabe|,
| schema.|tabe |...
TO { TIMESTAMP | SCN } expr
| { ENABLE | DISABLE } TRIGGERS |;
DROP TABLE emp2;
The exampe restores the EMP2 tabe to a state before a DROP statement
SELECT orgna_name, operaton, droptme FROM recycebn;
FLASHBACK TABLE emp2 TO BEFORE DROP;
When you drop a user, any ob|ects beongng to that user are not paced n the
recyce bn and any ob|ects n the recyce bn are purged.
You can purge the recyce bn wth the foowng statement:
PURGE RECYCLEBIN;
Externa Tabes
An externa tabe s a read-ony tabe whose metadata s stored n the database
but whose data s stored outsde the database. Ths externa tabe denton can
be thought of as a vew that s used for runnng any SOL query aganst externa
data wthout requrng that the externa data rst be oaded nto the database.
The externa tabe data can be quered and |oned drecty and n parae wthout
requrng that the externa data rst be oaded n the database. You can use SOL,
PL/SOL and |ava to query the data n an externa tabe.
The man dherence between externa tabes and reguar tabes s that externay
organzed tabes are read-ony. No data manpuaton anguage (DML) operatons
are possbe, and no ndexes can be created on them. However, you can create
Page | 68
an externa tabe, and thus unoad data, by usng the CREATE TABLE AS SELECT
command.
Exampe:
Create a DIRECTORY ob|ect that corresponds to the drectory on the e system
where the externa data source resdes.
CREATE OR REPLACE DIRECTORY emp_dr
AS '/./emp_dr';
GRANT READ ON DIRECTORY emp_dr TO hr;
An externa tabe does not descrbe any data that s stored n the database. It
does not descrbe how data s stored n the externa source. Instead, t descrbes
how the externa tabe ayer must present the data to the server. It s the
responsbty of the access drver and the externa tabe ayer to do the
necessary transformatons requred on the data n the data e so that t matches
the externa tabe denton.
When the database server accesses data n an externa source, t cas the
approprate access drver to get the data from an externa source n a form that
the database server expects.
Page | 69
Data Dctonary
User tabes are tabes created by the user and contan busness data, such as
EMPLOYEES. There s another coecton of tabes and vews n the Orace
database known as the data dctonary. Ths coecton s created and mantaned
by the Orace server and contans nformaton about the database. The data
dictionary s structured n tabes and vews, |ust ke other database data. Not
ony s the data dctonary centra to every Orace database, but t s an
mportant too for a users, from end users to appcaton desgners and
database admnstrators.
You use SOL statements to access the data dctonary. Because the data
dctonary s read-ony, you can ssue ony queres aganst ts tabes and vews.
You can query the dctonary vews that are based on the dctonary tabes to nd
nformaton such as:
F Dentons of a schema ob|ects n the database (tabes, vews, ndexes,
synonyms, sequences, procedures, functons, packages, trggers, and so on)
F Defaut vaues for coumns
F Integrty constrant nformaton
F Names of Orace users
F Prveges and roes that each user has been granted
F Other genera database nformaton
Data Dctonary Structure
F Underyng base tabes store nformaton about the assocated database. Ony
the Orace server shoud wrte to and read from these tabes. You rarey
access them drecty.
F There are severa vews that summarze and dspay the nformaton stored n
the base tabes of the data dctonary. These vews decode the base tabe
data nto usefu nformaton (such as user or tabe names) usng |ons and
WHERE causes to smpfy the nformaton. Most users are gven access to the
vews rather than the base tabes.
F The Orace user SYS owns a base tabes and user-accessbe vews of the
data dctonary. No Orace user shoud ever ater (UPDATE, DELETE, or INSERT)
any rows or schema ob|ects contaned n the SYS schema because such
actvty can compromse data ntegrty.
How to Use the Dctonary Vews
Start wth DICTIONARY. It contans the names and descrptons of the dctonary
tabes and vews.
SOL>DESCRIBE DICTIONARY
SOL>SELECT *FROM dctonary WHERE tabe_name = 'USER_OB|ECTS';
USER_OB|ECTS and ALL_OB|ECTS Vews
Exampe:
Page | 70
UnitDE + Managing #b.ects 5ith Data
Dictionary 1ie5s
SOL>SELECT ob|ect_name, ob|ect_type, created, status FROM user_ob|ects
ORDER BY ob|ect_type;
The CAT Vew
For a smped query and output, you can query the CAT vew. Ths vew
contans ony two coumns: TABLE_NAME and TABLE_TYPE. It provdes the names
of a your INDEX, TABLE, CLUSTER, VIEW, SYNONYM, SEOUENCE, or UNDEFINED
ob|ects.
Note: CAT s a synonym for USER_CATALOG-a vew that sts tabes, vews,
synonyms and sequences owned by the user.
Tabe Informaton
You can use the USER_TABLES vew to obtan the names of a your tabes. The
USER_TABLES vew contans nformaton about your tabes. In addton to
provdng the tabe name, t contans detaed nformaton about the storage.
The TABS vew s a synonym of the USER_TABLES vew. You can query t to see a
stng of tabes that you own:
SOL>SELECT tabe_name FROM tabs;
Coumn Informaton
You can query the USER_TAB_COLUMNS vew to nd detaed nformaton about
the coumns n your tabes. Athough the USER_TABLES vew provdes nformaton
about your tabe names and storage, detaed coumn nformaton s found n the
USER_TAB_COLUMNS vew.
Ths vew contans nformaton such as:
F Coumn names
F Coumn data types
F Length of data types
F Precson and scae for NUMBER coumns
F Whether nus are aowed (Is there a NOT NULL constrant on the coumn?)
F Defaut vaue
Exampe:
SOL> SELECT coumn_name, data_type, data_ength, data_precson,
data_scae, nuabe
FROM user_tab_coumns WHERE tabe_name = 'EMPLOYEES';
Constrant Informaton
You can nd out the names of your constrants, the type of constrant, the
tabe name to whch the constrant appes, the condton for check
constrants, foregn key constrant nformaton, deeton rue for foregn key
constrants, the status, and many other types of nformaton about your
constrants.
USER_CONSTRAINTS descrbes the constrant dentons on your tabes.
USER_CONS_COLUMNS descrbes coumns that are owned by you and that are
speced n constrants
Exampe:
Page | 71
SOL>SELECT constrant_name, constrant_type, search_condton,
r_constrant_name, deete_rue, status FROM
user_constrants WHERE tabe_name = 'EMPLOYEES';
Addng Comments to a Tabe
You can add comments to a tabe or coumn by usng the COMMENT
statement
Exampes:
SOL>COMMENT ON TABLE empoyees IS 'Empoyee Informaton';
SOL>COMMENT ON COLUMN empoyees.rst_name IS 'Frst name of the
empoyee';
Comments can be vewed through the data dctonary vews:
ALL_COL_COMMENTS
USER_COL_COMMENTS
ALL_TAB_COMMENTS
USER_TAB_COMMENTS
Oueryng the dctonary vews for vew nformaton
USER_VIEWS
Oueryng the dctonary vews for sequence nformaton
USER_SEOUENCES
Oueryng the dctonary vews for synonym nformaton
USER_SYNONYMS
Oueryng the dctonary vews for ndex nformaton
USER_INDEXES
Page | 72
Usng Subqueres to Manpuate Data
Subqueres can be used to retreve data from a tabe that you can use as nput to
an INSERT nto a dherent tabe. In ths way, you can easy copy arge voumes of
data from one tabe to another wth one snge SELECT statement. Smary, you
can use subqueres to do mass updates and deetes by usng them n the WHERE
cause of the UPDATE and DELETE statements. You can aso use subqueres n the
FROM cause of a SELECT statement. Ths s caed an nne vew.
SOL>SELECT department_name, cty FROM departments
NATURAL |OIN (SELECT .ocaton_d, .cty, .country_d
FROM oc |OIN countres c ON(.country_d = c.country_d)
|OIN regons USING(regon_d) WHERE regon_name = 'Europe');
Insertng Usng a Subquery as a Target
You can use a subquery n pace of the tabe name n the INTO cause of the
INSERT statement. The SELECT st of ths subquery must have the same number
of coumns as the coumn st of the VALUES cause. Any rues on the coumns of
the base tabe must be foowed n order for the INSERT statement to work
successfuy
SOL>INSERT INTO (SELECT .ocaton_d, .cty, .country_d
FROM oc
|OIN countres c
ON(.country_d = c.country_d)
|OIN regons USING(regon_d)
WHERE regon_name = 'Europe')
VALUES (3300, 'Cardh', 'UK');
Verfy the resuts.
SOL>SELECT ocaton_d, cty, country_d FROM oc
Overvew of Muttabe INSERT Statements
In a muttabe INSERT statement, you nsert computed rows derved from the
rows returned from the evauaton of a subquery nto one or more tabes.
Muttabe INSERT statements are usefu n a data warehouse scenaro. You need
to oad your data warehouse reguary so that t can serve ts purpose of
factatng busness anayss. To do ths, data from one or more operatona
systems must be extracted and coped nto the warehouse. The process of
extractng data from the source system and brngng t nto the data warehouse
s commony caed ETL, whch stands for extracton, transformaton, and oadng.
Durng extracton, the desred data must be dented and extracted from many
dherent sources, such as database systems and appcatons. After extracton,
the data must be physcay transported to the target system or an ntermedate
system for further processng. Dependng on the chosen means of
transportaton, some transformatons can be done durng ths process. For
exampe, a SOL statement that drecty accesses a remote target through a
gateway can concatenate two coumns as part of the SELECT statement.
Page | 73
Unit+DF Manipulating Large
Data Sets
After data s oaded nto the Orace database, data transformatons can be
executed usng SOL operatons. A muttabe INSERT statement s one of the
technques for mpementng SOL data transformatons.
Types of Muttabe INSERT Statements
The dherent types of muttabe INSERT statements are:
F Uncondtona INSERT: For each row returned by the subquery, a row s nserted
nto each of the target tabes.
F Condtona INSERT ALL: For each row returned by the subquery, a row s
nserted nto each target tabe f the speced condton s met.
F Pvotng INSERT: Ths s a speca case of the uncondtona INSERT ALL.
F Condtona INSERT FIRST: For each row returned by the subquery, a row s
nserted nto the very rst target tabe n whch the condton s met.
Exampe:
Seect the EMPLOYEE_ID, HIRE_DATE, SALARY, and MANAGER_ID vaues from
the EMPLOYEES tabe for those empoyees whose EMPLOYEE_ID s greater
than 200.
Insert these vaues nto the SAL_HISTORY and MGR_HISTORY tabes by usng a
muttabe INSERT.
SOL>INSERT ALL INTO sa_hstory VALUES(EMPID,HIREDATE,SAL)
INTO mgr_hstory VALUES(EMPID,MGR,SAL) SELECT empoyee_d EMPID,
hre_date HIREDATE, saary SAL, manager_d MGR FROM empoyees
WHERE empoyee_d > 200;
Ths INSERT statement s referred to as an uncondtona INSERT because no
further restrcton s apped to the rows that are retreved by the SELECT
statement. A the rows retreved by the SELECT statement are nserted nto the
two tabes: SAL_HISTORY and MGR_HISTORY. The VALUES cause n the INSERT
statements speces the coumns from the SELECT statement that must be
nserted nto each of the tabes. Each row returned by the SELECT statement
resuts n two nsertons: one for the SAL_HISTORY tabe and one for the
MGR_HISTORY tabe.
Condtona INSERT ALL
Exampe
For a empoyees n the empoyees tabes, f the empoyee was hred before
1995, then nsert that empoyee record nto the empoyee hstory. If the
empoyee earns a saes commsson, then nsert the record nformaton nto the
EMP_SALES tabe.
SOL>INSERT ALL WHEN HIREDATE < '01-|AN-95' THEN INTO emp_hstory
vALUES(EMPID,HIREDATE,SAL) WHEN COMM IS NOT NULL THEN
INTO emp_saes VALUES(EMPID,COMM,SAL) SELECT
empoyee_d EMPID, hre_date HIREDATE,
saary SAL, commsson_pct COMM FROM empoyees
Page | 74
Condtona INSERT FIRST:
Exampe
For a empoyees n the EMPLOYEES tabe, nsert the empoyee nformaton nto
the rst target tabe that meets the condton. In the exampe, f an empoyee
has a saary of 2,000, the record s nserted nto the SAL_LOW tabe ony.
SOL>INSERT FIRST WHEN saary < 5000 THEN
INTO sa_ow VALUES (empoyee_d, ast_name, saary)
WHEN saary between 5000 and 10000 THEN
INTO sa_md VALUES (empoyee_d, ast_name, saary)
ELSE
INTO sa_hgh VALUES (empoyee_d, ast_name, saary)
SELECT empoyee_d, ast_name, saary
FROM empoyees
The SELECT statement retreves detas such as empoyee ID, ast name, and
saary for every empoyee n the EMPLOYEES tabe. For each empoyee record, t
s nserted nto the very rst target tabe that meets the condton.
Ths INSERT statement s referred to as a condtona INSERT FIRST. The WHEN
saary < 5000 condton s evauated rst. If ths rst WHEN cause evauates to
true, the Orace server executes the correspondng INTO cause and nserts the
record nto the SAL_LOW tabe. It skps subsequent WHEN causes for ths row.
If the row that does not satsfy the rst WHEN condton (WHEN saary < 5000),
the next condton (WHEN saary between 5000 and 10000) s evauated. If ths
condton evauates to true, the record s nserted nto the SAL_MID tabe, and the
ast condton s skpped.
If nether the rst condton (WHEN saary < 5000) nor the second condton
(WHEN saary between 5000 and 10000) s evauated to true, the Orace server
executes the correspondng INTO cause for the ELSE cause.
Pvotng INSERT
Pvotng s an operaton n whch you must bud a transformaton such that each
record from any nput stream, such as a nonreatona database tabe, must be
converted nto mutpe records for a more reatona database tabe
envronment.
Suppose you receve a set of saes records from a nonreatona database tabe:
SALES_SOURCE_DATA, n the foowng format:
EMPLOYEE_ID, WEEK_ID, SALES_MON, SALES_TUE, SALES_WED,
SALES_THUR, SALES_FRI
You want to store these records n the SALES_INFO tabe n a more typca
reatona format:
EMPLOYEE_ID, WEEK, SALES
To sove ths probem, you must bud a transformaton such that each record
from the orgna nonreatona database tabe, SALES_SOURCE_DATA, s
converted nto ve records for the data warehouses SALES_INFO tabe. Ths
operaton s commony referred to as pivotin!.
Exampes:
SOL>INSERT ALL
INTO saes_nfo VALUES (empoyee_d,week_d,saes_MON)
INTO saes_nfo VALUES (empoyee_d,week_d,saes_TUE)
INTO saes_nfo VALUES (empoyee_d,week_d,saes_WED)
INTO saes_nfo VALUES (empoyee_d,week_d,saes_THUR)
Page | 75
INTO saes_nfo VALUES (empoyee_d,week_d, saes_FRI)
SELECT EMPLOYEE_ID, week_d, saes_MON, saes_TUE,
saes_WED, saes_THUR,saes_FRI
FROM saes_source_data;
MERGE Statement
You can condtonay nsert, update, or deete rows n a tabe by usng the
MERGE statement
Performs an UPDATE f the row exsts, and an INSERT f t s a new row:
Avods separate updates
Increases performance and ease of use
Is usefu n data warehousng appcatons
Syntax:
MERGE INTO table_name table_alias
USING (table|view|sub_query) alias
ON (#oin condition)
WHEN MATCHED THEN
UPDATE SET
col1 & col1_val"
col2 & col2_val
WHEN NOT MATCHED THEN
INSERT (column_list)
VALUES (column_values);
Page | 76
Mergng Rows: Exampe
The COPY_EMP3 tabe s created by usng the foowng code:
SOL>CREATE TABLE COPY_EMP3 AS SELECT * FROM EMPLOYEES
WHERE SALARY<10000;
Then query the COPY_EMP3 tabe.
SOL>SELECT empoyee_d, saary, commsson_pct FROM COPY_EMP3;
SOL>MERGE INTO copy_emp3 c
USING (SELECT * FROM EMPLOYEES ) e
ON (c.empoyee_d = e.empoyee_d)
WHEN MATCHED THEN
UPDATE SET
c.rst_name = e.rst_name,
c.ast_name = e.ast_name,
c.ema = e.ema,
c.phone_number = e.phone_number,
c.hre_date = e.hre_date,
c.|ob_d = e.|ob_d,
c.saary = e.saary*2,
c.commsson_pct = e.commsson_pct,
c.manager_d = e.manager_d,
c.department_d = e.department_d
DELETE WHERE (E.COMMISSION_PCT IS NOT NULL)
WHEN NOT MATCHED THEN
INSERT VALUES(e.empoyee_d, e.rst_name, e.ast_name,
e.ema, e.phone_number, e.hre_date, e.|ob_d,
e.saary, e.commsson_pct, e.manager_d,
e.department_d);
EMPLOYEE_ID n the COPY_EMP3 tabe matches to the EMPLOYEE_ID n the
EMPLOYEES tabe. If a match s found, the row n the COPY_EMP3 tabe s updated
to match the row n the EMPLOYEES tabe and the saary of the empoyee s
doubed. The records of the two empoyees wth vaues n the COMMISSION_PCT
coumn are deeted. If the match s not found, then rows are nserted nto the
COPY_EMP3 tabe.
Page | 77
U$"T+DG Managing Data in DiHerent
Time Iones
Time Iones
The hours of the day are measured by the turnng of the earth. The tme of day
at any partcuar moment depends on where you are. When t s noon n
Greenwch, Engand, t s mdnght aong the Internatona Date Lne. The earth s
dvded nto 24 tme zones, one for each hour of the day. The tme aong the
prme merdan n Greenwch, Engand, s known as Greenwch Mean Tme, or
GMT. GMT s now known as Coordnated Unversa Tme or UTC. UTC s the tme
standard aganst whch a other tme zones n the word are referenced. It s the
same a year round and s not ahected by summer tme or dayght savng tme.
The merdan ne s an magnary ne that runs from the North Poe to the South
Poe. It s known as zero ongtude and t s the ne from whch a other nes of
ongtude are measured. A tme s measured reatve to UTC and a paces have
a attude (ther dstance north or south of the equator) and a ongtude (ther
dstance east or west of the Greenwch merdan).
TIME_ZONE may be set to:
An absoute ohset
Database tme zone
OS oca tme zone
A named regon
SOL>ALTER SESSION SET TIME_ZONE = '-05:00';
SOL>ALTER SESSION SET TIME_ZONE = dbtmezone;
SOL>ALTER SESSION SET TIME_ZONE = oca;
SOL>ALTER SESSION SET TIME_ZONE = 'Amerca/New_York';
TIME_ZONE Sesson Parameter
The Orace database supports storng the tme zone n your date and tme data,
as we as fractona seconds. The ALTER SESSION command can be used to
change tme zone vaues n a users sesson. The tme zone vaues can be set to
an absoute ohset, a named tme zone, a database tme zone, or the oca tme
zone.
CURRENT_DATE, CURRENT_TIMESTAMP,and LOCALTIMESTAMP
CURRENT_DATE:
Page | 78
Returns the current date from the user sesson
Has a data type of DATE
CURRENT_TIMESTAMP:
Returns the current date and tme from the user sesson
Has a data type of TIMESTAMP WITH TIME ZONE
LOCALTIMESTAMP:
Returns the current date and tme from the user sesson
Has a data type of TIMESTAMP
DBTIMEZONE and SESSIONTIMEZONE
Dspay the vaue of the database tme zone
SOL>SELECT DBTIMEZONE FROM DUAL;
Dspay the vaue of the sessons tme zone
SOL>SELECT SESSIONTIMEZONE FROM DUAL;
TIMESTAMP Data Types
The TIMESTAMP data type s an extenson of the DATE data type.
TIMESTAMP (fractona_seconds_ precson)
Ths data type contans the year, month, and day vaues of date, as we as
hour, mnute, and second vaues of tme, where sgncant fractona seconds
precson s the number of dgts n the fractona part of the SECOND datetme
ed. The accepted vaues of sgncant fractona_seconds_precson are 0
through 9. The defaut s 6.
TIMESTAMP (fractona_seconds_precson) WITH TIME ZONE
Ths data type contans a vaues of TIMESTAMP as we as tme zone
dspacement vaue.
TIMESTAMP (fractona_seconds_precson) WITH LOCAL TIME ZONE
Ths data type contans a vaues of TIMESTAMP, wth the foowng exceptons:
F Data s normazed to the database tme zone when t s stored n the database.
F When the data s retreved, users see the data n the sesson tme zone
INTERVAL Data Types
INTERVAL data types are used to store the dherence between two datetme
vaues. There are two casses of ntervas: year-month ntervas and day-tme
ntervas. A year-month nterva s made up of a contguous subset of eds of
YEAR and MONTH, whereas a day-tme nterva s made up of a contguous
subset of eds consstng of DAY, HOUR, MINUTE, and SECOND. The actua
subset of eds that consttute an nterva s caed the precson of the nterva
and s speced n the nterva quaer. Because the number of days n a year s
caendar dependent, the year-month nterva s NLS dependent, whereas day-
tme nterva s NLS ndependent.
The nterva quaer may aso specfy the eadng ed precson, whch s the
number of dgts n the eadng or ony ed, and n case the trang ed s
SECOND, t may aso specfy the fractona seconds precson, whch s the
number of dgts n the fractona part of the SECOND vaue. If not speced, the
defaut vaue for eadng ed precson s 2 dgts, and the defaut vaue for
fractona seconds precson s 6 dgts.
Page | 79
INTERVAL YEAR (year_precson) TO MONTH
Ths data type stores a perod of tme n years and months, where year_precson
s the number of dgts n the YEAR datetme ed. The accepted vaues are 0
through 9. The defaut s 6.
INTERVAL DAY (day_precson) TO SECOND (fractona_seconds_precson)
Ths data type stores a perod of tme n days, hours, mnutes, and seconds,
where day_precson s the maxmum number of dgts n the DAY datetme ed
(accepted vaues are 0 through 9; the defaut s 2), and
fractona_seconds_precson s the number of dgts n the fractona part of the
SECOND ed. The accepted vaues are 0 through 9. The defaut s 6.
Usng the foowng functons:
EXTRACT
TZ_OFFSET
FROM_TZ
TO_TIMESTAMP
TO_YMINTERVAL
TO_DSINTERVAL
Exampes:
EXTRACT
Dspay the YEAR component from the SYSDATE.
SOL> SELECT EXTRACT (YEAR FROM SYSDATE) FROM DUAL;
Dspay the MONTH component from the HIRE_DATE for those empoyees whose
MANAGER_ID s 100.
SOL> SELECT ast_name, hre_date, EXTRACT (MONTH FROM HIRE_DATE)
FROM empoyees
WHERE manager_d = 100;
TZ_OFFSET
Dspay the tme zone ohset for the 'US/Eastern', 'Canada/Yukon' and
'Europe/London' tme zones:
SOL>SELECT TZ_OFFSET('US/Eastern'),
TZ_OFFSET('Canada/Yukon'),TZ_OFFSET('Europe/London')
FROM DUAL;
FROM_TZ
Dspay the TIMESTAMP vaue '2000-03-28 08:00:00' as a TIMESTAMP WITH
TIME ZONE vaue for the 'Austraa/North' tme zone regon.
SOL>SELECT FROM_TZ(TIMESTAMP '2000-07-12 08:00:00', 'Austraa/North')
FROM DUAL;
Page | 80
TO_TIMESTAMP
Dspay the character strng '2007-03-06 11:00:00'
as a TIMESTAMP vaue:
SOL>SELECT TO_TIMESTAMP ('2007-03-06 11:00:00', 'YYYY-MM-DD HH:MI:SS')
FROM DUAL;
TO_YMINTERVAL
Dspay a date that s one year and two months after the hre date for the
empoyees workng n the department wth the DEPARTMENT_ID 20.
SOL>SELECT hre_date, hre_date + TO_YMINTERVAL('01-02') AS
HIRE_DATE_YMININTERVAL FROM empoyees WHERE department_d =
20;
TO_DSINTERVAL
Dspay a date that s 100 days and 10 hours after the hre date for a the
empoyees.
SOL>SELECT ast_name, TO_CHAR(hre_date, 'mm-dd-yy:hh:m:ss') hre_date,
TO_CHAR(hre_date + TO_DSINTERVAL('100 10:00:00'), 'mm-dd-
yy:hh:m:ss') hredate2
FROM empoyees;
Page | 81
Ob|ectves
Wrte a mutpe-coumn subquery
Use scaar subqueres n SOL
Sove probems wth correated subqueres
Update and deete rows usng correated subqueres
Use the EXISTS and NOT EXISTS operators
Use the WITH cause
Multiple+Column Sub3ueries
If you want to compare two or more coumns, you must wrte a compound
WHERE cause usng ogca operators. Usng mutpe-coumn subqueres, you
can combne dupcate WHERE condtons nto a snge WHERE cause.
Syntax
SELECT column" column, ...
FROM table
WHERE (column" column, ...) IN
(SELECT column" column, ...
FROM table
WHERE condition);
The graphc n the sde ustrates that the vaues of MANAGER_ID and
DEPARTMENT_ID from the man query are beng compared wth the
MANAGER_ID and DEPARTMENT_ID vaues retreved by the subquery. Because
the number of coumns that are beng compared s more than one, the
exampe quaes as a mutpe-coumn subquery.
&air5ise 1ersus $onpair5ise Comparisons
Mutpe-coumn comparsons nvovng subqueres can be nonparwse
comparsons or parwse comparsons. If you consder the exampe "Dspay
the detas of the empoyees who work n the same department, and have the
same manager, as Dane? ," you get the correct resut wth the foowng
statement:
SOL>SELECT rst_name, ast_name, manager_d, department_d FROM
emp_demo
WHERE manager_d IN (SELECT manager_d FROM emp_demo WHERE
rst_name = Dane)AND department_d IN (SELECT department_d
FROM emp_demo
WHERE rst_name = Dane);
There s ony one "Dane" n the EMPL_DEMO tabe (Dane Favet, who s
managed by empoyee 108 and works n department 100). However, f the
subqueres return more than one row, the resut mght not be correct. For
exampe, f you run the same query but substtute "|ohn" for "Dane," you get
an ncorrect resut. Ths s because the combnaton of department_d and
Page | 82
Unit+DC Retrie-ing Data Using
Sub3ueries
manager_d s mportant. To get the correct resut for ths query, you need a
parwse comparson.
Parwse Comparson Subquery
Dspay the detas of the empoyees who are managed by the same manager
and work n the same department as empoyees wth the rst name of "|ohn."
Exampes:
SOL>SELECT empoyee_d, manager_d, department_d FROM emp_demo
WHERE (manager_d, department_d) IN (SELECT manager_d,
department_d FROM emp_demo WHERE rst_name = '|ohn') AND
rst_name <> '|ohn';
Nonparwse Comparson Subquery
Dspay the detas of the empoyees who are managed by the same manager
as the empoyees wth the rst name of "|ohn" and work n the same
department as the empoyees wth the rst name of "|ohn."
SOL>SELECT empoyee_d, manager_d, department_d FROM emp_demo
WHERE manager_d IN (SELECT manager_d FROM emp_demo
WHERE rst_name = '|ohn') AND department_d IN (SELECT department_d
FROM emp_demo
WHERE rst_name = '|ohn') AND rst_name <> '|ohn';
Scaar Subquery Expressons
A scaar subquery expresson s a subquery that
returns exacty one coumn vaue from one row.
Scaar subqueres can be used n:
The condton and expresson part of DECODE and CASE
A causes of SELECT except GROUP BY
The SET cause and WHERE cause of an UPDATE statement
Scaar Subqueres: Exampes
Scaar subqueres n CASE expressons:
SOL>SELECT empoyee_d, ast_name, (CASE WHEN department_d =
(SELECT department_d FROM departments WHERE ocaton_d =
1800)
THEN 'Canada' ELSE 'USA' END) ocaton FROM empoyees;
Scaar subqueres n the ORDER BY cause
SOL>SELECT empoyee_d, ast_name FROM empoyees e
ORDER BY (SELECT department_name FROM departments d
WHERE e.department_d = d.department_d);
Page | 83
Correlated Sub3ueries
The Orace server performs a correated subquery when the subquery references
a coumn from a tabe referred to n the parent statement. A correated subquery
s evauated once for each row processed by the parent statement. The parent
statement can be a SELECT, UPDATE, or DELETE statement.
$ested Sub3ueries 1ersus Correlated Sub3ueries
Wth a norma nested subquery, the nner SELECT query runs rst and executes
once, returnng vaues to be used by the man query. A correated subquery,
however, executes once for each canddate row consdered by the outer query.
That s, the nner query s drven by the outer query.
Nested Subquery Executon
F The nner query executes rst and nds a vaue.
F The outer query executes once, usng the vaue from the
nner query.
Correated Subquery Executon
F Get a canddate row (fetched by the outer query).
F Execute the nner query usng the vaue of the canddate row.
F Use the vaues resutng from the nner query to quafy or
dsquafy the canddate.
Repeat unt no canddate row remans.
A correated subquery s one way of readng every row n a tabe and comparng
vaues n each row aganst reated data. It s used whenever a subquery must
return a dherent resut or set of resuts for each canddate row consdered by the
man query. That s, you use a correated subquery to answer a mutpart
queston whose answer depends on the vaue n each row processed by the
parent statement.
The Orace server performs a correated subquery when the subquery references
a coumn from a tabe n the parent query.
Note: You can use the ANY and ALL operators n a correated subquery
Exampe:
Fnd a empoyees who earn more than the average saary n ther department.
SOL> SELECT ast_name, saary, department_d FROM empoyees outer
WHERE saary > (SELECT AVG(saary) FROM empoyees WHERE
department_d =
outer.department_d);
Note: Each tme a row from the outer query s processed, the nner query s
evauated.
Dspay detas of those empoyees who have changed |obs at east twce.
Page | 84
SOL>SELECT e.empoyee_d, ast_name,e.|ob_d FROM empoyees e WHERE 2
<= (SELECT COUNT(*) FROM |ob_hstory WHERE empoyee_d =
e.empoyee_d);
The Orace server evauates a correated subquery as foows:
1. Seect a row from the tabe speced n the outer query. Ths w be the
current canddate row.
2. Store the vaue of the coumn referenced n the subquery from ths
canddate row. (In the exampe n the sde, the coumn referenced n the
subquery s E.EMPLOYEE_ID.)
3. Perform the subquery wth ts condton referencng the vaue from the
outer querys canddate row. (In the exampe n the sde, the COUNT(*) group
functon s evauated based on the vaue of the E.EMPLOYEE_ID coumn obtaned
n step 2.)
4. Evauate the WHERE cause of the outer query on the bass of resuts of
the subquery performed n step 3. Ths determnes whether the canddate row s
seected for output. (In the exampe, the number of tmes an empoyee has
changed |obs, evauated by the subquery, s compared wth 2 n the WHERE
cause of the outer query. If the condton s satsed, that empoyee record s
dspayed.)
5. Repeat the procedure for the next canddate row of the tabe, and so on,
unt a the rows n the tabe have been processed.
The correaton s estabshed by usng an eement from the outer query n the
subquery. In ths exampe, you compare EMPLOYEE_ID from the tabe n the
subquery wth EMPLOYEE_ID from the tabe n the outer query.
Usng the EXISTS Operator
Fnd Empoyees Who Have at Least One Person Reportng to Them
SOL>SELECT empoyee_d, ast_name, |ob_d, department_d FROM empoyees
outer
WHERE EXISTS ( SELECT 'X' FROM empoyees WHERE manager_d =
outer.empoyee_d);
Fnd A Departments That Do Not Have Any Empoyees
SOL>SELECT department_d, department_name FROM departments d WHERE
NOT EXISTS (SELECT 'X' FROM empoyees WHERE department_d
= d.department_d);
Usng Correated DELETE
Use a correated subquery to deete ony those rows from the EMPL6 tabe that
aso exst n the EMP_HISTORY tabe
SOL>DELETE FROM emp6 E WHERE empoyee_d = (SELECT empoyee_d
FROM emp_hstory WHERE empoyee_d = E.empoyee_d);
Two tabes are used n ths exampe. They are:
F The EMPL6 tabe, whch provdes detas of a the current empoyees
F The EMP_HISTORY tabe, whch provdes detas of prevous empoyees
Page | 85
EMP_HISTORY contans data regardng prevous empoyees, so t woud be
erroneous f the same empoyees record exsted n both the EMPL6 and
EMP_HISTORY tabes. You can deete such erroneous records by usng the
correated subquery
WITH Cause
Usng the WITH cause, you can dene a query bock before usng t n a query.
The WITH cause (formay known as subquery_factorng_cause) enabes you to
reuse the same query bock n a SELECT statement when t occurs more than
once wthn a compex query. Ths s partcuary usefu when a query has many
references to the same query bock and there are |ons and aggregatons.
Usng the WITH cause, you can reuse the same query when t s costy to
evauate the query bock and t occurs more than once wthn a compex query.
Usng the WITH cause, the Orace server retreves the resuts of a query bock
and stores t n the users temporary tabespace. Ths can mprove performance.
WITH Cause Benets
F Makes the query easy to read
F Evauates a cause ony once, even f t appears mutpe tmes n the query
F In most cases, may mprove performance for arge queres
Usng the WITH cause, wrte a query to dspay the department name and tota
saares for those departments whose tota saary s greater than the average
saary across departments
WITH Cause: Exampe
WITH
dept_costs AS (
SELECT d.department_name, SUM(e.saary) AS dept_tota
FROM empoyees e |OIN departments d
ON e.department_d = d.department_d
GROUP BY d.department_name),
avg_cost AS (
SELECT SUM(dept_tota)/COUNT(*) AS dept_avg
FROM dept_costs)
SELECT *
FROM dept_costs
WHERE dept_tota >
(SELECT dept_avg
FROM avg_cost)
ORDER BY department_name;
WITH Cause Usage Notes
F It s used ony wth SELECT statements.
F A query name s vsbe to a WITH eement query bocks (ncudng ther
subquery bocks) dened after t and the man query bock tsef (ncudng ts
subquery bocks).
F When the query name s the same as an exstng tabe name, the parser
searches from the nsde out, and the query bock name takes precedence
over the tabe name.
F The WITH cause can hod more than one query. Each query s then separated
by a comma.
Page | 86
Page | 87
0hat %re Regular /pressionsJ
You use reguar expressons to search for (and manpuate) smpe and compex
patterns n
strng data by usng standard syntax conventons.
You use a set of SOL functons and condtons to search for and manpuate
strngs n SOL and PL/SOL.
You specfy a reguar expresson by usng:
Metacharacters, whch are operators that specfy the search agorthms
Lteras, whch are the characters for whch you are searchng
(enefts of Using Regular /pressions
Reguar expressons enabe you to mpement compex match ogc n the
database wth the foowng benets:
By centrazng match ogc n Orace Database, you avod ntensve strng
processng of SOL resuts sets by mdde-ter appcatons.
Usng server-sde reguar expressons to enforce constrants, you emnate the
need to code data vadaton ogc on the cent.
The but-n SOL and PL/SOL reguar expresson functons and condtons make
strng manpuatons more powerfu and easer than n prevous reeases of
Orace Database 10!.
Usng the Reguar Expressons Functons and Condtons n SOL and PL/SOL
Orace Database provdes a set of SOL functons that you use to search and
manpuate strngs usng reguar expressons. You use these functons on a
text tera, bnd varabe, or any coumn that hods character data such as
CHAR, NCHAR, CLOB, NCLOB, NVARCHAR2, and VARCHAR2 (but not LONG). A
reguar expresson must be encosed or wrapped between snge quotaton
marks. Ths ensures that the entre expresson s nterpreted by the SOL
functon and can mprove the readabty of your code.
R!>&)L"K: Ths condton searches a character coumn for a pattern. Use
ths condton n the WHERE cause of a query to return rows matchng the
reguar expresson you specfy.
R!>&)R&L%C: Ths functon searches for a pattern n a character coumn
and repaces each occurrence of that pattern wth the pattern you specfy.
R!>&)"$STR: Ths functon searches a strng for a gven occurrence of a
reguar expresson pattern. You specfy whch occurrence you want to nd and
the start poston to search from. Ths functon returns an nteger ndcatng
the poston n the strng where the match s found.
R!>&)SU(STR: Ths functon returns the actua substrng matchng the
reguar expresson pattern you specfy.
R!>&)C#U$T: Ths functon returns the number of tmes a pattern match s
found n the nput strng.
0hat %re MetacharactersJ
Metacharacters are speca characters that have a speca meanng such as a
wdcard, a repeatng character, a nonmatchng character, or a range of
characters.
Page | 88
U$"T+DL Regular /pression
Support
You can use severa predened metacharacter symbos n the pattern
matchng.
For exampe, the (f|ht)tps?:$ reguar expresson searches for the foowng
from the begnnng of the strng:
The teras f or ht
The t tera
The p tera, optonay foowed by the s tera
The coon ":" tera at the end of the strng
Using Metacharacters 5ith Regular /pressions
Any character, " . " : a.b matches the strngs abb, acb, and adb, but not acc.
One or more, " + " : a+ matches the strngs a, aa, and aaa, but does not
match bbb.
Zero or one, " ? ": ab?c matches the strngs abc and ac, but does not match
abbc.
Zero or more, " * ": ab*c matches the strngs ac, abc, and abbc, but does
not match abb.
Exact count, " {m} ": a{3} matches the strngs aaa, but does not match aa.
At east count, " {m,} ": a{3,} matches the strngs aaa and aaaa, but not
aa.
Between count, " {m,n} ": a{3,5} matches the strngs aaa, aaaa, and
aaaaa, but not aa.
Matchng character st, " |.| ": |abc| matches the rst character n the strngs
a, b, and cod, but does not match any characters n do.
Or, " | ": a|b matches character a or character b.
Subexpresson, " (.) ": (abc)?def matches the optona strng abc, foowed by
def. The expresson matches abcdefgh and def, but does not match gh. The
subexpresson can be a strng of teras or a compex expresson contanng
operators.
Begnnng/end of ne anchor, " " and "$": def matches def n the strng
defgh but does not match def n abcdef. def$ matches def n the strng abcdef
but does not match def n the strng defgh.
Escape character " \ ": \+ searches for a +. It matches the pus
character n the strng abc+def, but does not match Abcdef.
Backreference, " \n ": (abc|def)xy\1 matches the strngs abcxyabc and
defxydef, but does not match abcxydef or abcxy. A backreference enabes you to
search for a repeated strng wthout knowng the actua strng ahead of tme. For
exampe, the expresson (.*)\1$ matches a ne consstng of two ad|acent
nstances of the same strng.
Dgt character, "\d": The expresson \|\d{3}\| \d{3}-\d{4}$ matches |650|
555-1212 but does not match 650-555-1212.
Character cass, " |:cass:| " : ||:upper:||+ searches for one or more
consecutve uppercase characters. Ths matches DEF n the strng abcDEFgh but
does not match the strng abcdefgh.
&erforming a (asic Search Using the R!>&)L"K Condition
Exampe:
SOL>SELECT rst_name, ast_name FROM empoyees WHERE REGEXP_LIKE
(rst_name, 'Ste(v|ph)en$');
REGEXP_LIKE s smar to the LIKE condton, except that REGEXP_LIKE performs
reguar-expresson matchng nstead of the smpe pattern matchng performed
Page | 89
by LIKE. Ths condton evauates strngs usng characters as dened by the nput
character set.
In ths query, aganst the EMPLOYEES tabe, a empoyees wth rst names
contanng ether Steven or Stephen are dspayed. In the expresson used,
'Ste(v|ph)en$'
F ndcates the begnnng of the expresson
F $ ndcates the end of the expresson
F | ndcates ether/or
Using the R!>&)R&L%C function
Exampe
SOL>SELECT REGEXP_REPLACE(phone_number, \.',-') AS phone
FROM empoyees;
Usng the REGEXP_REPLACE functon, you reformat the phone number to repace
the perod (.) demter wth a dash (-) demter. Here s an expanaton of each of
the eements used n the reguar expresson exampe:
F phone_number s the source coumn.
F \. s the search pattern.
1 Use snge quotaton marks ( ) to search for the tera
character perod (.).
1 Use a backsash (\) to search for a character that s
normay treated as a metacharacter.
F - s the repace strng.
Exampe:
6inding &atterns Using the R!>&)"$STR 6unction
SOL>SELECT street_address,REGEXP_INSTR(street_address,'||:apha:||') AS
Frst_Apha_Poston
FROM ocatons;
The REGEXP_INSTR functon s used to search the street address to nd the
ocaton of the rst aphabetc character, regardess of whether t s n uppercase
or owercase. Note that |:<class>:| mpes a character cass and matches any
character from wthn that cass; |:apha:| matches wth any aphabetc character.
The parta resuts are dspayed.
In the expresson used n the query '||:apha:||':
F | starts the expresson.
F |:apha:| ndcates aphabetc character cass.
| ends the expresson.
/tracting Substrings Using the R!>&)SU(STR 6unction
SOL>SELECT REGEXP_SUBSTR(street_address , ' | |+ ') AS Road
FROM ocatons;
In ths exampe, the road names are extracted from the LOCATIONS tabe. To do
ths, the contents n the STREET_ADDRESS coumn that are after the rst space
are returned usng the REGEXP_SUBSTR functon. In the expresson used n the
query | |+ :
Page | 90
F | starts the expresson.
F ndcates NOT.
F ndcates space.
F | ends the expresson.
F + ndcates 1 or more.
F ndcates space.

Page | 91

You might also like