You are on page 1of 366

Writing Basic SQL SELECT Statements

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
40 minutes 25 minutes 65 minutes

Topic
Lecture Practice Total

Selecting All Columns

SELECT * FROM departments;

1-5

Copyright Oracle Corporation, 2001. All rights reserved.

Selecting All Columns of All o!s You can display all columns of data in a table by following the SELECT keyword with an asterisk *!" #n the e$ample on the slide% the department table contains four columns& DEPARTMENT_ID% DEPARTMENT_NAME% MANAGER_ID% and LOCATION_ID" The table contains se'en rows% one for each department" You can also display all columns in the table by listing all the columns after the SELECT keyword" (or e$ample% the following )*L statement% like the e$ample on the slide% displays all columns and all rows of the DEPARTMENTS table& SELECT ROM department_id, department_name, manager_id, location_id department!"

"nstructor #ote Let the students know that details of all the tables are gi'en in +ppendi$ ," "ntroduction to $racle%i: SQL 1-5

Selecting Specific Columns

SELECT department_id, location_id FROM departments;

1-&

Copyright Oracle Corporation, 2001. All rights reserved.

Selecting Specific Columns of All o!s You can use the SELECT statement to display specific columns of the table by specifying the column names% separated by commas" The e$ample on the slide displays all the department numbers and location numbers from the DEPARTMENTS table" #n the SELECT clause% specify the columns that you want% in the order in which you want them to appear in the output" (or e$ample% to display location before department number going from left to right% you use the following statement& SELECT location_id, department_id ROM department!"

'
"nstructor #ote You can also select from pseudocolumns" + pseudocolumn beha'es like a table column but is not actually stored in the table" You cannot insert or delete 'alues of the pseudocolumns" )ome a'ailable pseudocolumns are C#RR$AL% NE%T$AL% LE$EL% RO&ID% and RO&N#M" "ntroduction to $racle%i: SQL 1-&

Arithmetic E(pressions
Create e(pressions !ith num)er and date data )* using arithmetic operators+
$perator , . 0 -escription Add Su)tract /ultipl* -i1ide

1-%

Copyright Oracle Corporation, 2001. All rights reserved.

Arithmetic E(pressions You may need to modify the way in which data is displayed% perform calculations% or look at what-if scenarios" These are all possible using arithmetic e$pressions" +n arithmetic e$pression can contain column names% constant numeric 'alues% and the arithmetic operators" Arithmetic $perators The slide lists the arithmetic operators a'ailable in )*L" You can use arithmetic operators in any clause of a )*L statement e$cept in the ROM clause"

"nstructor #ote You can use the addition and subtraction operators only with DATE and TIMESTAMP data types" "ntroduction to $racle%i: SQL 1-%

2sing Arithmetic $perators


SELECT last_name, salary, salary + 300 FROM employees;

'

1-13

Copyright Oracle Corporation, 2001. All rights reserved.

2sing Arithmetic $perators The e$ample in the slide uses the addition operator to calculate a salary increase of ./00 for all employees and displays a new SALAR'()** column in the output" 0ote that the resultant calculated column SALAR'()** is not a new column in the EMPLO'EES table1 it is for display only" ,y default% the name of a new column comes from the calculation that generated it2in this case% !alar+()**" Note: The 3racle4i ser'er ignores blank spaces before and after the arithmetic operator"

"ntroduction to $racle%i: SQL 1-13

$perator 4recedence
SELECT last_name, salary, FROM employees; !*salary+ 00

'

1-15

Copyright Oracle Corporation, 2001. All rights reserved.

$perator 4recedence 6continued7 The e$ample on the slide displays the last name% salary% and annual compensation of employees" #t calculates the annual compensation as 52 multiplied by the monthly salary% plus a one-time bonus of .500" 0otice that multiplication is performed before addition" Note: 6se parentheses to reinforce the standard order of precedence and to impro'e clarity" (or e$ample% the e$pression on the slide can be written as ,-.*!alar+/(-** with no change in the result"

"nstructor #ote 7emo& -_prec-0!1l, -_prec.0!1l Purpose& To illustrate 'iewing a 8uery containing no parentheses and e$ecuting a 8uery with parentheses to o'erride rules of precedence" "ntroduction to $racle%i: SQL 1-15

2sing 4arentheses
SELECT last_name, salary, FROM employees; !*"salary+ 00#

'

1-18

Copyright Oracle Corporation, 2001. All rights reserved.

2sing 4arentheses You can o'erride the rules of precedence by using parentheses to specify the order in which operators are e$ecuted" The e$ample on the slide displays the last name% salary% and annual compensation of employees" #t calculates the annual compensation as monthly salary plus a monthly bonus of .500% multiplied by 52" ,ecause of the parentheses% addition takes priority o'er multiplication"

"ntroduction to $racle%i: SQL 1-18

-efining a #ull 9alue


A null is a 1alue that is una1aila)le: unassigned: un;no!n: or inapplica)le+ A null is not the same as <ero or a )lan; space+

SELECT last_name, $o%_id, salary, commission_pct FROM employees;

' '

1-1=

Copyright Oracle Corporation, 2001. All rights reserved.

#ull 9alues #f a row lacks the data 'alue for a particular column% that 'alue is said to be null% or to contain a null" + null is a 'alue that is una'ailable% unassigned% unknown% or inapplicable" + null is not the same as 9ero or a space" :ero is a number% and a space is a character" ;olumns of any data type can contain nulls" <owe'er% some constraints% NOT N#LL and PRIMAR' 2E'% pre'ent nulls from being used in the column" #n the COMMISSION_PCT column in the EMPLO'EES table% notice that only a sales manager or sales representati'e can earn a commission" 3ther employees are not entitled to earn commissions" + null represents that fact"

"nstructor #ote 7emo& -_n3ll0!1l Purpose& To illustrate calculating with null 'alues" "ntroduction to $racle%i: SQL 1-1=

#ull 9alues in Arithmetic E(pressions


Arithmetic e(pressions containing a null 1alue e1aluate to null+
SELECT last_name, FROM employees; !*salary*commission_pct

' '

1-15

Copyright Oracle Corporation, 2001. All rights reserved.

#ull 9alues 6continued7 #f any column 'alue in an arithmetic e$pression is null% the result is null" (or e$ample% if you attempt to perform di'ision with 9ero% you get an error" <owe'er% if you di'ide a number by null% the result is a null or unknown" #n the e$ample on the slide% employee =ing does not get any commission" ,ecause the COMMISSION_PCT column in the arithmetic e$pression is null% the result is null" (or more information% see Oracle9i SQL Reference, >,asic ?lements of )*L"@

"ntroduction to $racle%i: SQL 1-15

2sing Column Aliases


SELECT last_name &S name, commission_pct comm FROM employees;

'
SELECT last_name '(ame', salary* ! '&nn)al Salary' FROM employees;

'

1-1>

Copyright Oracle Corporation, 2001. All rights reserved.

Column Aliases 6continued7 The first e$ample displays the names and the commission percentages of all the employees" 0otice that the optional AS keyword has been used before the column alias name" The result of the 8uery is the same whether the AS keyword is used or not" +lso notice that the )*L statement has the column aliases% name and comm% in lowercase% whereas the result of the 8uery displays the column headings in uppercase" +s mentioned in a pre'ious slide% column headings appear in uppercase by default" The second e$ample displays the last names and annual salaries of all the employees" ,ecause Ann3al Salar+ contain a space% it has been enclosed in double 8uotation marks" 0otice that the column heading in the output is e$actly the same as the column alias"

"nstructor #ote Point out the optional AS keyword in the first e$ample and the double 8uotation marks in the second e$ample" +lso show that the aliases always appear in uppercase% unless enclosed within double 8uotation marks" "ntroduction to $racle%i: SQL 1-1>

2sing the Concatenation $perator

SELECT FROM

last_name**$o%_id &S 'Employees' employees;

'

1-1%

Copyright Oracle Corporation, 2001. All rights reserved.

Concatenation $perator 6continued7 #n the e$ample% LAST_NAME and 4O5_ID are concatenated% and they are gi'en the alias Emplo+ee!" 0otice that the employee last name and Aob code are combined to make a single output column" The AS keyword before the alias name makes the SELECT clause easier to read"

"ntroduction to $racle%i: SQL 1-1%

2sing Literal Character Strings

SELECT last_name **+ is a +**$o%_id &S 'Employee ,etails' FROM employees;

'

1-51

Copyright Oracle Corporation, 2001. All rights reserved.

Literal Character Strings 6continued7 The e$ample on the slide displays last names and Aob codes of all employees" The column has the heading ?mployee 7etails" 0otice the spaces between the single 8uotation marks in the SELECT statement" The spaces impro'e the readability of the output" #n the following e$ample% the last name and salary for each employee are concatenated with a literal to gi'e the returned rows more meaning" SELECT la!t_name 6678 - Mont9 !alar+ : 766!alar+ Mont9l+ ROM emplo+ee!"

'
"ntroduction to $racle%i: SQL 1-51

-uplicate o!s
The default displa* of ?ueries is all ro!s: including duplicate ro!s+
SELECT department_id FROM employees;

'

1-55

Copyright Oracle Corporation, 2001. All rights reserved.

-uplicate o!s 6nless you indicate otherwise% i)*LBPlus displays the results of a 8uery without eliminating duplicate rows" The e$ample on the slide displays all the department numbers from the EMPLO'EES table" 0otice that the department numbers are repeated"

"ntroduction to $racle%i: SQL 1-55

Eliminating -uplicate

o!s

Eliminate duplicate ro!s )* using the ,-ST-(CT ;e*!ord in the SELECT clause+
SELECT ,-ST-(CT department_id FROM employees;

1-58

Copyright Oracle Corporation, 2001. All rights reserved.

-uplicate o!s 6continued7 To eliminate duplicate rows in the result% include the DISTINCT keyword in the SELECT clause immediately after the SELECT keyword" #n the e$ample on the slide% the EMPLO'EES table actually contains 20 rows but there are only se'en uni8ue department numbers in the table" You can specify multiple columns after the DISTINCT 8ualifier" The DISTINCT 8ualifier affects all the selected columns% and the result is e'ery distinct combination of the columns" SELECT ROM DISTINCT department_id, ;o<_id emplo+ee!"

'
"ntroduction to $racle%i: SQL 1-58

-ispla*ing Ta)le Structure


2se the iSQL.4lus ,ESCR-.E command to displa* the structure of a ta)le+
,ESC/R-.E0 tablename

1-5%

Copyright Oracle Corporation, 2001. All rights reserved.

-ispla*ing the Ta)le Structure #n i)*LBPlus% you can display the structure of a table using the DESCRI5E command" The command shows the column names and data types% as well as whether a column must contain data" #n the synta$& tablename is the name of any e$isting table% 'iew% or synonym accessible to the user

"ntroduction to $racle%i: SQL 1-5%

-ispla*ing Ta)le Structure

,ESCR-.E employees

1-83

Copyright Oracle Corporation, 2001. All rights reserved.

-ispla*ing the Ta)le Structure 6continued7 The e$ample on the slide displays the information about the structure of the DEPARTMENTS table" #n the result& Null? Type indicates whether a column must contain data1 NOT N#LL indicates that a column must contain data displays the data type for a column

The data types are described in the following table& Data Type Description
N#M5ER,p,s/ $ARC=AR.,s/ DATE C=AR,s/ 0umber 'alue ha'ing a ma$imum number of digits p% with s digits to the right of the decimal point Cariable-length character 'alue of ma$imum si9e s 7ate and time 'alue between Danuary 5% 4E52 ,";"% and 7ecember /5% 4444 +"7" (i$ed-length character 'alue of si9e s

"nstructor #ote #nform students that the column se8uence in DESCRI5E tablename is the same as that in SELECT * ROM tablename . The order in which the columns are displayed is determined when the table is created" "ntroduction to $racle%i: SQL 1-83

4ractice 1 $1er1ie!
This practice co1ers the follo!ing topics:

Selecting all data from different ta)les -escri)ing the structure of ta)les 4erforming arithmetic calculations and specif*ing column names 2sing iSQL.4lus

1-85

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 1 $1er1ie! This is the first of many practices" The solutions if you re8uire them! can be found in +ppendi$ +" Practices are intended to introduce all topics co'ered in the lesson" *uestions 2F4 are paper-based" #n any practice% there may be >if you ha'e time@ or >if you want an e$tra challenge@ 8uestions" 7o these only if you ha'e completed all other 8uestions within the allocated time and would like a further challenge to your skills" Perform the practices slowly and precisely" You can e$periment with sa'ing and running command files" #f you ha'e any 8uestions at any time% attract the instructorGs attention" 4aper-Based Questions (or 8uestions 2F4% circle either True or (alse"

"nstructor #ote Let the students know that to get a listing of the tables they can access during the course% the command is& SELECT * ROM TA5" "ntroduction to $racle%i: SQL 1-85

4ractice 1 5" #nitiate an i)*LBPlus session using the user #7 and password pro'ided by the instructor" 2" i)*LBPlus commands access the database" TrueH(alse /" The following SELECT statement e$ecutes successfully& SELECT la!t_name, ;o<_id, !alar+ AS Sal ROM emplo+ee!" TrueH(alse 4" The following SELECT statement e$ecutes successfully& SELECT * ROM ;o<_grade!" TrueH(alse 5" There are four coding errors in this statement" ;an you identify themI SELECT !al > -. ROM emplo+ee_id, la!t_name ANN#AL SALAR' emplo+ee!"

6" )how the structure of the DEPARTMENTS table" )elect all data from the table"

"ntroduction to $racle%i: SQL 1-8&

4ractice 1 6continued7 E" )how the structure of the EMPLO'EES table" ;reate a 8uery to display the last name% Aob code% hire date% and employee number for each employee% with employee number appearing first" Pro'ide an alias )T+JT7+T? for the <#J?K7+T? column" )a'e your )*L statement to a file named la<-_?0!1l"

L" Jun your 8uery in the file la<-_?0!1l"

'
"ntroduction to $racle%i: SQL 1-8>

4ractice 1 6continued7 4" ;reate a 8uery to display uni8ue Aob codes from the EMPLO'EES table"

#f you ha'e time% complete the following e$ercises& 50" ;opy the statement from la<-_?0!1l into the i)*LBPlus ?dit window" 0ame the column headings Emp @% Emplo+ee% 4o<% and =ire Date% respecti'ely" Jun your 8uery again"

'

"ntroduction to $racle%i: SQL 1-8@

4ractice 1 6continued7 55" 7isplay the last name concatenated with the Aob #7% separated by a comma and space% and name the column Emplo+ee and Title"

'
#f you want an e$tra challenge% complete the following e$ercise& 52" ;reate a 8uery to display all the data from the EMPLO'EES table" )eparate each column by a comma" 0ame the column T=E_O#TP#T"

'

"ntroduction to $racle%i: SQL 1-8%

estricting and Sorting -ata

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
45 minutes /0 minutes E5 minutes

Topic
Lecture Practice Total

2sing the 12ERE Clause

SELECT employee_id, last_name, $o%_id, department_id FROM employees 12ERE department_id 3 40 ;

5-5

Copyright Oracle Corporation, 2001. All rights reserved.

2sing the 12ERE Clause #n the e$ample% the SELECT statement retrie'es the name% Aob #7% and department number of all employees whose Aob #7 is SA_REP" 0ote that the Aob title SA_REP has been specified in uppercase to ensure that it matches the Aob #7 column in the EMPLO'EES table" ;haracter strings are case sensiti'e"

"ntroduction to $racle%i: SQL 5-5

Character Strings and -ates


Character strings and date 1alues are enclosed in single ?uotation mar;s+ Character 1alues are case sensiti1e: and date 1alues are format sensiti1e+ The default date format is ---/$#+
SELECT last_name, $o%_id, department_id FROM employees 12ERE last_name 3 +15alen+;

5-&

Copyright Oracle Corporation, 2001. All rights reserved.

Character Strings and -ates ;haracter strings and dates in the &=ERE clause must be enclosed in single 8uotation marks 77!" 0umber constants% howe'er% should not be enclosed in single 8uotation marks" +ll character searches are case sensiti'e" #n the following e$ample% no rows are returned because the EMPLO'EES table stores all the last names in mi$ed case& SELECT la!t_name, ;o<_id, department_id ROM emplo+ee! &=ERE la!t_name : 7&=ALEN7" 3racle databases store dates in an internal numeric format% representing the century% year% month% day% hours% minutes% and seconds" The default date display is 77-M30-JJ" Note: ;hanging the default date format is co'ered in a subse8uent lesson"

"nstructor #ote )ome students may ask how to o'erride the case sensiti'ity" Later in the course% we co'er the use of single-row functions such as #PPER and LO&ER to o'erride the case sensiti'ity" "ntroduction to $racle%i: SQL 5-&

Comparison Conditions
$perator A B BA D DA DB /eaning E?ual to Creater than Creater than or e?ual to Less than Less than or e?ual to #ot e?ual to

5->

Copyright Oracle Corporation, 2001. All rights reserved.

Comparison Conditions ;omparison conditions are used in conditions that compare one e$pression to another 'alue or e$pression" They are used in the &=ERE clause in the following format& Syntax 000 &=ERE expr operator value For Example 000 &=ERE 9ire_date:7*-A4ANABC7 000 &=ERE !alar+D:E*** 000 &=ERE la!t_name:7Smit97 +n alias cannot be used in the &=ERE clause" Note: The symbol F: and G: can also represent the not equal to condition"

"ntroduction to $racle%i: SQL 5->

2sing Comparison Conditions

SELECT last_name, salary FROM employees 12ERE salary 63 3000;

5-@

Copyright Oracle Corporation, 2001. All rights reserved.

2sing the Comparison Conditions #n the e$ample% the SELECT statement retrie'es the last name and salary from the EMPLO'EES table% where the employee salary is less than or e8ual to /000" 0ote that there is an e$plicit 'alue supplied to the &=ERE clause" The e$plicit 'alue of /000 is compared to the salary 'alue in the SALAR' column of the EMPLO'EES table"

"ntroduction to $racle%i: SQL 5-@

$ther Comparison Conditions


$perator .ET1EE( 777&(,777 -("set# L-8E -S (9LL /eaning Bet!een t!o 1alues 6inclusi1e7:

/atch an* of a list of 1alues /atch a character pattern "s a null 1alue

5-%

Copyright Oracle Corporation, 2001. All rights reserved.

"ntroduction to $racle%i: SQL 5-%

2sing the .ET1EE( Condition


2se the .ET1EE( condition to displa* ro!s )ased on a range of 1alues+
SELECT last_name, salary FROM employees 12ERE salary .ET1EE( !:00 &(, 3:00; Lo!er limit 2pper limit

5-13

Copyright Oracle Corporation, 2001. All rights reserved.

The .ET1EE( Condition You can display rows based on a range of 'alues using the 5ET&EEN range condition" The range that you specify contains a lower limit and an upper limit" The SELECT statement on the slide returns rows from the EMPLO'EES table for any employee whose salary is between .2%500 and ./%500" Calues specified with the 5ET&EEN condition are inclusi'e" You must specify the lower limit first"

"nstructor #ote ?mphasi9e that the 'alues specified with the 5ET&EEN operator in the e$ample are inclusi'e" ?$plain that 5ET&EEN H AND H is actually translated by 3racle ser'er to a pair of AND conditions& a D: loIer limit! AND a J: 9ig9er limit!" )o using 5ET&EEN H AND H has no performance benefits% and it is used for logical simplicity" 7emo& ._<etI0!1l Purpose& To illustrate using the 5ET&EEN operator" "ntroduction to $racle%i: SQL 5-13

2sing the -( Condition


2se the -( mem)ership condition to test for 1alues in a list+
SELECT employee_id, last_name, salary, mana;er_id FROM employees 12ERE mana;er_id -( " 00, 0 , !0 #;

5-11

Copyright Oracle Corporation, 2001. All rights reserved.

The -( Condition To test for 'alues in a specified set of 'alues% use the IN condition" The IN condition is also known as the membership condition" The slide e$ample displays employee numbers% last names% salaries% and managerGs employee numbers for all the employees whose managerGs employee number is 500% 505% or 205" The IN condition can be used with any data type" The following e$ample returns a row from the EMPLO'EES table for any employee whose last name is included in the list of names in the &=ERE clause& SELECT emplo+ee_id, manager_id, department_id ROM emplo+ee! &=ERE la!t_name IN ,7=art!tein7, 7$arga!7/" #f characters or dates are used in the list% they must be enclosed in single 8uotation marks 77!" "nstructor #ote ?$plain that IN , 000 / is actually translated by 3racle ser'er to a set of OR conditions& a : Kal3e- OR a : Kal3e. OR a : Kal3e)" )o using IN , 000 / has no performance benefits% and it is used for logical simplicity" 7emo& ._in0!1l Purpose& To illustrate using the IN operator" "ntroduction to $racle%i: SQL 5-11

2sing the L-8E Condition


2se the L-8E condition to perform !ildcard searches of 1alid search string 1alues+ Search conditions can contain either literal characters or num)ers:
L < denotes <ero or man* characters+ L _ denotes one character+

SELECT FROM 12ERE

=irst_name employees =irst_name L-8E +S<+;

5-15

Copyright Oracle Corporation, 2001. All rights reserved.

The L-8E Condition You may not always know the e$act 'alue to search for" You can select rows that match a character pattern by using the LI2E condition" The character pattern-matching operation is referred to as a ildcard search" Two symbols can be used to construct the search string"
Sym bol M _ Description Jepresents any se8uence of 9ero or more characters Jepresents any single character

The SELECT statement on the slide returns the employee first name from the EMPLO'EES table for any employee whose first name begins with an S" 0ote the uppercase S" 0ames beginning with an s are not returned" The LI2E condition can be used as a shortcut for some 5ET&EEN comparisons" The following e$ample displays the last names and hire dates of all employees who Aoined between Danuary 5445 and 7ecember 5445& SELECT la!t_name, 9ire_date ROM emplo+ee! &=ERE 9ire_date LI2E 7MBC7" "ntroduction to $racle%i: SQL 5-15

2sing the L-8E Condition


Eou can com)ine pattern-matching characters+
SELECT last_name FROM employees 12ERE last_name L-8E +_o<+;

Eou can use the ESC&>E identifier to search for the actual % and _ s*m)ols+

5-18

Copyright Oracle Corporation, 2001. All rights reserved.

Com)ining Wildcard Characters The M and _ symbols can be used in any combination with literal characters" The e$ample on the slide displays the names of all employees whose last names ha'e an o as the second character" The ESC&>E $ption Nhen you need to ha'e an e$act match for the actual ! and " characters% use the ESCAPE option" This option specifies what the escape character is" #f you want to search for strings that contain O)+KG% you can use the following )*L statement& SELECT emplo+ee_id, la!t_name, ;o<_id ROM emplo+ee! &=ERE ;o<_id LI2E 7MSAN_M7 ESCAPE 7N7"

The ESCAPE option identifies the backslash P! as the escape character" #n the pattern% the escape character precedes the underscore K!" This causes the 3racle )er'er to interpret the underscore literally" "ntroduction to $racle%i: SQL 5-18

2sing the (9LL Conditions


Test for nulls !ith the -S (9LL operator+
SELECT last_name, mana;er_id FROM employees 12ERE mana;er_id -S (9LL;

5-1=

Copyright Oracle Corporation, 2001. All rights reserved.

The (9LL Conditions The N#LL conditions include the IS N#LL condition and the IS NOT N#LL condition" The IS N#LL condition tests for nulls" + null 'alue means the 'alue is una'ailable% unassigned% unknown% or inapplicable" Therefore% you cannot test with Q because a null cannot be e8ual or une8ual to any 'alue" The slide e$ample retrie'es the last names and managers of all employees who do not ha'e a manager" (or another e$ample% to display last name% Aob #7% and commission for all employees who are 03T entitled to get a commission% use the following )*L statement& SELECT la!t_name, ;o<_id, commi!!ion_pct ROM emplo+ee! &=ERE commi!!ion_pct IS N#LL"

'

"ntroduction to $racle%i: SQL 5-1=

Logical Conditions
$perator &(, OR /eaning eturns TR9E if both component conditions are true eturns TR9E if either component condition is true eturns TR9E if the follo!ing condition is false

(OT

5-15

Copyright Oracle Corporation, 2001. All rights reserved.

Logical Conditions + logical condition combines the result of two component conditions to produce a single result based on them or in'erts the result of a single condition" + row is returned only if the o'erall result of the condition is true" Three logical operators are a'ailable in )*L& O AND O OR O NOT +ll the e$amples so far ha'e specified only one condition in the &=ERE clause" You can use se'eral conditions in one &=ERE clause using the AND and OR operators"

"ntroduction to $racle%i: SQL 5-15

2sing the &(, $perator


&(, re?uires )oth conditions to )e true+
SELECT FROM 12ERE &(, employee_id, last_name, $o%_id, salary employees salary ?3 0000 $o%_id L-8E +<M&(<+;

5-1&

Copyright Oracle Corporation, 2001. All rights reserved.

The &(, $perator #n the e$ample% both conditions must be true for any record to be selected" Therefore% only employees who ha'e a Aob title that contains the string M+0 and earn .50%000 or more are selected" +ll character searches are case sensiti'e" 0o rows are returned if M+0 is not in uppercase" ;haracter strings must be enclosed in 8uotation marks" &(, Truth Table The following table shows the results of combining two e$pressions with AND&
AND TRUE FALSE NULL TRUE TJ6? (+L)? 06LL FALSE (+L)? (+L)? (+L)? NULL 06LL (+L)? 06LL

"nstructor #ote 7emo& ._and0!1l Purpose& To illustrate using the AND operator" "ntroduction to $racle%i: SQL 5-1&

2sing the OR $perator


OR re?uires either condition to )e true+
SELECT FROM 12ERE OR employee_id, last_name, $o%_id, salary employees salary ?3 0000 $o%_id L-8E +<M&(<+;

5-1>

Copyright Oracle Corporation, 2001. All rights reserved.

The OR $perator #n the e$ample% either condition can be true for any record to be selected" Therefore% any employee who has a Aob #7 containing M+0 or earns .50%000 or more is selected" The OR Truth Table The following table shows the results of combining two e$pressions with OR&
OR TRUE FALSE NULL TRUE TJ6? TJ6? TJ6? FALSE TJ6? (+L)? 06LL NULL TJ6? 06LL 06LL

"nstructor #ote 7emo& ._or0!1l Purpose& To illustrate using the OR operator" "ntroduction to $racle%i: SQL 5-1>

2sing the (OT $perator


SELECT last_name, $o%_id FROM employees 12ERE $o%_id (OT -( "+-T_>RO@+, +ST_CLER8+, +S&_RE>+#;

5-1@

Copyright Oracle Corporation, 2001. All rights reserved.

The (OT $perator The slide e$ample displays the last name and Aob #7 of all employees whose Aob #7 is not #TKPJ3R% )TK;L?J=% or )+KJ?P" The (OT Truth Table The following table shows the result of applying the NOT operator to a condition&
NOT TRUE (+L)? FALSE TJ6? NULL 06LL

Note: The NOT operator can also be used with other )*L operators% such as 5ET&EEN% LI2E% and N#LL" 000 000 000 000 &=ERE &=ERE &=ERE &=ERE ;o<_id NOT IN ,7AC_ACCO#NT7, 7AD_$P7/ !alar+ NOT 5ET&EEN -**** AND -C*** la!t_name NOT LI2E 7MAM7 commi!!ion_pct IS NOT N#LL

"ntroduction to $racle%i: SQL 5-1@

ules of 4recedence

$rder E1aluated 1 5 8 = 5 & > @

$perator Arithmetic operators Concatenation operator Comparison conditions -S /(OT0 (9LL L-8E /(OT0 -( /(OT0 .ET1EE( (OT logical condition &(, logical condition OR logical condition

$1erride rules of precedence )* using parentheses+

5-1%

Copyright Oracle Corporation, 2001. All rights reserved.

ules of 4recedence The rules of precedence determine the order in which e$pressions are e'aluated and calculated" The table lists the default order of precedence" You can o'erride the default order by using parentheses around the e$pressions you want to calculate first"

"ntroduction to $racle%i: SQL 5-1%

ules of 4recedence

SELECT FROM 12ERE OR &(,

last_name, $o%_id, salary employees $o%_id 3 +S&_RE>+ $o%_id 3 +&,_>RES+ salary ? :000;

5-53

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of the 4recedence of the &(, $perator #n the slide e$ample% there are two conditions& S S The first condition is that the Aob #7 is +7KPJ?) and the salary is greater than 55%000" The second condition is that the Aob #7 is )+KJ?P"

Therefore% the SELECT statement reads as follows& >)elect the row if an employee is a president and earns more than .55%000% or if the employee is a sales representati'e"@

"nstructor #ote 7emo& ._!al-0!1l Purpose& To illustrate the rules of precedence" "ntroduction to $racle%i: SQL 5-53

ules of 4recedence
2se parentheses to force priorit*+
SELECT FROM 12ERE OR &(, last_name, $o%_id, salary employees "$o%_id 3 +S&_RE>+ $o%_id 3 +&,_>RES+# salary ? :000;

5-51

Copyright Oracle Corporation, 2001. All rights reserved.

2sing 4arentheses #n the e$ample% there are two conditions& S S The first condition is that the Aob #7 is +7KPJ?) or )+KJ?P" The second condition is that salary is greater than .55%000"

Therefore% the SELECT statement reads as follows& >)elect the row if an employee is a president or a sales representati'e% and if the employee earns more than .55%000"@

"nstructor #ote 7emo& ._!al.0!1l Purpose& To illustrate the rules of precedence" "ntroduction to $racle%i: SQL 5-51

OR,ER .A Clause
Sort ro!s !ith the OR,ER .A clause
ASC: ascending order: default -ESC: descending order

The OR,ER .A clause comes last in the SELECT statement+

SELECT last_name, $o%_id, department_id, 5ire_date FROM employees OR,ER .A 5ire_date ;

'

5-55

Copyright Oracle Corporation, 2001. All rights reserved.

The OR,ER .A Clause The order of rows returned in a 8uery result is undefined" The ORDER 5' clause can be used to sort the rows" #f you use the ORDER 5' clause% it must be the last clause of the )*L statement" You can specify an e$pression% or an alias% or column position as the sort condition" Syntax SELECT ROM P&=ERE PORDER DESCQQ" #n the synta$& ORDER 5' ASC DESC expr table condition(s)Q Rcolumn, exprS

5'

PASC6

specifies the order in which the retrie'ed rows are displayed orders the rows in ascending order this is the default order! orders the rows in descending order

#f the ORDER 5' clause is not used% the sort order is undefined% and the 3racle ser'er may not fetch rows in the same order for the same 8uery twice" 6se the ORDER 5' clause to display the rows in a specific order" "nstructor #ote Let the students know that the ORDER 5' clause is e$ecuted last in 8uery e$ecution" #t is placed last unless the OR #PDATE clause is used" "ntroduction to $racle%i: SQL 5-55

Sorting in -escending $rder


SELECT last_name, $o%_id, department_id, 5ire_date FROM employees OR,ER .A 5ire_date ,ESC ;

'

5-58

Copyright Oracle Corporation, 2001. All rights reserved.

-efault $rdering of -ata The default sort order is ascending& S S S S 0umeric 'alues are displayed with the lowest 'alues first2for e$ample% 5L444" 7ate 'alues are displayed with the earliest 'alue first2for e$ample% 05-D+0-42 before 05-D+0-45" ;haracter 'alues are displayed in alphabetical order2for e$ample% # first and $ last" 0ull 'alues are displayed last for ascending se8uences and first for descending se8uences"

e1ersing the -efault $rder To re'erse the order in which rows are displayed% specify the DESC keyword after the column name in the ORDER 5' clause" The slide e$ample sorts the result by the most recently hired employee"

"nstructor #ote Let the students know that you can also sort by a column number in the SELECT list" The following e$ample sorts the output in the descending order by salary& SELECT ROM ORDER 5' la!t_name, !alar+ emplo+ee! . DESC" "ntroduction to $racle%i: SQL 5-58

Sorting )* Column Alias


SELECT employee_id, last_name, salary* ! annsal FROM employees OR,ER .A annsal;

'

5-5=

Copyright Oracle Corporation, 2001. All rights reserved.

Sorting )* Column Aliases You can use a column alias in the ORDER 5' clause" The slide e$ample sorts the data by annual salary"

"nstructor #ote #nternally% the order of e$ecution for a SELECT statement is as follows& ROM clause &=ERE clause SELECT clause ORDER clause 5' "ntroduction to $racle%i: SQL 5-5=

Sorting )* /ultiple Columns


The order of OR,ER .A list is the order of sort+
SELECT last_name, department_id, salary FROM employees OR,ER .A department_id, salary ,ESC;

'

5-55

Eou can sort )* a column that is not in the SELECT list+


Copyright Oracle Corporation, 2001. All rights reserved.

Sorting )* /ultiple Columns You can sort 8uery results by more than one column" The sort limit is the number of columns in the gi'en table" #n the ORDER 5' clause% specify the columns% and separate the column names using commas" #f you want to re'erse the order of a column% specify DESC after its name" You can also order by columns that are not included in the SELECT clause" Example 7isplay the last names and salaries of all employees" 3rder the result by department number% and then in descending order by salary" SELECT la!t_name, !alar+ ROM emplo+ee! ORDER 5' department_id, !alar+ DESC"

"nstructor #ote )how that the DEPARTMENT_ID column is sorted in ascending order and the SALAR' column in descending order" "ntroduction to $racle%i: SQL 5-55

Summar*
"n this lesson: *ou should ha1e learned ho! to: 2se the 12ERE clause to restrict ro!s of output
2se the comparison conditions 2se the .ET1EE(: -(: L-8E: and (9LL conditions Appl* the logical &(,: OR: and (OT operators

2se the OR,ER .A clause to sort ro!s of output


**B/,-ST-(CT0 column|expression /alias0,777C table condition(s)0 Bcolumn, expr, aliasC /&SC*,ESC00;

SELECT FROM /12ERE /OR,ER .A

5-5&

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* #n this lesson% you should ha'e learned about restricting and sorting rows returned by the SELECT statement" You should also ha'e learned how to implement 'arious operators and conditions"

"ntroduction to $racle%i: SQL 5-5&

4ractice 5 $1er1ie!
This practice co1ers the follo!ing topics:

Selecting data and changing the order of ro!s displa*ed estricting ro!s )* using the 12ERE clause Sorting ro!s )* using the OR,ER .A clause

5-5>

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 5 $1er1ie! This practice gi'es you a 'ariety of e$ercises using the &=ERE clause and the ORDER 5' clause"

"ntroduction to $racle%i: SQL 5-5>

4ractice 5 5" ;reate a 8uery to display the last name and salary of employees earning more than .52%000" Place your )*L statement in a te$t file named la<._-0!1l" Jun your 8uery"

2" ;reate a 8uery to display the employee last name and department number for employee number 5E6"

/" Modify la<._-0!1l to display the last name and salary for all employees whose salary is not in the range of .5%000 and .52%000" Place your )*L statement in a te$t file named la<._)0!1l"

"ntroduction to $racle%i: SQL 5-5@

4ractice 5 6continued7 4" 7isplay the employee last name% Aob #7% and start date of employees hired between (ebruary 20% 544L% and May 5% 544L" 3rder the 8uery in ascending order by start date"

5" 7isplay the last name and department number of all employees in departments 20 and 50 in alphabetical order by name"

6" Modify la<._)0!1l to list the last name and salary of employees who earn between .5%000 and .52%000% and are in department 20 or 50" Label the columns Emplo+ee and Mont9l+ Salar+% respecti'ely" Jesa'e la<._)0!1l as la<._E0!1l" Jun the statement in la<._E0!1l"

"ntroduction to $racle%i: SQL 5-5%

4ractice 5 6continued7 E" 7isplay the last name and hire date of e'ery employee who was hired in 5444"

L" 7isplay the last name and Aob title of all employees who do not ha'e a manager"

4" 7isplay the last name% salary% and commission for all employees who earn commissions" )ort data in descending order of salary and commissions"

#f you ha'e time% complete the following e$ercises& 50" 7isplay the last names of all employees where the third letter of the name is an a.

55" 7isplay the last name of all employees who ha'e an a and an e in their last name"

"ntroduction to $racle%i: SQL 5-83

4ractice 5 6continued7 #f you want an e$tra challenge% complete the following e$ercises& 52" 7isplay the last name% Aob% and salary for all employees whose Aob is sales representati'e or stock clerk and whose salary is not e8ual to .2%500% ./%500% or .E%000"

5/" Modify la<._E0!1l to display the last name% salary% and commission for all employees whose commission amount is 20T" Jesa'e la<._E0!1l as la<._-)0!1l" Jerun the statement in la<._-)0!1l"

"ntroduction to $racle%i: SQL 5-81

"ntroduction to $racle%i: SQL 5-85

Single- o! Functions

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
55 minutes /0 minutes L5 minutes

Topic
Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing:

-escri)e 1arious t*pes of functions a1aila)le in SQL 2se character: num)er: and date functions in SELECT statements -escri)e the use of con1ersion functions

8-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim (unctions make the basic 8uery block more powerful and are used to manipulate data 'alues" This is the first of two lessons that e$plore functions" #t focuses on single-row character% number% and date functions% as well as those functions that con'ert data from one type to another% for e$ample% character data to numeric data"

"ntroduction to $racle%i: SQL 8-5

SQL Functions

"nput arg 1 arg 5

Function Function performs action

$utput

esult 1alue

arg n

8-8

Copyright Oracle Corporation, 2001. All rights reserved.

SQL Functions (unctions are a 'ery powerful feature of )*L and can be used to do the following& S S S S S Perform calculations on data Modify indi'idual data items Manipulate output for groups of rows (ormat dates and numbers for display ;on'ert column data types

)*L functions sometimes take arguments and always return a 'alue" Note: Most of the functions described in this lesson are specific to 3racleGs 'ersion of )*L"

"nstructor #ote This lesson does not discuss all functions in great detail" #t presents the most common functions with a brief e$planation of them" "ntroduction to $racle%i: SQL 8-8

T!o T*pes of SQL Functions

Functions

Single-ro! functions

/ultiple-ro! functions

8-=

Copyright Oracle Corporation, 2001. All rights reserved.

SQL Functions 6continued7 There are two distinct types of functions& S S )ingle-row functions Multiple-row functions

Sin!le-Ro" Functions These functions operate on single rows only and return one result per row" There are different types of single-row functions" This lesson co'ers the following ones& S S S S ;haracter 0umber 7ate ;on'ersion

#ultiple-Ro" Functions (unctions can manipulate groups of rows to gi'e one result per group of rows" These functions are known as group functions" This is co'ered in a later lesson" (or more information% see Oracle9i SQL Reference for the complete list of a'ailable functions and their synta$"

"ntroduction to $racle%i: SQL 8-=

Single- o! Functions
Single ro! functions:

/anipulate data items Accept arguments and return one 1alue Act on each ro! returned eturn one result per ro! /a* modif* the data t*pe Can )e nested Accept arguments !hich can )e a column or an e(pression

function_name /"arg1, arg2,...#0

8-5

Copyright Oracle Corporation, 2001. All rights reserved.

Single- o! Functions )ingle-row functions are used to manipulate data items" They accept one or more arguments and return one 'alue for each row returned by the 8uery" +n argument can be one of the following& S S S S S S S S S 6ser-supplied constant Cariable 'alue ;olumn name ?$pression +cting on each row returned in the 8uery Jeturning one result per row Possibly returning a data 'alue of a different type than that referenced Possibly e$pecting one or more arguments ;an be used in SELECT% &=ERE% and ORDER 5' clauses1 can be nested

(eatures of single-row functions include&

#n the synta$& function_name is the name of the function" arg1, arg2 is any argument to be used by the function" This can be represented by a column name or e$pression"

"ntroduction to $racle%i: SQL 8-5

Single- o! Functions
Character

Ceneral Single-ro! functions

#um)er

Con1ersion

-ate

8-&

Copyright Oracle Corporation, 2001. All rights reserved.

Single- o! Functions 6continued7 This lesson co'ers the following single-row functions& S S S S S ;haracter functions ccept character input and can return both character and number 'alues 0umber functions +ccept numeric input and return numeric 'alues 7ate functions 3perate on 'alues of the DATE data type +ll date functions return a 'alue of DATE data type e$cept the MONT=S_5ET&EEN function% which returns a number"! ;on'ersion functions ;on'ert a 'alue from one data type to another Reneral functions& L N$L L N$L. L N#LLI L COALSECE L CASE L DECODE

"ntroduction to $racle%i: SQL 8-&

Character Functions
Character functions

Case-manipulation functions
LO1ER 9>>ER -(-TC&>

Character-manipulation functions
CO(C&T S9.STR LE(@T2 -(STR L>&, * R>&, TR-M RE>L&CE

8->

Copyright Oracle Corporation, 2001. All rights reserved.

Character Functions )ingle-row character functions accept character data as input and can return both character and numeric 'alues" ;haracter functions can be di'ided into the following& S ;ase-manipulation functions S ;haracter-manipulation functions
$urpose ;on'erts alpha character 'alues to lowercase ;on'erts alpha character 'alues to uppercase ;on'erts alpha character 'alues to uppercase for the first letter of each word% all other letters in lowercase ;oncatenates the first character 'alue to the second character 'alue1 e8ui'alent to concatenation operator UU! Jeturns specified characters from character 'alue starting at character position m, n characters long #f m is negati'e% the count starts from the end of the character 'alue" #f n is omitted% all characters to the end of the string are returned"! Function LO&ER,column|expression/ #PPER,column|expression/ INITCAP,column|expression/ CONCAT,column1|expression1 , column2|expression2/ S#5STR,column|expression,m [,n]/

Note: The functions discussed in this lesson are only some of the a'ailable functions"

"ntroduction to $racle%i: SQL 8->

Character Functions
Character functions

Case-manipulation functions
LO1ER 9>>ER -(-TC&>

Character-manipulation functions
CO(C&T S9.STR LE(@T2 -(STR L>&, * R>&, TR-M RE>L&CE

8-@

Copyright Oracle Corporation, 2001. All rights reserved.

Character Functions 6continued7


Function LENGT=,column|expression/ INSTR,column|expression, string, [,m], [n] / $urpose Jeturns the number of characters in the e$pression Jeturns the numeric position of a named string" 3ptionally% you can pro'ide a position m to start searching% and the occurrence n of the string" m and n default to 5% meaning start the search at the beginning of the search and report the first occurrence" Pads the character 'alue right-Austified to a total width of n character positions Pads the character 'alue left-Austified to a total width of n character positions ?nables you to trim heading or trailing characters or both! from a character string" #f trim_character or trim_source is a character literal% you must enclose it in single 8uotes" This is a feature a'ailable from 3racleLi and later" )earches a te$t e$pression for a character string and% if found% replaces it with a specified replacement string

LPAD,column6expression, n, +string+/ RPAD,column6expression, n, +string+/ TRIM,leading|trailing|both , trim_character !"# trim_source/

REPLACE,text, search_string, replacement_string/

"ntroduction to $racle%i: SQL 8-@

Case /anipulation Functions


These functions con1ert case for character strings+ Function LO1ER"+SDL Co)rse+# 9>>ER"+SDL Co)rse+# esult sEl co)rse SDL CO9RSE

-(-TC&>"+SDL Co)rse+# SEl Co)rse

8-%

Copyright Oracle Corporation, 2001. All rights reserved.

Case /anipulation Functions LO&ER% #PPER% and INITCAP are the three case-con'ersion functions" O LO&ER ;on'erts mi$ed case or uppercase character strings to lowercase O #PPER ;on'erts mi$ed case or lowercase character strings to uppercase O INITCAP ;on'erts the first letter of each word to uppercase and remaining letters to lowercase SELECT TT9e ;o< id Uor T66#PPER,la!t_name/66T i! T 66LO&ER,;o<_id/ AS VEMPLO'EE DETAILSV ROM emplo+ee!"

'

"ntroduction to $racle%i: SQL 8-%

2sing Case /anipulation Functions

-ispla* the emplo*ee num)er: name: and department num)er for emplo*ee Higgins:
SELECT employee_id, last_name, department_id FROM employees 12ERE last_name 3 +5i;;ins+; no roFs selected SELECT employee_id, last_name, department_id FROM employees 12ERE LO1ER"last_name# 3 +5i;;ins+;

8-13

Copyright Oracle Corporation, 2001. All rights reserved.

Case /anipulation Functions 6continued7 The slide e$ample displays the employee number% name% and department number of employee <iggins" The &=ERE clause of the first )*L statement specifies the employee name as 9iggin!" ,ecause all the data in the EMPLO'EES table is stored in proper case% the name 9iggin! does not find a match in the table% and no rows are selected" The &=ERE clause of the second )*L statement specifies that the employee name in the EMPLO'EES table is compared to 9iggin!, con'erting the LAST_NAME column to lowercase for comparison purposes" )ince both names are lowercase now% a match is found and one row is selected" The &=ERE clause can be rewritten in the following manner to produce the same result& 000&=ERE la!t_name : 7=iggin!7 The name in the output appears as it was stored in the database" To display the name capitali9ed% use the #PPER function in the SELECT statement" SELECT emplo+ee_id, #PPER,la!t_name/, department_id ROM emplo+ee! &=ERE INITCAP,la!t_name/ : 7=iggin!7"

"ntroduction to $racle%i: SQL 8-13

Character-/anipulation Functions
These functions manipulate character strings: Function CO(C&T"+2ello+, +1orld+# S9.STR"+2ello1orld+, ,:# LE(@T2"+2ello1orld+# -(STR"+2ello1orld+, +1+# L>&,"salary, 0,+*+# R>&,"salary, 0, +*+# TR-M"+2+ FROM +2ello1orld+# G *****!H000 !H000***** ello1orld esult 2ello1orld 2ello 0

8-11

Copyright Oracle Corporation, 2001. All rights reserved.

Character /anipulation Functions CONCAT% S#5STR% LENGT=% INSTR% LPAD% RPAD% and TRIM are the character manipulation functions co'ered in this lesson" O CONCAT Doins 'alues together You are limited to using two parameters with CONCAT0/ O S#5STR ?$tracts a string of determined length O LENGT= )hows the length of a string as a numeric 'alue O INSTR (inds numeric position of a named character O LPAD Pads the character 'alue right-Austified O RPAD& Pads the character 'alue left-Austified O TRIM& Trims heading or trailing characters or both! from a character string #f trim_character or trim_source is a character literal% you must enclose it in single 8uotes"!

"nstructor #ote ,e sure to point out RPAD to the students% because this function is needed in a practice e$ercise" +lso% TRIM% which was a new function in 3racleLi% does the Aob of both the LTRIM and the RTRIM functions" "ntroduction to $racle%i: SQL 8-11

2sing the Character-/anipulation Functions


1
SELECT employee_id, CO(C&T"=irst_name, last_name# (&ME, $o%_id, 5 LE(@T2 "last_name#, -(STR"last_name, +a+# 'Contains +a+I' FROM employees 8 12ERE S9.STR"$o%_id, H# 3 +RE>+;

8-15

Copyright Oracle Corporation, 2001. All rights reserved.

Character-/anipulation Functions 6continued7 The slide e$ample displays employee first names and last names Aoined together% the length of the employee last name% and the numeric position of the letter a in the employee last name for all employees who ha'e the string REP contained in the Aob #7 starting at the fourth position of the Aob #7" Example Modify the )*L statement on the slide to display the data for those employees whose last names end with an n" SELECT emplo+ee_id, CONCAT,Uir!t_name, la!t_name/ NAME, LENGT= ,la!t_name/, INSTR,la!t_name, 7a7/ VContain! 7a7WV ROM emplo+ee! 12ERE S9.STR"last_name, J , # 3 +n+"

"ntroduction to $racle%i: SQL 8-15

#um)er Functions
RO9(,: ounds 1alue to specified decimal
H:743 H:74! 00

RO9(,"H:74!G, !# TR9(C"H:74!G, !#

TR9(C: Truncates 1alue to specified decimal MO,: eturns remainder of di1ision


MO," G00, 300#

8-18

Copyright Oracle Corporation, 2001. All rights reserved.

#um)er Functions 0umber functions accept numeric input and return numeric 'alues" This section describes some of the number functions" Function $urpose
RO#ND,column6expression, n/ Jounds the column% e$pression% or 'alue to n decimal places% or% if n is omitted% no decimal places" #f n is negati'e% numbers to left of the decimal point are rounded"! Truncates the column% e$pression% or 'alue to n decimal places% or% if n is omitted% then n defaults to 9ero Jeturns the remainder of m di'ided by n

TR#NC,column6expression,n/ MOD,m,n/

Note: This list contains only some of the a'ailable number functions" (or more information% see Oracle9i SQL Reference, >0umber (unctions"@

"ntroduction to $racle%i: SQL 8-18

2sing the RO9(, Function


1 5 8

SELECT RO9(,"H:74!3,!#, RO9(,"H:74!3,0#, RO9(,"H:74!3,J # FROM ,9&L;

,9&L is a dumm* ta)le *ou can use to 1ie! results from functions and calculations+

8-1=

Copyright Oracle Corporation, 2001. All rights reserved.

RO9(, Function The RO#ND function rounds the column% e$pression% or 'alue to n decimal places" #f the second argument is 0 or is missing% the 'alue is rounded to 9ero decimal places" #f the second argument is 2% the 'alue is rounded to two decimal places" ;on'ersely% if the second argument is -2% the 'alue is rounded to two decimal places to the left" The RO#ND function can also be used with date functions" You will see e$amples later in this lesson" The ,9&L Table The D#AL table is owned by the user S'S and can be accessed by all users" #t contains one column% D#MM'% and one row with the 'alue %" The D#AL table is useful when you want to return a 'alue once only% for instance% the 'alue of a constant% pseudocolumn% or e$pression that is not deri'ed from a table with user data" The D#AL table is generally used for SELECT clause synta$ completeness% because both SELECT and ROM clauses are mandatory% and se'eral calculations do not need to select from actual tables"

"ntroduction to $racle%i: SQL 8-1=

2sing the TR9(C Function


1
SELECT FROM

5 8

TR9(C"H:74!3,!#, TR9(C"H:74!3#, TR9(C"H:74!3,J!# ,9&L;

8-15

Copyright Oracle Corporation, 2001. All rights reserved.

TR9(C Function The TR#NC function truncates the column% e$pression% or 'alue to n decimal places" The TR#NC function works with arguments similar to those of the RO#ND function" #f the second argument is 0 or is missing% the 'alue is truncated to 9ero decimal places" #f the second argument is 2% the 'alue is truncated to two decimal places" ;on'ersely% if the second argument is -2% the 'alue is truncated to two decimal places to the left" Like the RO#ND function% the TR#NC function can be used with date functions"

"ntroduction to $racle%i: SQL 8-15

2sing the MO, Function


Calculate the remainder of a salar* after it is di1ided )* 5333 for all emplo*ees !hose Go) title is sales representati1e+
SELECT last_name, salary, MO,"salary, :000# FROM employees 12ERE $o%_id 3 +S&_RE>+;

8-1&

Copyright Oracle Corporation, 2001. All rights reserved.

MO, Function The MOD function finds the remainder of 'alue5 di'ided by 'alue2" The slide e$ample calculates the remainder of the salary after di'iding it by 5%000 for all employees whose Aob #7 is )+KJ?P" Note: The MOD function is often used to determine if a 'alue is odd or e'en"

"nstructor #ote 6for page 8-1>7 You can change the default date display setting for a user session by e$ecuting the command& ALTER SESSION SET NLS_DATE_ ORMAT : 7date format model7" The 7,+ can set the date format for a database to a different format from the default" #n either case% changing these settings is usually not a de'eloperGs role" "ntroduction to $racle%i: SQL 8-1&

Wor;ing !ith -ates


$racle data)ase stores dates in an internal numeric format: centur*: *ear: month: da*: hours: minutes: seconds+ The default date displa* format is ---/$#- +
Allo!s *ou to store 51st centur* dates in the 53th centur* )* specif*ing onl* the last t!o digits of the *ear+ Allo!s *ou to store 53th centur* dates in the 51st centur* in the same !a*+
SELECT last_name, 5ire_date FROM employees 12ERE last_name liKe +@<+;

8-1>

Copyright Oracle Corporation, 2001. All rights reserved.

$racle -ate Format 3racle database stores dates in an internal numeric format% representing the century% year% month% day% hours% minutes% and seconds" The default display and input format for any date is 77-M30-JJ" Calid 3racle dates are between Danuary 5% 4E52 ,";" and 7ecember /5% 4444 +"7" #n the e$ample in the slide% the =IRE_DATE for the employee Riet9 is displayed in the default format 77-M30-JJ" <owe'er% dates are not stored in the database in this format" +ll the components of the date and time are stored" )o% although a =IRE_DATE such as 0E-D60-44 is displayed as day% month% and year% there is also time and century information associated with it" The complete data might be Dune Eth% 5444 5&50&4/ p"m" This data is stored internally as follows& ;?0T6JY Y?+J 54 44 %enturies an& the 'ear ())) The 3racle ser'er is year 2000 compliant" Nhen a record with a date column is inserted into a table% the century information is picked up from the S'SDATE function" <owe'er% when the date column is displayed on the screen% the century component is not displayed by default" The DATE data type always stores year information as a four-digit number internally& two digits for the century and two digits for the year" (or e$ample% the 3racle database stores the year as 5446 or 2005% and not Aust as 46 or 05" "ntroduction to $racle%i: SQL 8-1> M30T< 06 7+Y 0E <36J 5 M#06T? 50 )?;307 4/

Wor;ing !ith -ates


SAS,&TE is a function that returns:

-ate Time

8-1@

Copyright Oracle Corporation, 2001. All rights reserved.

The SAS,&TE Function S'SDATE is a date function that returns the current database ser'er date and time" You can use S'SDATE Aust as you would use any other column name" (or e$ample% you can display the current date by selecting S'SDATE from a table" #t is customary to select S'SDATE from a dummy table called D#AL" Example 7isplay the current date using the D#AL table" SELECT S'SDATE ROM D#AL"

"ntroduction to $racle%i: SQL 8-1@

Arithmetic !ith -ates


Add or su)tract a num)er to or from a date for a resultant date 1alue+ Su)tract t!o dates to find the num)er of da*s )et!een those dates+ Add hours to a date )* di1iding the num)er of hours )* 5=+

8-1%

Copyright Oracle Corporation, 2001. All rights reserved.

Arithmetic !ith -ates )ince the database stores dates as numbers% you can perform calculations using arithmetic operators such as addition and subtraction" You can add and subtract number constants as well as dates" You can perform the following operations& Operation Result
date V number date - number date - date date V numberH24 7ate 7ate 0umber of days 7ate Description +dds a number of days to a date )ubtracts a number of days from a date )ubtracts one date from another +dds a number of hours to a date

"ntroduction to $racle%i: SQL 8-1%

2sing Arithmetic $perators !ith -ates


SELECT last_name, "SAS,&TEJ5ire_date#LM &S 1EE8S FROM employees 12ERE department_id 3 40;

8-53

Copyright Oracle Corporation, 2001. All rights reserved.

Arithmetic !ith -ates 6continued7 The e$ample on the slide displays the last name and the number of weeks employed for all employees in department 40" #t subtracts the date on which the employee was hired from the current date S'SDATE! and di'ides the result by E to calculate the number of weeks that a worker has been employed" Note: S'SDATE is a )*L function that returns the current date and time" Your results may differ from the e$ample" #f a more current date is subtracted from an older date% the difference is a negati'e number"

"ntroduction to $racle%i: SQL 8-53

-ate Functions
Function MO(T2S_.ET1EE( &,,_MO(T2S (ENT_,&A L&ST_,&A RO9(, TR9(C -escription #um)er of months )et!een t!o dates Add calendar months to date #e(t da* of the date specified Last da* of the month ound date Truncate date

8-51

Copyright Oracle Corporation, 2001. All rights reserved.

-ate Functions 7ate functions operate on 3racle dates" +ll date functions return a 'alue of DATE data type e$cept MONT=S_5ET&EEN% which returns a numeric 'alue" O MONT=S_5ET&EEN,date1, date2/ (inds the number of months between date1 and date2" The result can be positi'e or negati'e" #f date1 is later than date2% the result is positi'e1 if date1 is earlier than date2% the result is negati'e" The noninteger part of the result represents a portion of the month" O ADD_MONT=S,date, n/ +dds n number of calendar months to date" The 'alue of n must be an integer and can be negati'e" O NE%T_DA',date, TcharT/ (inds the date of the ne$t specified day of the week ,TcharT/ following date" The 'alue of char may be a number representing a day or a character string" O LAST_DA',date/ (inds the date of the last day of the month that contains date" O RO#ND,dateP,TfmtTQ/ Jeturns date rounded to the unit specified by the format model fmt. #f the format model fmt is omitted% date is rounded to the nearest day" O TR#NC,dateP, TfmtTQ/ Jeturns date with the time portion of the day truncated to the unit specified by the format model fmt" #f the format model fmt is omitted% date is truncated to the nearest day" This list is a subset of the a'ailable date functions" The format models are co'ered later in this lesson" ?$amples of format models are month and year" "ntroduction to $racle%i: SQL 8-51

2sing -ate Functions


O MO(T2S_.ET1EE( "+0 JSE>J4:+,+ JO&(J4H+# 47GMMH 4H O &,,_MO(T2S "+ JO&(J4H+,G# + JO9LJ4H+

O (ENT_,&A "+0 JSE>J4:+,+FR-,&A+# +0PJSE>J4:+ O L&ST_,&A"+0 JFE.J4:+# +!PJFE.J4:+

8-55

Copyright Oracle Corporation, 2001. All rights reserved.

-ate Functions 6continued7 (or e$ample% display the employee number% hire date% number of months employed% si$-month re'iew date% first (riday after hire date% and last day of the hire month for all employees employed for fewer than /6 months" SELECT emplo+ee_id, 9ire_date, MONT=S_5ET&EEN ,S'SDATE, 9ire_date/ TEN#RE, ADD_MONT=S ,9ire_date, E/ RE$IE&, NE%T_DA' ,9ire_date, 7 RIDA'7/, LAST_DA',9ire_date/ ROM emplo+ee! &=ERE MONT=S_5ET&EEN ,S'SDATE, 9ire_date/ J )E"

"ntroduction to $racle%i: SQL 8-55

2sing -ate Functions


Assume SAS,&TE 3 +!:JO9LJ4:+: O RO9(,"SAS,&TE,+MO(T2+# O RO9(,"SAS,&TE ,+AE&R+# O TR9(C"SAS,&TE ,+MO(T2+# O TR9(C"SAS,&TE ,+AE&R+# 0 J&9@J4: 0 JO&(J4G 0 JO9LJ4: 0 JO&(J4:

8-58

Copyright Oracle Corporation, 2001. All rights reserved.

-ate Functions 6continued7 The RO#ND and TR#NC functions can be used for number and date 'alues" Nhen used with dates% these functions round or truncate to the specified format model" Therefore% you can round dates to the nearest year or month" Example ;ompare the hire dates for all employees who started in 544E" 7isplay the employee number% hire date% and start month using the RO#ND and TR#NC functions" SELECT emplo+ee_id, 9ire_date, RO#ND,9ire_date, 7MONT=7/, TR#NC,9ire_date, 7MONT=7/ ROM emplo+ee! &=ERE 9ire_date LI2E 7MB?7"

"nstructor #ote #f the format model is month% dates 5-55 result in the first day of the current month" 7ates 56-/5 result in the first day of the ne$t month" #f the format model is year% months 5-6 result with Danuary 5st of the current year" Months E-52 result in Danuary 5st of the ne$t year" This is a good point to break the lesson in half" <a'e the students do Practice / - Part 5 5-5! now" "ntroduction to $racle%i: SQL 8-58

4ractice 8: 4art $ne: $1er1ie!


This practice co1ers the follo!ing topics: Writing a ?uer* that displa*s the current date

Creating ?ueries that re?uire the use of numeric: character: and date functions 4erforming calculations of *ears and months of ser1ice for an emplo*ee

8-5=

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 8: 4art $ne: $1er1ie! This practice is designed to gi'e you a 'ariety of e$ercises using different functions a'ailable for character% number% and date data types" ;omplete 8uestions 5-5 at the end of this lesson"

"ntroduction to $racle%i: SQL 8-5=

Con1ersion Functions

-ata t*pe con1ersion

"mplicit data t*pe con1ersion

E(plicit data t*pe con1ersion

8-55

Copyright Oracle Corporation, 2001. All rights reserved.

Con1ersion Functions #n addition to 3racle data types% columns of tables in an 3racle4i database can be defined using +0)#% 7,2% and )*LH7) data types" <owe'er% the 3racle ser'er internally con'erts such data types to 3racle data types" #n some cases% 3racle ser'er uses data of one data type where it e$pects data of a different data type" Nhen this happens% 3racle ser'er can automatically con'ert the data to the e$pected data type" This data type con'ersion can be done implicitly by 3racle ser'er% or e%plicitly by the user" #mplicit data type con'ersions work according to the rules e$plained in the ne$t two slides" ?$plicit data type con'ersions are done by using the con'ersion functions" ;on'ersion functions con'ert a 'alue from one data type to another" Renerally% the form of the function names follows the con'ention data t$pe TO data t$pe" The first data type is the input data type1 the last data type is the output" Note: +lthough implicit data type con'ersion is a'ailable% it is recommended that you do e$plicit data type con'ersion to ensure the reliability of your )*L statements"

"ntroduction to $racle%i: SQL 8-55

"mplicit -ata T*pe Con1ersion


For assignments: the $racle ser1er can automaticall* con1ert the follo!ing: From Q&RC2&R! or C2&R Q&RC2&R! or C2&R (9M.ER ,&TE To (9M.ER ,&TE Q&RC2&R! Q&RC2&R!

8-5&

Copyright Oracle Corporation, 2001. All rights reserved.

"mplicit -ata T*pe Con1ersion The assignment succeeds if the 3racle ser'er can con'ert the data type of the 'alue used in the assignment to that of the assignment target"

"nstructor #ote There are se'eral new data types a'ailable in the 3racle4i release pertaining to time" These include& TIMESTAMP% TIMESTAMP &IT= TIME XONE% TIMESTAMP &IT= LOCAL TIME XONE% INTER$AL 'EAR% INTER$AL DA'" These are discussed later in the course" You can also refer students to the Oracle9i SQL Reference, >,asic ?lements of 3racle )*L"@ "ntroduction to $racle%i: SQL 8-5&

"mplicit -ata T*pe Con1ersion


For e(pression e1aluation: the $racle Ser1er can automaticall* con1ert the follo!ing: From Q&RC2&R! or C2&R Q&RC2&R! or C2&R To (9M.ER ,&TE

8-5>

Copyright Oracle Corporation, 2001. All rights reserved.

"mplicit -ata T*pe Con1ersion 6continued7 #n general% the 3racle ser'er uses the rule for e$pressions when a data type con'ersion is needed in places not co'ered by a rule for assignment con'ersions" Note: C=AR to N#M5ER con'ersions succeed only if the character string represents a 'alid number"

"nstructor #ote #mplicit data con'ersion is not solely performed on the data types mentioned" 3ther implicit data con'ersions can also be done" (or e$ample% $ARC=AR. can be implicitly con'erted to RO&ID"

"ntroduction to $racle%i: SQL 8-5>

E(plicit -ata T*pe Con1ersion


TO_(9M.ER TO_,&TE

(9M.ER

CHA ACTE

,&TE

TO_C2&R

TO_C2&R

8-5@

Copyright Oracle Corporation, 2001. All rights reserved.

E(plicit -ata T*pe Con1ersion )*L pro'ides three functions to con'ert a 'alue from one data type to another&
Function TO_C=AR,number6date,P fmtQ, [nlsparamsQ/ $urpose ;on'erts a number or date 'alue to a $ARC=AR. character string with format model fmt" Number %on*ersion: The nl!param! parameter specifies the following characters% which are returned by number format elements& 7ecimal character Rroup separator Local currency symbol #nternational currency symbol #f nl!param! or any other parameter is omitted% this function uses the default parameter 'alues for the session"

"ntroduction to $racle%i: SQL 8-5@

E(plicit -ata T*pe Con1ersion


TO_(9M.ER TO_,&TE

(9M.ER

CHA ACTE

,&TE

TO_C2&R

TO_C2&R

8-5%

Copyright Oracle Corporation, 2001. All rights reserved.

E(plicit -ata T*pe Con1ersion 6continued7 Function $urpose


TO_C=AR,number6date,P fmtQ, PnlsparamsQ/ Date %on*ersion: The nl!param! parameter specifies the language in which month and day names and abbre'iations are returned" #f this parameter is omitted% this function uses the default date languages for the session" ;on'erts a character string containing digits to a number in the format specified by the optional format model fmt" The nl!param! parameter has the same purpose in this function as in the TO_C=AR function for number con'ersion" TO_DATE,char,PfmtQ,PnlsparamsQ/ ;on'erts a character string representing a date to a date 'alue according to the fmt specified" #f fmt is omitted% the format is 77-M30-YY" The nl!param! parameter has the same purpose in this function as in the TO_C=AR function for date con'ersion"

TO_N#M5ER,char,[fmt], [nlsparams]/

"ntroduction to $racle%i: SQL 8-5%

E(plicit -ata T*pe Con1ersion 6continued7 Note: The list of functions mentioned in this lesson includes only some of the a'ailable con'ersion functions" (or more information% see Oracle9i SQL Reference, >;on'ersion (unctions"@

"ntroduction to $racle%i: SQL 8-83

2sing the TO_C2&R Function !ith -ates


TO_C2&R"date, +format_model+#

The format model:

/ust )e enclosed in single ?uotation mar;s and is case sensiti1e Can include an* 1alid date format element Has an fm element to remo1e padded )lan;s or suppress leading <eros "s separated from the date 1alue )* a comma

8-81

Copyright Oracle Corporation, 2001. All rights reserved.

-ispla*ing a -ate in a Specific Format Pre'iously% all 3racle date 'alues were displayed in the 77-M30-YY format" You can use the TO_C=AR function to con'ert a date from this default format to one specified by you" +ui&elines S S S S S The format model must be enclosed in single 8uotation marks and is case sensiti'e" The format model can include any 'alid date format element" ,e sure to separate the date 'alue from the format model by a comma" The names of days and months in the output are automatically padded with blanks" To remo'e padded blanks or to suppress leading 9eros% use the fill mode fm element" You can format the resulting character field with the i)*LBPlus COL#MN command co'ered in a later lesson" SELECT emplo+ee_id, TO_C=AR,9ire_date, 7MMY''7/ Mont9_=ired ROM emplo+ee! &=ERE la!t_name : 7=iggin!7"

"ntroduction to $racle%i: SQL 8-81

Elements of the -ate Format /odel


EEEE EEA // /$#TH /$# -E -AE -8-85

Full *ear in num)ers Eear spelled out T!o-digit 1alue for month Full name of the month Three-letter a))re1iation of the month Three-letter a))re1iation of the da* of the !ee; Full name of the da* of the !ee; #umeric da* of the month
Copyright Oracle Corporation, 2001. All rights reserved.

"ntroduction to $racle%i: SQL 8-85

Sample Format Elements of 9alid -ate Formats


Element );; or ;; Years in dates YYYY or )YYYY YYY or YY or Y Y%YYY #YYY% #YY% #Y% # )Y?+J or Y?+J ,; or +7 ,";" or +"7" * MM M30T< M30 JM NN or N 777 or 77 or 7 7+Y 7Y D Description ;entury1 ser'er prefi$es ,";" date with Year1 ser'er prefi$es ,";" date with Last three% two% or one digits of year Year with comma in this position (our% three% two% or one digit year based on the #)3 standard Year spelled out1 ser'er prefi$es ,";" date with ,";"H"7" indicator ,";"H+"7" indicator with periods *uarter of year Month& two-digit 'alue 0ame of month padded with blanks to length of nine characters 0ame of month% three-letter abbre'iation Joman numeral month Neek of year or month 7ay of year% month% or week 0ame of day padded with blanks to a length of nine characters 0ame of day1 three-letter abbre'iation Dulian day1 the number of days since /5 7ecember 4E5/ ,";"

"nstructor #ote ?mphasi9e the format D% as the students need it for practice 50" The D format returns a 'alue from 5 to E representing the day of the week" 7epending on the 0L) date setting options% the 'alue 5 may represent )unday or Monday" #n the 6nited )tates% the 'alue 5 represents )unday"

"ntroduction to $racle%i: SQL 8-88

Elements of the -ate Format /odel Time elements format the time portion of the date+
22!HRM-RSS &M ?uotation mar;s+ ,, 'o=' MO(T2 ddspt5 ! o= OCTO.ER =o)rteent5 :RH:R3! >M

Add character strings )* enclosing them in dou)le #um)er suffi(es spell out num)ers+

8-8=

Copyright Oracle Corporation, 2001. All rights reserved.

-ate Format Elements - Time Formats 6se the formats listed in the following tables to display time information and literals and to change numerals to spelled numbers" Element Description
+M or PM +"M" or P"M" << or <<52 or <<24 M# )) ))))) Meridian indicator Meridian indicator with periods <our of day% or hour 5L52!% or hour 0L2/! Minute 0L54! )econd 0L54! )econds past midnight 0LL6/44!

"ntroduction to $racle%i: SQL 8-8=

$ther Formats
Element H " % >of the@ Description Punctuation is reproduced in the result *uoted string is reproduced in the result

Specif*ing Suffi(es to "nfluence #um)er -ispla*


Element T< )P )PT< or T<)P Description 3rdinal number for e$ample% 77T< for 4T<! )pelled-out number for e$ample% 77)P for (36J! )pelled-out ordinal numbers for e$ample% 77)PT< for (36JT<!

"ntroduction to $racle%i: SQL 8-85

2sing the TO_C2&R Function !ith -ates


SELECT last_name, TO_C2&R"5ire_date, +=m,, Mont5 AAAA+# &S 2-RE,&TE FROM employees;

'

8-8&

Copyright Oracle Corporation, 2001. All rights reserved.

The TO_C2&R Function !ith -ates The )*L statement on the slide displays the last names and hire dates for all the employees" The hire date appears as 5E Dune 54LE" Example Modify the slide e$ample to display the dates in a format that appears as )e'enth of Dune 5444 52&00&00 +M" SELECT la!t_name, TO_C=AR,9ire_date, 7UmDd!pt9 VoUV Mont9 '''' Um==8MI8SS AM7/ =IREDATE ROM emplo+ee!"

'
0otice that the month follows the format model specified& in other words% the first letter is capitali9ed and the rest are lowercase" "ntroduction to $racle%i: SQL 8-8&

2sing the TO_C2&R Function !ith #um)ers


TO_C2&R"number, +format_model+#

These are some of the format elements *ou can use !ith the TO_C2&R function to displa* a num)er 1alue as a character: % 3 I L + :
8-8>

epresents a num)er Forces a <ero to )e displa*ed 4laces a floating dollar sign 2ses the floating local currenc* s*m)ol 4rints a decimal point 4rints a thousand indicator
Copyright Oracle Corporation, 2001. All rights reserved.

The TO_C2&R Function !ith #um)ers Nhen working with number 'alues such as character strings% you should con'ert those numbers to the character data type using the TO_C=AR function% which translates a 'alue of N#M5ER data type to $ARC=AR. data type" This techni8ue is especially useful with concatenation" #um)er Format Elements #f you are con'erting a number to the character data type% you can use the following format elements&
Element 4 0 . L " % M# PJ ???? C , Description 0umeric position number of 4s determine display width! 7isplay leading 9eros (loating dollar sign (loating local currency symbol 7ecimal point in position specified ;omma in position specified Minus signs to right negati'e 'alues! Parenthesi9e negati'e numbers )cientific notation format must specify four ?s! Multiply by 50 n times n Q number of 4s after C! 7isplay 9ero 'alues as blank% not 0 Example 444444 044444 .444444 L444444 444444"44 444%444 444444M# 444444PJ 44"444???? 4444C44 ,4444"44 Result 52/4 0052/4 .52/4 ((52/4 52/4"00 5%2/4 52/4W52/4X 5"2/4?V0/ 52/400 52/4"00

"ntroduction to $racle%i: SQL 8-8>

2sing the TO_C2&R Function !ith #um)ers

SELECT TO_C2&R"salary, +S44,444700+# S&L&RA FROM employees 12ERE last_name 3 +Ernst+;

8-8@

Copyright Oracle Corporation, 2001. All rights reserved.

Cuidelines S S The 3racle ser'er displays a string of hash signs Y! in place of a whole number whose digits e$ceed the number of digits pro'ided in the format model" The 3racle ser'er rounds the stored decimal 'alue to the number of decimal spaces pro'ided in the format model"

"nstructor #ote 6for page 8-8%7 You can demonstrate the code using the U> modifier in the file )_)Bn" Jun the file with the U> modifier present% then remo'e the U> modifier and run the statement again" "ntroduction to $racle%i: SQL 8-8@

2sing the TO_(9M.ER and TO_,&TE Functions


Con1ert a character string to a num)er format using the TO_(9M.ER function:
TO_(9M.ER"char/, +format_model+0#

Con1ert a character string to a date format using the TO_,&TE function:


TO_,&TE"char/, +format_model+0#

These functions ha1e an =T modifier+ This modifier specifies the e(act matching for the character argument and date format model of a TO_,&TE function
Copyright Oracle Corporation, 2001. All rights reserved.

8-8%

The TO_(9M.ER and TO_,&TE Functions You may want to con'ert a character string to either a number or a date" To accomplish this task% use the TO_N#M5ER or TO_DATE functions" The format model you choose is based on the pre'iously demonstrated format elements" The >U>@ modifier specifies e$act matching for the character argument and date format model of a TO_DATE function& S Punctuation and 8uoted te$t in the character argument must e$actly match e$cept for case! the corresponding parts of the format model" S The character argument cannot ha'e e$tra blanks" Nithout U>% 3racle ignores e$tra blanks" S 0umeric data in the character argument must ha'e the same number of digits as the corresponding element in the format model" Nithout U>% numbers in the character argument can omit leading 9eroes"

"ntroduction to $racle%i: SQL 8-8%

The TO_(9M.ER and TO_,&TE Functions 6continued7 E(ample 7isplay the names and hire dates of all the employees who Aoined on May 24% 5444" ,ecause the U> modifier is used% an e$act match is re8uired and the spaces after the word OMayG are not recogni9ed" SELECT la!t_name, 9ire_date ROM emplo+ee! &=ERE 9ire_date : TO_DATE,7Ma+ .Z, -BBB7, 7U>Mont9 DD, ''''7/"

"ntroduction to $racle%i: SQL 8-=3

-ate Format
Current Eear 1%%5 1%%5 5331 5331 Specified -ate 5>-$CT-%5 5>-$CT-1> 5>-$CT-1> 5>-$CT-%5 Format 1%%5 531> 531> 1%%5 EE Format 1%%5 1%1> 531> 53%5

"f the specified t!o-digit *ear is:


3J=% "f t!o digits of the current *ear are: 3J=% The return date is in the current centur* 53J%% The return date is in the centur* )efore the current one The return date is in the current centur*

The return date is in 53J%% the centur* after the current one

8-=1

Copyright Oracle Corporation, 2001. All rights reserved.

The

-ate Format Element

The JJ date format is similar to the YY element% but you can use it to specify different centuries" You can use the JJ date format element instead of YY% so that the century of the return 'alue 'aries according to the specified two-digit year and the last two digits of the current year" The table on the slide summari9es the beha'ior of the JJ element"
%urrent 'ear 5444 5444 2005 +i*en Date 2E-3;T-45 2E-3;T-5E 2E-3;T-5E ,nterprete& -RR. 5445 205E 205E ,nterprete& -''. 5445 545E 205E

"nstructor #ote JJ is a'ailable in 3racleE% not 3racle 'ersion 6" 0L) parameters can be added to the init0ora file to set default date formats and language names and abbre'iations" (or more information% see Oracle9i SQL Reference, >ALTER SESSION@" 7emo& )_9ire0!1l Purpose& To illustrate date format model elements" "ntroduction to $racle%i: SQL 8-=1

E(ample of RR -ate Format


To find emplo*ees hired prior to 1%%3: use the RR format: !hich produces the same results !hether the command is run in 1%%% or no!:
SELECT last_name, TO_C2&R"5ire_date, +,,JMonJAAAA+# FROM employees 12ERE 5ire_date 6 TO_,&TE"+0 JOanJ40+, +,,JMonJRR+#;

8-=5

Copyright Oracle Corporation, 2001. All rights reserved.

The

-ate Format Element E(ample

To find employees who were hired prior to 5440% the JJ format can be used" )ince the year is now greater than 5444% the JJ format interprets the year portion of the date from 5450 to 5444" The following command% on the other hand% results in no rows being selected because the YY format interprets the year portion of the date in the current century 2040!" SELECT la!t_name, TO_C=AR,9ire_date, 7DDAMonA++++7/ ROM emplo+ee! &=ERE TO_DATE,9ire_date, 7DDAMonA++7/ J 7*-A4anA-BB*7" no roI! !elected

"ntroduction to $racle%i: SQL 8-=5

#esting Functions
Single-ro! functions can )e nested to an* le1el+ #ested functions are e1aluated from deepest le1el to the least deep le1el+

F3"F!"F "col,ar; #,ar;!#,ar;3#


Step 1 A Step 5 A Step 8 A esult 1 esult 5 esult 8

8-=8

Copyright Oracle Corporation, 2001. All rights reserved.

#esting Functions )ingle-row functions can be nested to any depth" 0ested functions are e'aluated from the innermost le'el to the outermost le'el" )ome e$amples follow to show you the fle$ibility of these functions"

"ntroduction to $racle%i: SQL 8-=8

#esting Functions

SELECT last_name, (QL"TO_C2&R"mana;er_id#, +(o Mana;er+# FROM employees 12ERE mana;er_id -S (9LL;

8-==

Copyright Oracle Corporation, 2001. All rights reserved.

#esting Functions 6continued7 The slide e$ample displays the head of the company% who has no manager" The e'aluation of the )*L statement in'ol'es two steps& 5" ?'aluate the inner function to con'ert a number 'alue to a character string" L Re!3lt- : TO_C=AR,manager_id/ 2" ?'aluate the outer function to replace the null 'alue with a te$t string" L N$L,Re!3lt-, 7No Manager7/ The entire e$pression becomes the column heading because no column alias was gi'en" Example 7isplay the date of the ne$t (riday that is si$ months from the hire date" The resulting date should appear as (riday% +ugust 5/th% 5444" 3rder the results by hire date" SELECT TO_C=AR,NE%T_DA',ADD_MONT=S ,9ire_date, E/, T RIDA'T/, TUmDa+, Mont9 DDt9, ''''T/ VNe>t E Mont9 ReKieIV ROM emplo+ee! ORDER 5' 9ire_date" "nstructor #ote 7emo& )_ne!t0!1l Purpose& To illustrate nesting of se'eral single row functions "ntroduction to $racle%i: SQL 8-==

Ceneral Functions
These functions !or; !ith an* data t*pe and pertain to using nulls+ (QL "eTpr , eTpr!#

(QL! "eTpr , eTpr!, eTpr3# (9LL-F "eTpr , eTpr!# CO&LESCE "eTpr , eTpr!, 777, eTprn#

8-=5

Copyright Oracle Corporation, 2001. All rights reserved.

Ceneral Functions These functions work with any data type and pertain to the use of null 'alues in the e$pression list"
Function N$L N$L. N#LLI COALESCE Description ;on'erts a null 'alue to an actual 'alue #f e>pr- is not null% N$L. returns e>pr." #f e>pr- is null% N$L. returns e>pr)" The argument e>pr-can ha'e any data type" ;ompares two e$pressions and returns null if they are e8ual% or the first e$pression if they are not e8ual Jeturns the first non-null e$pression in the e$pression list

Note: (or more information on the hundreds of functions a'ailable% see Oracle9i SQL Reference, >(unctions"@

"ntroduction to $racle%i: SQL 8-=5

(QL Function
Con1erts a null to an actual 1alue+

-ata t*pes that can )e used are date: character: and num)er+ -ata t*pes must match:
L (QL"commission_pct,0# L (QL"5ire_date,+0 JO&(J4M+# L (QL"$o%_id,+(o Oo% Aet+#

8-=&

Copyright Oracle Corporation, 2001. All rights reserved.

The (QL Function To con'ert a null 'alue to an actual 'alue% use the N$L function" Syntax N$L ,expr1, expr2/ #n the synta$& expr1 expr2 is the source 'alue or e$pression that may contain a null is the target 'alue for con'erting the null

You can use the N$L function to con'ert any data type% but the return 'alue is always the same as the data type of expr1" (QL %on*ersions /or 0arious Data Types Data Type %on*ersion Example
N#M5ER DATE C=AR or $ARC=AR. N$L,number_column,B/ N$L,date_column, 7*-A4ANABC7/ N$L,character_column, 7#naKaila<le7/

"ntroduction to $racle%i: SQL 8-=&

2sing the (QL Function


1 SELECT last_name, salary, (QL"commission_pct, 0#, "salary* !# + "salary* !*(QL"commission_pct, 0## &(_S&L FROM employees;

' 1
8-=> Copyright Oracle Corporation, 2001. All rights reserved.

The (QL Function To calculate the annual compensation of all employees% you need to multiply the monthly salary by 52 and then add the commission percentage to it" SELECT la!t_name, !alar+, commi!!ion_pct, ,!alar+*-./ ( ,!alar+*-.*commi!!ion_pct/ AN_SAL ROM emplo+ee!"

' '
0otice that the annual compensation is calculated only for those employees who earn a commission" #f any column 'alue in an e$pression is null% the result is null" To calculate 'alues for all employees% you must con'ert the null 'alue to a number before applying the arithmetic operator" #n the e$ample on the slide% the N$L function is used to con'ert null 'alues to 9ero" "ntroduction to $racle%i: SQL 8-=>

2sing the (QL! Function


1 SELECT last_name, salary, commission_pct, (QL!"commission_pct, 5 +S&L+COMM+, +S&L+# income FROM employees 12ERE department_id -( ":0, P0#;

1
8-=@ Copyright Oracle Corporation, 2001. All rights reserved.

The (QL! Function The N$L. function e$amines the first e$pression" #f the first e$pression is not null% then the N$L. function returns the second e$pression" #f the first e$pression is null% then the third e$pression is returned" Syntax N$L,expr1, expr2, expr%/ #n the synta$& expr1 expr2 expr% is the source 'alue or e$pression that may contain null is the 'alue returned if expr1 is not null is the 'alue returned if expr2 is null

#n the e$ample shown% the COMMISSION_PCT column is e$amined" #f a 'alue is detected% the second e$pression of SAL(COMM is returned" #f the COMMISSION_PCT column holds a null 'alues% the third e$pression of SAL is returned" The argument expr1 can ha'e any data type" The arguments expr2 and expr% can ha'e any data types e$cept LONG" #f the data types of expr2 and expr% are different% The 3racle ser'er con'erts expr% to the data type of expr2 before comparing them unless expr% is a null constant" #n that case% a data type con'ersion is not necessary" The data type of the return 'alue is always the same as the data type of expr2% unless expr2 is character data% in which case the return 'alueGs data type is $ARC=AR." "ntroduction to $racle%i: SQL 8-=@

2sing the (9LL-F Function


1
SELECT =irst_name, LE(@T2"=irst_name# 'eTpr ', 5 last_name, LE(@T2"last_name# 'eTpr!', (9LL-F"LE(@T2"=irst_name#, LE(@T2"last_name## res)lt FROM employees;

' 1
8-=%

Copyright Oracle Corporation, 2001. All rights reserved.

The (9LL-F Function The N#LLI function compares two e$pressions" #f they are e8ual% the function returns null" #f they are not e8ual% the function returns the first e$pression" You cannot specify the literal 06LL for first e$pression" Syntax N#LLI #n the synta$& expr1 expr2 ,expr1, expr2/ is the source 'alue compared to expr2

is the source 'alue compared with expr1" #f it is not e8ual to expr1% expr1 is returned"! #n the e$ample shown% the Aob #7 in the EMPLO'EES table is compared to the Aob #7 in the 4O5_=ISTOR' table for any employee who is in both tables" The output shows the employeeGs current Aob" #f the employee is listed more than once% that means the employee has held at least two Aobs pre'iously" Note: The N#LLI function is logically e8ui'alent to the following CASE e$pression" The CASE e$pression is discussed in a subse8uent page& CASE &=EN e>pr- : e>pr . T=EN N#LL ELSE e>pr- END

"ntroduction to $racle%i: SQL 8-=%

2sing the CO&LESCE Function


The ad1antage of the CO&LESCE function o1er the (QL function is that the CO&LESCE function can ta;e multiple alternate 1alues+ "f the first e(pression is not null: it returns that e(pressionK other!ise: it does a CO&LESCE of the remaining e(pressions+

8-53

Copyright Oracle Corporation, 2001. All rights reserved.

The CO&LESCE Function The COALESCE function returns the first non-null e$pression in the list" Syntax COALESCE ,expr1, expr2, &&& exprn/ #n the synta$& expr1 expr2 exprn returns this e$pression if it is not null returns this e$pression if the first e$pression is null and this e$pression is not null returns this e$pression if the preceding e$pressions are null

"ntroduction to $racle%i: SQL 8-53

2sing the CO&LESCE Function


SELECT last_name, CO&LESCE"commission_pct, salary, FROM employees OR,ER .A commission_pct;

0# comm

'

8-51

Copyright Oracle Corporation, 2001. All rights reserved.

The CO&LESCE Function #n the e$ample shown% if the COMMISSION_PCT 'alue is not null% it is shown" #f the COMMISSION_PCT 'alue is null% then the SALAR' is shown" #f the COMMISSION_PCT and SALAR' 'alues are null% then the 'alue 50 is shown"

"ntroduction to $racle%i: SQL 8-51

Conditional E(pressions
4ro1ide the use of "F-THE#-ELSE logic !ithin a SQL statement 2se t!o methods:
L C&SE e(pression L ,ECO,E function

8-55

Copyright Oracle Corporation, 2001. All rights reserved.

Conditional E(pressions Two methods used to implement conditional processing #(-T<?0-?L)? logic! within a )*L statement are the CASE e$pression and the DECODE function" Note: The CASE e$pression is new in the 3racle4i )er'er release" The CASE e$pression complies with +0)# )*L1 DECODE is specific to 3racle synta$"

"ntroduction to $racle%i: SQL 8-55

The C&SE E(pression


Facilitates conditional in?uiries )* doing the !or; of an "F-THE#-ELSE statement:
C&SE expr 12E( /12E( 12E( ELSE E(, comparison_expr1 T2E( return_expr1 comparison_expr2 T2E( return_expr2 comparison_exprn T2E( return_exprn else_expr0

8-58

Copyright Oracle Corporation, 2001. All rights reserved.

The C&SE E(pression CASE e$pressions let you use #(-T<?0-?L)? logic in )*L statements without ha'ing to in'oke procedures" #n a simple CASE e$pression% 3racle searches for the first &=EN 000 T=EN pair for which e>pr is e8ual to compari!on_e>pr and returns ret3rn_e>pr" #f none of the &=EN 000 T=EN pairs meet this condition% and an ELSE clause e$ists% then 3racle returns el!e_e>pr" 3therwise% 3racle returns null" You cannot specify the literal 06LL for all the ret3rn_e>prs and the el!e_e>pr" +ll of the e$pressions e>pr% compari!on_e>pr% and ret3rn_e>pr! must be of the same data type% which can be C=AR% $ARC=AR.% NC=AR% or N$ARC=AR."

"nstructor #ote There is also a searched CASE e$pression" 3racle searches from left to right until it finds an occurrence of a condition that is true% and then returns ret3rn_e>pr" #f no condition is found to be true% and an ELSE clause e$ists% 3racle returns el!e_e>pr" 3therwise 3racle returns null" (or more information% see Oracle9i SQL Reference% >?$pressions"@ "ntroduction to $racle%i: SQL 8-58

2sing the C&SE E(pression


Facilitates conditional in?uiries )* doing the !or; of an "F-THE#-ELSE statement:
SELECT last_name, $o%_id, salary, C&SE $o%_id 12E( +-T_>RO@+ T2E( 7 0*salary 12E( +ST_CLER8+ T2E( 7 :*salary 12E( +S&_RE>+ T2E( 7!0*salary ELSE salary E(, 'REQ-SE,_S&L&RA' FROM employees;

' '

8-5=

Copyright Oracle Corporation, 2001. All rights reserved.

2sing the C&SE E(pression #n the preceding )*L statement% the 'alue of 4O5_ID is decoded" #f 4O5_ID is IT_PROG% the salary increase is 50T1 if 4O5_ID is ST_CLER2% the salary increase is 55T1 if 4O5_ID is SA_REP% the salary increase is 20T" (or all other Aob roles% there is no increase in salary" The same statement can be written with the DECODE function"

"ntroduction to $racle%i: SQL 8-5=

The ,ECO,E Function


Facilitates conditional in?uiries )* doing the !or; of a C&SE or "F-THE#-ELSE statement:
,ECO,E"col|expression, search1, result1 /, search2, result2,...,0 /, default0#

8-55

Copyright Oracle Corporation, 2001. All rights reserved.

The ,ECO,E Function The DECODE function decodes an e$pression in a way similar to the #(-T<?0-?L)? logic used in 'arious languages" The DECODE function decodes expression after comparing it to each search 'alue" #f the e$pression is the same as search% result is returned" #f the default 'alue is omitted% a null 'alue is returned where a search 'alue does not match any of the result 'alues"

"ntroduction to $racle%i: SQL 8-55

2sing the ,ECO,E Function

SELECT last_name, $o%_id, salary, ,ECO,E"$o%_id, +-T_>RO@+, +ST_CLER8+, +S&_RE>+, salary# REQ-SE,_S&L&RA FROM employees;

7 0*salary, 7 :*salary, 7!0*salary,

' '

8-5&

Copyright Oracle Corporation, 2001. All rights reserved.

2sing the ,ECO,E Function #n the preceding )*L statement% the 'alue of 4O5_ID is tested" #f 4O5_ID is IT_PROG% the salary increase is 50T1 if 4O5_ID is ST_CLER2% the salary increase is 55T1 if 4O5_ID is SA_REP% the salary increase is 20T" (or all other Aob roles% there is no increase in salary" The same statement can be e$pressed in pseudocode as an #(-T<?0-?L)? statement& I ;o<_id : I ;o<_id : I ;o<_id : ELSE !alar+ 7IT_PROG7 7ST_CLER27 7SA_REP7 : !alar+ T=EN T=EN T=EN !alar+ : !alar+*-0-* !alar+ : !alar+*-0-C !alar+ : !alar+*-0.*

"ntroduction to $racle%i: SQL 8-5&

2sing the ,ECO,E Function


-ispla* the applica)le ta( rate for each emplo*ee in department @3+
SELECT last_name, salary, ,ECO,E "TR9(C"salaryL!000, 0#, 0, 0700, , 0704, !, 07!0, 3, 0730, H, 07H0, :, 07H!, G, 07HH, 07H:# T&N_R&TE FROM employees 12ERE department_id 3 P0;

8-5>

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample This slide shows another e$ample using the DECODE function" #n this e$ample% we determine the ta$ rate for each employee in department L0 based on the monthly salary" The ta$ rates are as per the 'alues mentioned in the following data" Monthly Salary Range .0"00 - 5444"44 .2%000"00 - /%444"44 .4%000"00 - 5%444"44 .6%000"00 - E%444"44 .L%000"00 - 4%444"44 .50%000"00 - 55%444"44 .52%200"00 - 5/%444"44 .54%000"00 or greater Rate 00T 04T 20T /0T 40T 42T 44T 45T

"ntroduction to $racle%i: SQL 8-5>

Summar*
"n this lesson: *ou should ha1e learned ho! to:

4erform calculations on data using functions /odif* indi1idual data items using functions /anipulate output for groups of ro!s using functions Alter date formats for displa* using functions Con1ert column data t*pes using functions 2se #9L functions 2se "F-THE#-ELSE logic

8-5@

Copyright Oracle Corporation, 2001. All rights reserved.

Single- o! Functions )ingle-row functions can be nested to any le'el" )ingle-row functions can manipulate the following& S ;haracter data& LO&ER% #PPER% INITCAP% CONCAT% S#5STR% INSTR% LENGT= S S S S S S 0umber data& RO#ND% TR#NC% MOD 7ate data& MONT=S_5ET&EEN% ADD_MONT=S% NE%T_DA'% LAST_DA'% RO#ND% TR#NC 7ate 'alues can also use arithmetic operators" ;on'ersion functions can con'ert character% date% and numeric 'alues& TO_C=AR% TO_DATE% TO_N#M5ER There are se'eral functions that pertain to nulls% including N$L% N$L.% N#LLI % and COALESCE" #(-T<?0-?L)? logic can be applied within a )*L statement by using the CASE e$pression or the DECODE function"

SAS,&TE and ,9&L S'SDATE is a date function that returns the current date and time" #t is customary to select S'SDATE from a dummy table called D#AL"

"ntroduction to $racle%i: SQL 8-5@

4ractice 8: 4art T!o: $1er1ie!


This practice co1ers the follo!ing topics:

Creating ?ueries that re?uire the use of numeric: character: and date functions 2sing concatenation !ith functions Writing case-insensiti1e ?ueries to test the usefulness of character functions 4erforming calculations of *ears and months of ser1ice for an emplo*ee -etermining the re1ie! date for an emplo*ee

8-5%

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 8: 4art T!o: $1er1ie! This practice is designed to gi'e you a 'ariety of e$ercises using different functions a'ailable for character% number% and date data types" Jemember that for nested functions% the results are e'aluated from the innermost function to the outermost function"

"nstructor #ote This practice should be done in two parts" Part 5 contains 8uestions 5-5 which co'er the material from pages 5-2/" Part 2 contains 8uestions 6-54 and matches the material for the remainder of the lesson" Practice 8uestion 6& ,e sure to tell the students that their results may differ from the one pro'ided% because S'SDATE is used in the e$ercise" #nstructor hint for practice 8uestion 50& The ORDER 5' clause in the solution sorts on TO_C=AR,9iredateA-, 7d7/" The format element OdG returns a O5G for )unday% O2G for Monday% and so forth" The e$pression 9iredateA- effecti'ely >shifts@ each hiredate to the pre'ious day% so that an employee hired on a Monday appears to ha'e been hired on )unday" The TO_C=AR function returns a O5G for that employee and the result set is sorted beginning with those employees hired on Monday" "ntroduction to $racle%i: SQL 8-5%

4ractice 8 - 4art $ne 6continued7 5" Nrite a 8uery to display the current date" Label the column Date"

2" (or each employee% display the employee number% lastKname% salary% and salary increased by 55T and e$pressed as a whole number" Label the column NeI Salar+" Place your )*L statement in a te$t file named la<)_.0!1l" /" Jun your 8uery in the file la<)_.0!1l0

'

4" Modify your 8uery la<)_.0!1l to add a column that subtracts the old salary from the new salary" Label the column Increa!e" )a'e the contents of the file as la<)_Z0!1l" Jun the re'ised 8uery"

'

"ntroduction to $racle%i: SQL 8-&3

4ractice 8: 4art $ne 6continued7 5" Nrite a 8uery that displays the employeeGs last names with the first letter capitali9ed and all other letters lowercase% and the length of the names% for all employees whose name starts with D% +% or M" Ri'e each column an appropriate label" )ort the results by the employeesG last names"

"ntroduction to $racle%i: SQL 8-&1

4ractice 8 - 4art T!o 6" (or each employee% display the employeeGs last name% and calculate the number of months between today and the date the employee was hired" Label the column MONT=S_&OR2ED" 3rder your results by the number of months employed" Jound the number of months up to the closest whole number" Note: Your results will differ"

"ntroduction to $racle%i: SQL 8-&5

4ractice 8 - 4art T!o 6continued7 E" Nrite a 8uery that produces the following for each employee& Wemplo+ee la!t nameD earn! J!alar+D mont9l+ <3t Iant! J) time! !alar+X" Label the column Dream Salarie!"

'

#f you ha'e time% complete the following e$ercises& L" ;reate a 8uery to display the last name and salary for all employees" (ormat the salary to be 55 characters long% left-padded with ." Label the column SALAR'"

'

"ntroduction to $racle%i: SQL 8-&8

4ractice 8 - 4art T!o 6continued7 4" 7isplay each employeeGs last name% hire date% and salary re'iew date% which is the first Monday after si$ months of ser'ice" Label the column RE$IE&" (ormat the dates to appear in the format similar to >Monday% the Thirty-(irst of Duly% 2000"@

'
50" 7isplay the last name% hire date% and day of the week on which the employee started" Label the column DA'" 3rder the results by the day of the week starting with Monday"

'

"ntroduction to $racle%i: SQL 8-&=

4ractice 8 - 4art T!o 6continued7 #f you want an e$tra challenge% complete the following e$ercises& 55" ;reate a 8uery that displays the employeesG last names and commission amounts" #f an employee does not earn commission% put >0o ;ommission"@ Label the column COMM"

'

52" ;reate a 8uery that displays the employeesG last names and indicates the amounts of their annual salaries with asterisks" ?ach asterisk signifies a thousand dollars" )ort the data in descending order of salary" Label the column EMPLO'EES_AND_T=EIR_SALARIES"

'

"ntroduction to $racle%i: SQL 8-&5

4ractice 8 - 4art T!o 6continued7 5/" 6sing the DECODE function% write a 8uery that displays the grade of all employees based on the 'alue of the column 4O5_ID% as per the following data& Job +7KPJ?) )TKM+0 #TKPJ3R )+KJ?P )TK;L?J= 0one of the abo'e Grade + , ; 7 ? 0

'

54" Jewrite the statement in the preceding 8uestion using the CASE synta$"

"ntroduction to $racle%i: SQL 8-&&

-ispla*ing -ata from /ultiple Ta)les

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
55 minutes 55 minutes 550 minutes

Topic
Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing:

Write SELECT statements to access data from more than one ta)le using e?ualit* and none?ualit* Goins 9ie! data that generall* does not meet a Goin condition )* using outer Goins Loin a ta)le to itself )* using a self Goin

=-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim This lesson co'ers how to obtain data from more than one table"

"ntroduction to $racle%i: SQL =-5

$)taining -ata from /ultiple Ta)les


EM>LOAEES ,E>&RTME(TS

'

'

=-8

Copyright Oracle Corporation, 2001. All rights reserved.

-ata from /ultiple Ta)les )ometimes you need to use data from more than one table" #n the slide e$ample% the report displays data from two separate tables" S S S ?mployee #7s e$ist in the EMPLO'EES table" 7epartment #7s e$ist in both the EMPLO'EES and DEPARTMENTS tables" Location #7s e$ist in the DEPARTMENTS table"

To produce the report% you need to link the EMPLO'EES and DEPARTMENTS tables and access data from both of them"

"ntroduction to $racle%i: SQL =-8

Cartesian 4roducts
A Cartesian product is formed !hen:
A Goin condition is omitted A Goin condition is in1alid All ro!s in the first ta)le are Goined to all ro!s in the second ta)le

To a1oid a Cartesian product: al!a*s include a 1alid Goin condition in a 12ERE clause+

=-=

Copyright Oracle Corporation, 2001. All rights reserved.

Cartesian 4roducts Nhen a Aoin condition is in'alid or omitted completely% the result is a &artesian product, in which all combinations of rows are displayed" +ll rows in the first table are Aoined to all rows in the second table" + ;artesian product tends to generate a large number of rows% and the result is rarely useful" You should always include a 'alid Aoin condition in a &=ERE clause% unless you ha'e a specific need to combine all rows from all tables" ;artesian products are useful for some tests when you need to generate a large number of rows to simulate a reasonable amount of data"

"ntroduction to $racle%i: SQL =-=

Cenerating a Cartesian 4roduct


EM>LOAEES 653 ro!s7 ,E>&RTME(TS 6@ ro!s7

'

Cartesian product: 53(@A1&3 ro!s

'

=-5

Copyright Oracle Corporation, 2001. All rights reserved.

Cartesian 4roducts 6continued7 + ;artesian product is generated if a Aoin condition is omitted" The e$ample on the slide displays employee last name and department name from the EMPLO'EES and DEPARTMENTS tables" ,ecause no &=ERE clause has been specified% all rows 20 rows! from the EMPLO'EES table are Aoined with all rows L rows! in the DEPARTMENTS table% thereby generating 560 rows in the output" SELECT la!t_name, department_name dept_name ROM emplo+ee!, department!"

'
"nstructor #ote 7emo& Z_cart0!1l Purpose& To illustrate e$ecuting a ;artesian product "ntroduction to $racle%i: SQL =-5

T*pes of Loins
$racle 4roprietar* Loins 6@i and prior7: SQL: 1%%% Compliant Loins:

E?uiGoin #on-e?uiGoin $uter Goin Self Goin

Cross Goins #atural Goins 2sing clause Full or t!o sided outer Goins Ar)itrar* Goin conditions for outer Goins

=-&

Copyright Oracle Corporation, 2001. All rights reserved.

T*pes of Loins The 3racle4i database offers Aoin synta$ that is )*L& 5444 compliant" Prior to the 4i release% the Aoin synta$ was different from the +0)# standards" The new )*L& 5444 compliant Aoin synta$ does not offer any performance benefits o'er the 3racle proprietary Aoin synta$ that e$isted in prior releases"

"nstructor #ote 7o not get into details of all the types of Aoins now" ?$plain each Aoin one by one% as is done in the following slides" "ntroduction to $racle%i: SQL =-&

Loining Ta)les 2sing $racle S*nta(


2se a Goin to ?uer* data from more than one ta)le+
SELECT FROM 12ERE table1.column, table2.column table1, table2 table1.column1 3 table2.column2;

Write the Goin condition in the 12ERE clause+ 4refi( the column name !ith the ta)le name !hen the same column name appears in more than one ta)le+

=->

Copyright Oracle Corporation, 2001. All rights reserved.

-efining Loins Nhen data from more than one table in the database is re8uired% a 'oin condition is used" Jows in one table can be Aoined to rows in another table according to common 'alues e$isting in corresponding columns% that is% usually primary and foreign key columns" To display data from two or more related tables% write a simple Aoin condition in the &=ERE clause" #n the synta$& table1&column table1&column1 : table2&column2 denotes the table and column from which data is retrie'ed is the condition that Aoins or relates! the tables together

Cuidelines S Nhen writing a SELECT statement that Aoins tables% precede the column name with the table name for clarity and to enhance database access" S S #f the same column name appears in more than one table% the column name must be prefi$ed with the table name"

To Aoin n tables together% you need a minimum of nA- Aoin conditions" (or e$ample% to Aoin four tables% a minimum of three Aoins is re8uired" This rule may not apply if your table has a concatenated primary key% in which case more than one column is re8uired to uni8uely identify each row" (or more information% see Oracle9i SQL Reference, >SELECT"@ "ntroduction to $racle%i: SQL =->

What is an E?uiGoinM
EM>LOAEES ,E>&RTME(TS

'

'

Foreign ;e*
=-@

4rimar* ;e*

Copyright Oracle Corporation, 2001. All rights reserved.

E?uiGoins To determine an employeeGs department name% you compare the 'alue in the DEPARTMENT_ID column in the EMPLO'EES table with the DEPARTMENT_ID 'alues in the DEPARTMENTS table" The relationship between the EMPLO'EES and DEPARTMENTS tables is an equi'oin2that is% 'alues in the DEPARTMENT_ID column on both tables must be e8ual" (re8uently% this type of Aoin in'ol'es primary and foreign key complements" Note: ?8uiAoins are also called simple 'oins or inner 'oins" "nstructor #ote ?$plain the use of a decision matri$ for simplifying writing Aoins" (or e$ample% if you want to display the name and department number of all the employees who are in the same department as Royal% you can start by making the following decision tree& Columns to Display la!t_name department_name Originating Table emplo+ee! department! Condition la!t_name:7Go+al7 emplo+ee!0department_id : department!0department_id

0ow the )*L statement can be easily formulated by looking at the decision matri$" The first column gi'es the column list in the SELECT statement% the second column gi'es the tables for the ROM clause% and the third column gi'es the condition for the &=ERE clause" "ntroduction to $racle%i: SQL =-@

etrie1ing ecords !ith E?uiGoins


SELECT employees7employee_id, employees7last_name, employees7department_id, departments7department_id, departments7location_id FROM employees, departments 12ERE employees7department_id 3 departments7department_id;

'

=-%

Copyright Oracle Corporation, 2001. All rights reserved.

etrie1ing ecords !ith E?uiGoins #n the slide e$ample& S The SELECT clause specifies the column names to retrie'e& F employee last name% employee number% and department number% which are columns in the EMPLO'EES table F department number% department name% and location #7% which are columns in the DEPARTMENTS table S The ROM clause specifies the two tables that the database must access& L EMPLO'EES table L DEPARTMENTS table S The &=ERE clause specifies how the tables are to be Aoined& EMPLO'EES0DEPARTMENT_ID : DEPARTMENTS0DEPARTMENT_ID ,ecause the DEPARTMENT_ID column is common to both tables% it must be prefi$ed by the table name to a'oid ambiguity"

"ntroduction to $racle%i: SQL =-%

Additional Search Conditions 2sing the &(, $perator


EM>LOAEES ,E>&RTME(TS

'

'

=-13

Copyright Oracle Corporation, 2001. All rights reserved.

Additional Search Conditions #n addition to the Aoin% you may ha'e criteria for your &=ERE clause to restrict the rows under consideration for one or more tables in the Aoin" (or e$ample% to display employee MatosG department number and department name% you need an additional condition in the &=ERE clause" SELECT la!t_name, emplo+ee!0department_id, department_name ROM emplo+ee!, department! &=ERE emplo+ee!0department_id : department!0department_id AND la!t_name : 7Mato!7"

"ntroduction to $racle%i: SQL =-13

Qualif*ing Am)iguous Column #ames


2se ta)le prefi(es to ?ualif* column names that are in multiple ta)les+ "mpro1e performance )* using ta)le prefi(es+ -istinguish columns that ha1e identical names )ut reside in different ta)les )* using column aliases+

=-11

Copyright Oracle Corporation, 2001. All rights reserved.

Qualif*ing Am)iguous Column #ames You need to 8ualify the names of the columns in the &=ERE clause with the table name to a'oid ambiguity" Nithout the table prefi$es% the DEPARTMENT_ID column could be from either the DEPARTMENTS table or the EMPLO'EES table" #t is necessary to add the table prefi$ to e$ecute your 8uery" #f there are no common column names between the two tables% there is no need to 8ualify the columns" <owe'er% using the table prefi$ impro'es performance% because you tell the 3racle )er'er e$actly where to find the columns" The re8uirement to 8ualify ambiguous column names is also applicable to columns that may be ambiguous in other clauses% such as the SELECT clause or the ORDER 5' clause"

"nstructor #ote 7emo& Z_loc0!1l Purpose& To illustrate a SELECT clause with no aliases" "ntroduction to $racle%i: SQL =-11

2sing Ta)le Aliases


Simplif* ?ueries )* using ta)le aliases+ "mpro1e performance )* using ta)le prefi(es+

SELECT e7employee_id, e7last_name, e7department_id, d7department_id, d7location_id FROM employees e , departments d 12ERE e7department_id 3 d7department_id;

=-15

Copyright Oracle Corporation, 2001. All rights reserved.

Ta)le Aliases *ualifying column names with table names can be 'ery time consuming% particularly if table names are lengthy" You can use table aliases instead of table names" Dust as a column alias gi'es a column another name% a table alias gi'es a table another name" Table aliases help to keep )*L code smaller% therefore using less memory" 0otice how table aliases are identified in the ROM clause in the e$ample" The table name is specified in full% followed by a space and then the table alias" The EMPLO'EES table has been gi'en an alias of e% and the DEPARTMENTS table has an alias of d" Cuidelines S S S S Table aliases can be up to /0 characters in length% but shorter is better" #f a table alias is used for a particular table name in the ROM clause% then that table alias must be substituted for the table name throughout the SELECT statement" Table aliases should be meaningful" The table alias is 'alid only for the current SELECT statement"

"ntroduction to $racle%i: SQL =-15

Loining /ore than T!o Ta)les


EM>LOAEES ,E>&RTME(TS LOC&T-O(S

'

To Goin n ta)les together: *ou need a minimum of n-1 Goin conditions+ For e(ample: to Goin three ta)les: a minimum of t!o Goins is re?uired+
Copyright Oracle Corporation, 2001. All rights reserved.

=-18

Additional Search Conditions )ometimes you may need to Aoin more than two tables" (or e$ample% to display the last name% the department name% and the city for each employee% you ha'e to Aoin the EMPLO'EES% DEPARTMENTS% and LOCATIONS tables" SELECT ROM &=ERE AND e0la!t_name, d0department_name, l0cit+ emplo+ee! e, department! d, location! l e0department_id : d0department_id d0location_id : l0location_id"

'
"ntroduction to $racle%i: SQL =-18

#on-E?uiGoins
EM>LOAEES OO._@R&,ES

'

Salar* in the EM>LOAEES ta)le must )e )et!een lo!est salar* and highest salar* in the OO._@R&,ES ta)le+

=-1=

Copyright Oracle Corporation, 2001. All rights reserved.

#on-E?uiGoins + non-e8uiAoin is a Aoin condition containing something other than an e8uality operator" The relationship between the EMPLO'EES table and the 4O5_GRADES table has an e$ample of a non-e8uiAoin" + relationship between the two tables is that the SALAR' column in the EMPLO'EES table must be between the 'alues in the LO&EST_SALAR' and =IG=EST_SALAR' columns of the 4O5_GRADES table" The relationship is obtained using an operator other than e8uals Q!"

"ntroduction to $racle%i: SQL =-1=

etrie1ing ecords !ith #on-E?uiGoins


SELECT e7last_name, e7salary, $7;rade_leUel FROM employees e, $o%_;rades $ 12ERE e7salary .ET1EE( $7loFest_sal &(, $75i;5est_sal;

'

=-15

Copyright Oracle Corporation, 2001. All rights reserved.

#on-E?uiGoins 6continued7 The slide e$ample creates a non-e8uiAoin to e'aluate an employeeGs salary grade" The salary must be bet een any pair of the low and high salary ranges" #t is important to note that all employees appear e$actly once when this 8uery is e$ecuted" 0o employee is repeated in the list" There are two reasons for this& S 0one of the rows in the Aob grade table contain grades that o'erlap" That is% the salary 'alue for an employee can lie only between the low salary and high salary 'alues of one of the rows in the salary grade table" S +ll of the employeesG salaries lie within the limits pro'ided by the Aob grade table" That is% no employee earns less than the lowest 'alue contained in the LO&EST_SAL column or more than the highest 'alue contained in the =IG=EST_SAL column" Note: 3ther conditions% such as J: and D: can be used% but 5ET&EEN is the simplest" Jemember to specify the low 'alue first and the high 'alue last when using 5ET&EEN" Table aliases ha'e been specified in the slide e$ample for performance reasons% not because of possible ambiguity" "nstructor #ote ?$plain that 5ET&EEN H AND H is actually translated by the 3racle ser'er to a pair of AND conditions a D: loIer limit! and a J: 9ig9er limit! and IN , H / is translated by the 3racle ser'er to a set of OR conditions a : Kal3e- OR a : Kal3e. OR a : Kal3e) !" )o using 5ET&EEN H AND H , IN,H/ has no performance benefits1 the benefit is logical simplicity" "ntroduction to $racle%i: SQL =-15

$uter Loins

,E>&RTME(TS

EM>LOAEES

'
There are no emplo*ees in department 1%3+
=-1& Copyright Oracle Corporation, 2001. All rights reserved.

eturning ecords !ith #o -irect /atch !ith $uter Loins #f a row does not satisfy a Aoin condition% the row will not appear in the 8uery result" (or e$ample% in the e8uiAoin condition of EMPLO'EES and DEPARTMENTS tables% employee Rrant does not appear because there is no department #7 recorded for her in the EMPLO'EES table" #nstead of seeing 20 employees in the result set% you see 54 records" SELECT e0la!t_name, e0department_id, d0department_name ROM emplo+ee! e, department! d &=ERE e0department_id : d0department_id"

'

"ntroduction to $racle%i: SQL =-1&

$uter Loins S*nta(


Eou use an outer Goin to also see ro!s that do not meet the Goin condition+ The $uter Goin operator is the plus sign 6,7+

SELECT table1.column, table2.column FROM table1, table2 12ERE table1.column(+) 3 table2.column; SELECT table1.column, table2.column FROM table1, table2 12ERE table1.column 3 table2.column(+);

=-1>

Copyright Oracle Corporation, 2001. All rights reserved.

2sing $uter Loins to eturn ecords !ith #o -irect /atch The missing rows can be returned if an outer 'oin operator is used in the Aoin condition" The operator is a plus sign enclosed in parentheses V!% and it is placed on the >side@ of the 'oin that is deficient in information" This operator has the effect of creating one or more null rows% to which one or more rows from the nondeficient table can be Aoined" #n the synta$& table1&column ' table2&column ,(/ is the condition that Aoins or relates! the tables together" is the outer Aoin symbol% which can be placed on either side of the &=ERE clause condition% but not on both sides" Place the outer Aoin symbol following the name of the column in the table without the matching rows"!

"nstructor #ote 7emo& Z_e;oin0!1l Purpose& To illustrate an e8uiAoin leading to an outer Aoin" "ntroduction to $racle%i: SQL =-1>

2sing $uter Loins

SELECT e7last_name, e7department_id, d7department_name FROM employees e, departments d 12ERE e7department_id"+# 3 d7department_id ;

'

=-1@

Copyright Oracle Corporation, 2001. All rights reserved.

2sing $uter Loins to eturn ecords !ith #o -irect /atch 6continued7 The slide e$ample displays employee last names% department #7Gs and department names" The ;ontracting department does not ha'e any employees" The empty 'alue is shown in the output shown" $uter Loin estrictions S The outer Aoin operator can appear on only one side of the e$pression2the side that has information missing" #t returns those rows from one table that ha'e no direct match in the other table" + condition in'ol'ing an outer Aoin cannot use the IN operator or be linked to another condition by the OR operator"

"nstructor #ote The #NION operator works around the issue of being able to use an outer Aoin operator on one side of the e$pression" The +0)# full outer Aoin also allows you to ha'e an outer Aoin on both sides of the e$pression" #t is discussed later in this lesson" 7emo& Z_o;oin0!1l Purpose& To illustrate an outer Aoin" "ntroduction to $racle%i: SQL =-1@

Self Loins

EM>LOAEES "1OR8ER#

EM>LOAEES "M&(&@ER#

'

'

M&(&@ER_-, in the 1OR8ER ta)le is e?ual to EM>LOAEE_-, in the M&(&@ER ta)le+


=-1% Copyright Oracle Corporation, 2001. All rights reserved.

Loining a Ta)le to "tself )ometimes you need to Aoin a table to itself" To find the name of each employeeGs manager% you need to Aoin the EMPLO'EES table to itself% or perform a self Aoin" (or e$ample% to find the name of NhalenGs manager% you need to& S S S (ind Nhalen in the EMPLO'EES table by looking at the LAST_NAME column" (ind the manager number for Nhalen by looking at the MANAGER_ID column" NhalenGs manager number is 505" (ind the name of the manager with EMPLO'EE_ID 505 by looking at the LAST_NAME column" =ochharGs employee number is 505% so =ochhar is NhalenGs manager"

#n this process% you look in the table twice" The first time you look in the table to find Nhalen in the LAST_NAME column and MANAGER_ID 'alue of 505" The second time you look in the EMPLO'EE_ID column to find 505 and the LAST_NAME column to find =ochhar"

"nstructor #ote )how the data from the EMPLO'EES table and point out how each manager is also an employee" "ntroduction to $racle%i: SQL =-1%

Loining a Ta)le to "tself


SELECT ForKer7last_name ** + ForKs =or + ** mana;er7last_name FROM employees ForKer, employees mana;er 12ERE ForKer7mana;er_id 3 mana;er7employee_id ;

'

=-53

Copyright Oracle Corporation, 2001. All rights reserved.

Loining a Ta)le to "tself 6continued7 The slide e$ample Aoins the EMPLO'EES table to itself" To simulate two tables in the ROM clause% there are two aliases% namely I and m% for the same table% EMPLO'EES" #n this e$ample% the &=ERE clause contains the Aoin that means >where a workerGs manager number matches the employee number for the manager"@

"nstructor #ote Point out the following to the students& S S The column heading in the result of the 8uery on the slide seems meaningless" + meaningful column alias should ha'e been used instead" There are only 54 rows in the output% but there are 20 rows in the EMPLO'EES table" This occurs because employee =ing% who is the president% does not ha'e a manager" "ntroduction to $racle%i: SQL =-53

4ractice =: 4art $ne: $1er1ie!


This practice co1ers !riting ?ueries to Goin ta)les together using $racle s*nta(+

=-51

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice =: 4art $ne This practice is designed to gi'e you a 'ariety of e$ercises that Aoin tables together using the 3racle synta$ shown in the lesson so far" ;omplete practice 8uestions 5- 4 at the end of this lesson"

"ntroduction to $racle%i: SQL =-51

Loining Ta)les 2sing SQL: 1%%% S*nta(


2se a Goin to ?uer* data from more than one ta)le+
SELECT table1.column, table2.column FROM table1 /CROSS OO-( table20 * /(&T9R&L OO-( table20 * /OO-( table2 9S-(@ "column_name#0 * /OO-( table2 O("table1.column_name 3 table2.column_name#0 * /LEFT*R-@2T*F9LL O9TER OO-( table2 O( "table1.column_name 3 table2.column_name#0;

=-55

Copyright Oracle Corporation, 2001. All rights reserved.

-efining Loins 6sing the )*L& 5444 synta$% you can obtain the same results as were shown in the prior pages" #n the synta$& table1&column CROSS 4OIN NAT#RAL 4OIN 4OIN table #SING column_name 4OIN table "( table1&column_name : table2&column_name )* +,!-./+, 0)) "0+*! 7enotes the table and column from which data is retrie'ed Jeturns a ;artesian product from the two tables Doins two tables based on the same column name Performs an e8uiAoin based on the column name Performs an e8uiAoin based on the condition in the ON clause

(or more information% see Oracle9i SQL Reference, >SELECT"@

"ntroduction to $racle%i: SQL =-55

Creating Cross Loins


The CROSS OO-( clause produces the crossproduct of t!o ta)les+ This is the same as a Cartesian product )et!een the t!o ta)les+

SELECT last_name, department_name FROM employees CROSS OO-( departments ;

'

=-58

Copyright Oracle Corporation, 2001. All rights reserved.

Creating Cross Loins The e$ample on the slide gi'es the same results as the following& SELECT la!t_name, department_name ROM emplo+ee!, department!"

'

"ntroduction to $racle%i: SQL =-58

Creating #atural Loins


The (&T9R&L OO-( clause is )ased on all columns in the t!o ta)les that ha1e the same name+ "t selects ro!s from the t!o ta)les that ha1e e?ual 1alues in all matched columns+ "f the columns ha1ing the same names ha1e different data t*pes: an error is returned+

=-5=

Copyright Oracle Corporation, 2001. All rights reserved.

Creating #atural Loins #t was not possible to do a Aoin without e$plicitly specifying the columns in the corresponding tables in prior releases of 3racle" #n 3racle4i it is possible to let the Aoin be completed automatically based on columns in the two tables which ha'e matching data types and names% using the keywords NAT#RAL 4OIN keywords" Note: The Aoin can happen only on columns ha'ing the same names and data types in both the tables" #f the columns ha'e the same name% but different data types% then the NAT#RAL 4OIN synta$ causes an error"

"ntroduction to $racle%i: SQL =-5=

etrie1ing

ecords !ith #atural Loins

SELECT department_id, department_name, location_id, city FROM departments (&T9R&L OO-( locations ;

=-55

Copyright Oracle Corporation, 2001. All rights reserved.

etrie1ing ecords !ith #atural Loins #n the e$ample on the slide% the LOCATIONS table is Aoined to the DEPARTMENT table by the LOCATION_ID column% which is the only column of the same name in both tables" #f other common columns were present% the Aoin would ha'e used them all" E1ui2oins The natural Aoin can also be written as an e8uiAoin& SELECT department_id, department_name, department!0location_id, cit+ ROM department!, location! &=ERE department!0location_id : location!0location_id" Natural 3oins "ith a 12ERE %lause +dditional restrictions on a natural Aoin are implemented by using a &=ERE clause" The e$ample below limits the rows of output to those with a department #7 e8ual to 20 or 50" SELECT department_id, department_name, location_id, cit+ ROM department! NAT#RAL 4OIN location! &=ERE department_id IN ,.*, C*/" "ntroduction to $racle%i: SQL =-55

Creating Loins !ith the 9S-(@ Clause


"f se1eral columns ha1e the same names )ut the data t*pes do not match: the (&T9R&L OO-( clause can )e modified !ith the 9S-(@ clause to specif* the columns that should )e used for an e?uiGoin+ 2se the 9S-(@ clause to match onl* one column !hen more than one column matches+ -o not use a ta)le name or alias in the referenced columns+ The (&T9R&L OO-( and 9S-(@ clauses are mutuall* e(clusi1e+

=-5&

Copyright Oracle Corporation, 2001. All rights reserved.

The 9S-(@ Clause 0atural Aoins use all columns with matching names and data types to Aoin the tables" The #SING clause can be used to specify only those columns that should be used for an e8uiAoin" The columns referenced in the #SING clause should not ha'e a 8ualifier table name or alias! anywhere in the )*L statement" (or e$ample% this statement is 'alid& SELECT l0cit+, d0department_name ROM location! l 4OIN department! d #SING ,location_id/ &=ERE location_id : -Z**" This statement is in'alid because the LOCATION_ID is 8ualified in the &=ERE clause& SELECT l0cit+, d0department_name ROM location! l 4OIN department! d #SING ,location_id/ &=ERE d0location_id : -Z**" ORAA.C-CZ8 col3mn part oU #SING cla3!e cannot 9aKe 13aliUier The same restriction applies to NAT#RAL Aoins also" Therefore columns that ha'e the same name in both tables ha'e to be used without any 8ualifiers"

"ntroduction to $racle%i: SQL =-5&

etrie1ing

ecords !ith the 9S-(@ Clause

SELECT e7employee_id, e7last_name, d7location_id FROM employees e OO-( departments d 9S-(@ "department_id# ;

'

=-5>

Copyright Oracle Corporation, 2001. All rights reserved.

The 9S-(@ Clause 6continued7 The e$ample shown Aoins the DEPARTMENT_ID column in the EMPLO'EES and DEPARTMENTS tables% and thus shows the location where an employee works" This can also be written as an e8uiAoin& SELECT emplo+ee_id, la!t_name, emplo+ee!0department_id, location_id ROM emplo+ee!, department! &=ERE emplo+ee!0department_id : department!0department_id"

"ntroduction to $racle%i: SQL =-5>

Creating Loins !ith the O( Clause


The Goin condition for the natural Goin is )asicall* an e?uiGoin of all columns !ith the same name+ To specif* ar)itrar* conditions or specif* columns to Goin: the O( clause is used+ The Goin condition is separated from other search conditions+ The O( clause ma;es code eas* to understand+

=-5@

Copyright Oracle Corporation, 2001. All rights reserved.

The O( Condition 6se the ON clause to specify a Aoin condition" This lets you specify Aoin conditions separate from any search or filter conditions in the &=ERE clause"

"ntroduction to $racle%i: SQL =-5@

etrie1ing

ecords !ith the O( Clause

SELECT e7employee_id, e7last_name, e7department_id, d7department_id, d7location_id FROM employees e OO-( departments d O( "e7department_id 3 d7department_id#;

'

=-5%

Copyright Oracle Corporation, 2001. All rights reserved.

Creating Loins !ith the O( Clause The ON clause can also be used as follows to Aoin columns that ha'e different names& SELECT e0la!t_name emp, m0la!t_name mgr ROM emplo+ee! e 4OIN emplo+ee! m ON ,e0manager_id : m0emplo+ee_id/"

'
The preceding e$ample is a selfAoin of the EMPLO'EE table to itself% based on the EMPLO'EE_ID and MANAGER_ID columns" "ntroduction to $racle%i: SQL =-5%

Creating Three-Wa* Loins !ith the O( Clause


SELECT FROM OO-( O( OO-( O( employee_id, city, department_name employees e departments d d7department_id 3 e7department_id locations l d7location_id 3 l7location_id;

'

=-83

Copyright Oracle Corporation, 2001. All rights reserved.

Three-Wa* Loins + three-way Aoin is a Aoin of three tables" #n )*L& 5444 compliant synta$% Aoins are performed from left to right so the first Aoin to be performed is EMPLO'EES 4OIN DEPARTMENTS" The first Aoin condition can reference columns in EMPLO'EES and DEPARTMENTS but cannot reference columns in LOCATIONS" The second Aoin condition can reference columns from all three tables" This can also be written as a three-way e8uiAoin& SELECT emplo+ee_id, cit+, department_name ROM emplo+ee!, department!, location! &=ERE emplo+ee!0department_id : department!0department_id AND department!0location_id : location!0location_id"

"nstructor #ote The e$ample shown can also be accomplished with the #SING clause& SELECT e0emplo+ee_id, l0cit+, d0department_name ROM emplo+ee! e 4OIN department! d #SING ,department_id/ 4OIN location! l #SING ,location_id/" "ntroduction to $racle%i: SQL =-83

-((ER 9ersus O9TER Loins


"n SQL: 1%%%: the Goin of t!o ta)les returning onl* matched ro!s is an inner Goin+ A Goin )et!een t!o ta)les that returns the results of the inner Goin as !ell as unmatched ro!s left 6or right7 ta)les is a left 6or right7 outer Goin+ A Goin )et!een t!o ta)les that returns the results of an inner Goin as !ell as the results of a left and right Goin is a full outer Goin+

=-81

Copyright Oracle Corporation, 2001. All rights reserved.

Loins - Comparing SQL: 1%%% to $racle S*nta(


Oracle ?8ui-Doin 3uter-Doin )elf-Doin 0on-?8ui-Doin ;artesian Product S4L: 5666 0aturalH#nner Doin Left 3uter Doin Doin ON Doin #SING ;ross Doin

"ntroduction to $racle%i: SQL =-81

LEFT O9TER OO-(


SELECT e7last_name, e7department_id, d7department_name FROM employees e LEFT O9TER OO-( departments d O( "e7department_id 3 d7department_id# ;

'

=-85

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of LEFT O9TER OO-( This 8uery retrie'es all rows in the EMPLO'EES table% which is the left table e'en if there is no match in the DEPARTMENTS table" This 8uery was completed in earlier releases as follows& SELECT e0la!t_name, e0department_id, d0department_name ROM emplo+ee! e, department! d &=ERE d0department_id ,(/ : e0department_id"

"ntroduction to $racle%i: SQL =-85

R-@2T O9TER OO-(


SELECT e7last_name, e7department_id, d7department_name FROM employees e R-@2T O9TER OO-( departments d O( "e7department_id 3 d7department_id# ;

'

=-88

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of R-@2T O9TER OO-( This 8uery retrie'es all rows in the DEPARTMENTS table% which is the right table e'en if there is no match in the EMPLO'EES table" This 8uery was completed in earlier releases as follows& SELECT e0la!t_name, e0department_id, d0department_name ROM emplo+ee! e, department! d &=ERE d0department_id : e0department_id ,(/"

"ntroduction to $racle%i: SQL =-88

F9LL O9TER OO-(


SELECT e7last_name, e7department_id, d7department_name FROM employees e F9LL O9TER OO-( departments d O( "e7department_id 3 d7department_id# ;

'

=-8=

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of F9LL O9TER OO-( This 8uery retrie'es all rows in the EMPLO'EES table% e'en if there is no match in the DEPARTMENTS table" #t also retrie'es all rows in the DEPARTMENTS table% e'en if there is no match in the EMPLO'EES table"

"nstructor #ote #t was not possible to complete this in earlier releases using outer Aoins" <owe'er% you could accomplish the same results using the #NION operator" SELECT e0la!t_name, e0department_id, d0department_name ROM emplo+ee! e, department! d &=ERE e0department_id ,(/ : d0department_id #NION SELECT e0la!t_name, e0department_id, d0department_name ROM emplo+ee! e, department! d &=ERE e0department_id : d0department_id ,(/" "ntroduction to $racle%i: SQL =-8=

Additional Conditions
SELECT e7employee_id, e7last_name, e7department_id, d7department_id, d7location_id FROM employees e OO-( departments d O( "e7department_id 3 d7department_id# &(, e7mana;er_id 3 H4 ;

=-85

Copyright Oracle Corporation, 2001. All rights reserved.

Appl*ing Additional Conditions You can apply additional conditions in the &=ERE clause" The e$ample shown performs a Aoin on the EMPLO'EES and DEPARTMENTS tables% and% in addition% displays only employees with a manager #7 e8ual to 544"

"ntroduction to $racle%i: SQL =-85

Summar*
"n this lesson: *ou should ha1e learned ho! to use Goins to displa* data from multiple ta)les in:

$racle proprietar* s*nta( for 1ersions @i and earlier SQL: 1%%% compliant s*nta( for 1ersion %i

=-8&

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* There are multiple ways to Aoin tables" Types o/ 3oins S S S S S S S ?8uiAoins 0on-e8uiAoins 3uter Aoins )elf Aoins ;ross Aoins 0atural Aoins (ull or outer Aoins

%artesian $ro&ucts + ;artesian product results in all combinations of rows displayed" This is done by either omitting the &=ERE clause or specifying the CROSS 4OIN clause" Table Aliases S S Table aliases speed up database access" Table aliases can help to keep )*L code smaller% by conser'ing memory"

"ntroduction to $racle%i: SQL =-8&

4ractice =: 4art T!o: $1er1ie!


This practice co1ers the follo!ing topics: Loining ta)les using an e?uiGoin 4erforming outer and self Goins Adding conditions

=-8>

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice =: 4art T!o This practice is intended to gi'e you practical e$perience in e$tracting data from more than one table" Try using both the 3racle proprietary synta$ and the )*L& 5444 compliant synta$" #n Part Two% 8uestions 5-L% try writing the Aoin statements using +0)# synta$" #n Part Two% 8uestions 4-55% try writing the Aoin statements using both the 3racle synta$ and the +0)# synta$"

"ntroduction to $racle%i: SQL =-8>

4ractice = - 4art $ne 5" Nrite a 8uery to display the last name% department number% and department name for all employees"

'
2" ;reate a uni8ue listing of all Aobs that are in department L0" #nclude the location of the department in the output"

/" Nrite a 8uery to display the employee last name% department name% location #7% and city of all employees who earn a commission"

"ntroduction to $racle%i: SQL =-8@

4ractice = - 4art $ne 6continued7 4" 7isplay the employee last name and department name for all employees who ha'e an a lowercase! in their last names" Place your )*L statement in a te$t file named la<Z_Z0!1l"

"ntroduction to $racle%i: SQL =-8%

4ractice = - 4art T!o 5" Nrite a 8uery to display the last name% Aob% department number% and department name for all employees who work in Toronto"

6" 7isplay the employee last name and employee number along with their managerGs last name and manager number" Label the columns Emplo+ee% Emp@% Manager% and Mgr@% respecti'ely" Place your )*L statement in a te$t file named la<Z_E0!1l"

"ntroduction to $racle%i: SQL =-=3

4ractice = - 4art T!o 6continued7 E" Modify la<Z_E0!1l to display all employees including =ing% who has no manager" 3rder the results by the employee number" Place your )*L statement in a te$t file named la<Z_?0!1l" Jun the 8uery in la<Z_?0!1l"

'
#f you ha'e time% complete the following e$ercises& L" ;reate a 8uery that displays employee last names% department numbers% and all the employees who work in the same department as a gi'en employee" Ri'e each column an appropriate label"

'
"ntroduction to $racle%i: SQL =-=1

4ractice = - 4art T!o 6continued7 4" )how the structure of the 4O5_GRADES table" ;reate a 8uery that displays the name% Aob% department name% salary% and grade for all employees"

'
#f you want an e$tra challenge% complete the following e$ercises& 50" ;reate a 8uery to display the name and hire date of any employee hired after employee 7a'ies"

"ntroduction to $racle%i: SQL =-=5

4ractice = - 4art T!o 6continued7 55" 7isplay the names and hire dates for all employees who were hired before their managers% along with their managerGs names and hire dates" Label the columns Emplo+ee% Emp =ired% Manager% and Mgr =ired% respecti'ely"

"ntroduction to $racle%i: SQL =-=8

"ntroduction to $racle%i: SQL =-==

Aggregating -ata 2sing Croup Functions

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
/5 minutes 40 minutes E5 minutes

Topic
Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing:

"dentif* the a1aila)le group functions -escri)e the use of group functions Croup data using the @RO9> .A clause "nclude or e(clude grouped ro!s )* using the 2&Q-(@ clause

5-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim This lesson further addresses functions" #t focuses on obtaining summary information% such as a'erages% for groups of rows" #t discusses how to group rows in a table into smaller sets and how to specify search criteria for groups of rows"

"ntroduction to $racle%i: SQL 5-5

What Are Croup FunctionsM


Croup functions operate on sets of ro!s to gi1e one result per group+
EM>LOAEES

The ma(imum salar* in the EM>LOAEES ta)le+

'
5-8 Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions 6nlike single-row functions% group functions operate on sets of rows to gi'e one result per group" These sets may be the whole table or the table split into groups"

"ntroduction to $racle%i: SQL 5-8

T*pes of Croup Functions


&Q@ CO9(T M&N M-( ST,,EQ S9M Q&R-&(CE

5-=

Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions 6continued7 ?ach of the functions accepts an argument" The following table identifies the options that you can use in the synta$&
Function A$G,PDISTINCT6ALLQn/ CO#NT,R*6PDISTINCT6ALLQexprS/ Description +'erage 'alue of n% ignoring null 'alues 0umber of rows% where expr e'aluates to something other than null count all selected rows using B% including duplicates and rows with nulls! Ma$imum 'alue of expr% ignoring null 'alues Minimum 'alue of expr% ignoring null 'alues )tandard de'iation of n% ignoring null 'alues )um 'alues of n% ignoring null 'alues Cariance of n% ignoring null 'alues

MA%,PDISTINCT6ALLQexpr/ MIN,PDISTINCT6ALLQexpr/ STDDE$,PDISTINCT6ALLQx/ S#M,PDISTINCT6ALLQn/ $ARIANCE,PDISTINCT6ALLQx/

"ntroduction to $racle%i: SQL 5-=

Croup Functions S*nta(

SELECT FROM /12ERE /@RO9> .A /OR,ER .A

/column,0 group_function(column), ... table condition0 column0 column0;

5-5

Copyright Oracle Corporation, 2001. All rights reserved.

Cuidelines for 2sing Croup Functions O DISTINCT makes the function consider only nonduplicate 'alues1 ALL makes it consider e'ery 'alue including duplicates" The default is ALL and therefore does not need to be specified" S S S The data types for the functions with an e>pr argument may be C=AR% $ARC=AR.% N#M5ER% or DATE" +ll group functions ignore null 'alues" To substitute a 'alue for null 'alues% use the N$L% N$L.% or COALESCE functions" The 3racle ser'er implicitly sorts the result set in ascending order when using a GRO#P 5' clause" To o'erride this default ordering% DESC can be used in an ORDER 5' clause"

"nstructor #ote )tress the use of DISTINCT and group functions ignoring null 'alues" ALL is the default and is 'ery rarely specified"

"ntroduction to $racle%i: SQL 5-5

2sing the &Q@ and S9M Functions


Eou can use &Q@ and S9M for numeric data+
SELECT &Q@"salary#, M&N"salary#, M-("salary#, S9M"salary# FROM employees 12ERE $o%_id L-8E +<RE><+;

5-&

Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions You can use A$G% S#M% MIN% and MA% functions against columns that can store numeric data" The e$ample on the slide displays the a'erage% highest% lowest% and sum of monthly salaries for all sales representati'es"

"ntroduction to $racle%i: SQL 5-&

2sing the M-( and M&N Functions


Eou can use M-( and M&N for an* data t*pe+
SELECT M-("5ire_date#, M&N"5ire_date# FROM employees;

5->

Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions 6continued7 You can use the MA% and MIN functions for any data type" The slide e$ample displays the most Aunior and most senior employee" The following e$ample displays the employee last name that is first and the employee last name that is the last in an alphabeti9ed list of all employees" SELECT MIN,la!t_name/, MA%,la!t_name/ ROM emplo+ee!"

Note: A$G% S#M% $ARIANCE% and STDDE$ functions can be used only with numeric data types"

"ntroduction to $racle%i: SQL 5->

2sing the CO9(T Function


CO9(T"*# returns the num)er of ro!s in a ta)le+
SELECT CO9(T"*# FROM employees 12ERE department_id 3 :0;

5-@

Copyright Oracle Corporation, 2001. All rights reserved.

The CO9(T Function The CO#NT function has three formats& O CO#NT,*/ O CO#NT,expr/ O CO#NT,DISTINCT expr/ CO#NT,*/ returns the number of rows in a table that satisfy the criteria of the SELECT statement% including duplicate rows and rows containing null 'alues in any of the columns" #f a &=ERE clause is included in the SELECT statement% CO#NT,*/ returns the number of rows that satisfies the condition in the &=ERE clause" #n contrast% CO#NT,expr/ returns the number of non-null 'alues in the column identified by expr" CO#NT,DISTINCT expr/ returns the number of uni8ue% non-null 'alues in the column identified by expr" The slide e$ample displays the number of employees in department 50"

"nstructor #ote 7emo& C_co3nt-0!1l, C_co3nt.0!1l Purpose& To illustrate using the CO#NT,*/ and CO#NT,expr/ functions "ntroduction to $racle%i: SQL 5-@

2sing the CO9(T Function


CO9(T"expr# returns the num)er of ro!s !ith non-null 1alues for the expr+ -ispla* the num)er of department 1alues in the EM>LOAEES ta)le: e(cluding the null 1alues+

SELECT CO9(T"commission_pct# FROM employees 12ERE department_id 3 P0;

5-%

Copyright Oracle Corporation, 2001. All rights reserved.

The CO9(T Function 6continued7 The slide e$ample displays the number of employees in department L0 who can earn a commission" Example 7isplay the number of department 'alues in the EMPLO'EES table" SELECT CO#NT,department_id/ ROM emplo+ee!"

"ntroduction to $racle%i: SQL 5-%

2sing the ,-ST-(CT Ne*!ord


CO9(T",-ST-(CT eTpr# returns the num)er of distinct non-null 1alues of the expr+ -ispla* the num)er of distinct department 1alues in the EM>LOAEES ta)le+
SELECT CO9(T",-ST-(CT department_id# FROM employees;

5-13

Copyright Oracle Corporation, 2001. All rights reserved.

The ,-ST-(CT Ne*!ord 6se the DISTINCT keyword to suppress the counting of any duplicate 'alues within a column" The e$ample on the slide displays the number of distinct department 'alues in the EMPLO'EES table"

"ntroduction to $racle%i: SQL 5-13

Croup Functions and #ull 9alues


Croup functions ignore null 1alues in the column+
SELECT &Q@"commission_pct# FROM employees;

5-11

Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions and #ull 9alues +ll group functions ignore null 'alues in the column" #n the slide e$ample% the a'erage is calculated based only on the rows in the table where a 'alid 'alue is stored in the COMMISSION_PCT column" The a'erage is calculated as the total commission paid to all employees di'ided by the number of employees recei'ing a commission four!"

"ntroduction to $racle%i: SQL 5-11

2sing the (QL Function !ith Croup Functions


The (QL function forces group functions to include null 1alues+
SELECT &Q@"(QL"commission_pct, 0## FROM employees;

5-15

Copyright Oracle Corporation, 2001. All rights reserved.

Croup Functions and #ull 9alues 6continued7 The N$L function forces group functions to include null 'alues" #n the slide e$ample% the a'erage is calculated based on all rows in the table% regardless of whether null 'alues are stored in the COMMISSION_PCT column" The a'erage is calculated as the total commission paid to all employees di'ided by the total number of employees in the company 20!"

"ntroduction to $racle%i: SQL 5-15

Creating Croups of -ata


EM>LOAEES
==33 %533

The a1erage 8533 salar* in EM>LOAEES ta)le &=33 for each department+
13388

'

5-18

Copyright Oracle Corporation, 2001. All rights reserved.

Croups of -ata 6ntil now% all group functions ha'e treated the table as one large group of information" +t times% you need to di'ide the table of information into smaller groups" This can be done by using the GRO#P 5' clause"

"ntroduction to $racle%i: SQL 5-18

Creating Croups of -ata: The @RO9> .A Clause S*nta(

SELECT FROM /12ERE /@RO9> .A /OR,ER .A

column, group_function(column) table condition0 group_by_expression0 column0;

-i1ide ro!s in a ta)le into smaller groups )* using the @RO9> .A clause+

5-1=

Copyright Oracle Corporation, 2001. All rights reserved.

The @RO9> .A Clause You can use the GRO#P 5' clause to di'ide the rows in a table into groups" You can then use the group functions to return summary information for each group" #n the synta$& group_b$_expression Cuidelines S #f you include a group function in a SELECT clause% you cannot select indi'idual results as well% unless the indi'idual column appears in the GRO#P 5' clause" You recei'e an error message if you fail to include the column list in the GRO#P 5' clause" 6sing a &=ERE clause% you can e$clude rows before di'iding them into groups" You must include the columns in the GRO#P 5' clause" You cannot use a column alias in the GRO#P 5' clause" specifies columns whose 'alues determine the basis for grouping rows

S S S

S ,y default% rows are sorted by ascending order of the columns included in the GRO#P 5' list" You can o'erride this by using the ORDER 5' clause"

"ntroduction to $racle%i: SQL 5-1=

2sing the @RO9> .A Clause


All columns in the SELECT list that are not in group functions must )e in the @RO9> .A clause+
SELECT department_id, &Q@"salary# FROM employees @RO9> .A department_id ;

5-15

Copyright Oracle Corporation, 2001. All rights reserved.

The @RO9> .A Clause 6continued7 Nhen using the GRO#P 5' clause% make sure that all columns in the SELECT list that are not group functions are included in the GRO#P 5' clause" The e$ample on the slide displays the department number and the a'erage salary for each department" <ere is how this SELECT statement% containing a GRO#P 5' clause% is e'aluated& S The SELECT clause specifies the columns to be retrie'ed& F F S S S 7epartment number column in the EMPLO'EES table The a'erage of all the salaries in the group you specified in the GRO#P 5' clause

The ROM clause specifies the tables that the database must access& the EMPLO'EES table" The &=ERE clause specifies the rows to be retrie'ed" )ince there is no &=ERE clause% all rows are retrie'ed by default" The GRO#P 5' clause specifies how the rows should be grouped" The rows are being grouped by department number% so the A$G function that is being applied to the salary column will calculate the a(era)e salary for each department.

"nstructor #ote Rroup results are sorted implicitly% on the grouping column" You can use ORDER 5' to specify a different sort order% remembering to use only group functions% or the grouping column" "ntroduction to $racle%i: SQL 5-15

2sing the @RO9> .A Clause


The @RO9> .A column does not ha1e to )e in the SELECT list+
SELECT &Q@"salary# FROM employees @RO9> .A department_id ;

5-1&

Copyright Oracle Corporation, 2001. All rights reserved.

The @RO9> .A Clause 6continued7 The GRO#P 5' column does not ha'e to be in the SELECT clause" (or e$ample% the SELECT statement on the slide displays the a'erage salaries for each department without displaying the respecti'e department numbers" Nithout the department numbers% howe'er% the results do not look meaningful" You can use the group function in the ORDER 5' clause" SELECT ROM GRO#P 5' ORDER 5' department_id, A$G,!alar+/ emplo+ee! department_id A$G,!alar+/"

'
"nstructor #ote 7emonstrate the 8uery with and without the DEPARTMENT_ID column in the SELECT statement" "ntroduction to $racle%i: SQL 5-1&

Crouping )* /ore Than $ne Column


EM>LOAEES

'

OAdd up the salaries in the EM>LOAEES ta)le for each Go): grouped )* department+

5-1>

Copyright Oracle Corporation, 2001. All rights reserved.

Croups !ithin Croups )ometimes you need to see results for groups within groups" The slide shows a report that displays the total salary being paid to each Aob title% within each department" The EMPLO'EES table is grouped first by department number and% within that grouping% by Aob title" (or e$ample% the four stock clerks in department 50 are grouped together and a single result total salary! is produced for all stock clerks within the group"

"nstructor #ote 7emo& C_order-0!1l% C_order.0!1l Purpose& To illustrate ordering columns that are grouped by DEPARTMENT_ID first and ordering columns that are grouped by 4O5_ID first" "ntroduction to $racle%i: SQL 5-1>

2sing the @RO9> .A Clause on /ultiple Columns


SELECT department_id dept_id, $o%_id, S9M"salary# FROM employees @RO9> .A department_id, $o%_id ;

5-1@

Copyright Oracle Corporation, 2001. All rights reserved.

Croups !ithin Croups 6continued7 You can return summary results for groups and subgroups by listing more than one GRO#P 5' column" You can determine the default sort order of the results by the order of the columns in the GRO#P 5' clause" <ere is how the SELECT statement on the slide% containing a GRO#P 5' clause% is e'aluated& S The SELECT clause specifies the column to be retrie'ed& F F F S S 7epartment number in the EMPLO'EES table Dob #7 in the EMPLO'EES table The sum of all the salaries in the group that you specified in the GRO#P 5' clause

The ROM clause specifies the tables that the database must access& the EMPLO'EES table" The GRO#P 5' clause specifies how you must group the rows& F F (irst% the rows are grouped by department number" )econd% within the department number groups% the rows are grouped by Aob #7"

)o the S#M function is being applied to the salary column for all Aob #7s within each department number group"

"ntroduction to $racle%i: SQL 5-1@

"llegal Queries 2sing Croup Functions


An* column or e(pression in the SELECT list that is not an aggregate function must )e in the @RO9> .A clause+
SELECT department_id, CO9(T"last_name# FROM employees; SELECT department_id, CO9(T"last_name# * ERROR at line R OR&J0043MR not a sin;leJ;ro)p ;ro)p =)nction

Column missing in the @RO9> .A clause


5-1% Copyright Oracle Corporation, 2001. All rights reserved.

"llegal Queries 2sing Croup Functions Nhene'er you use a mi$ture of indi'idual items DEPARTMENT_ID! and group functions CO#NT! in the same SELECT statement% you must include a GRO#P 5' clause that specifies the indi'idual items in this case% DEPARTMENT_ID!" #f the GRO#P 5' clause is missing% then the error message >not a single-group group function@ appears and an asterisk B! points to the offending column" You can correct the error on the slide by adding the GRO#P 5' clause" SELECT department_id, co3nt,la!t_name/ ROM emplo+ee! GRO#P 5' department_id"

'
+ny column or e$pression in the SELECT list that is not an aggregate function must be in the GRO#P 5' clause" "nstructor #ote 7emo& C_error0!1l Purpose& To illustrate e$ecuting a SELECT statement with no GRO#P 5' clause "ntroduction to $racle%i: SQL 5-1%

"llegal Queries 2sing Croup Functions


Eou cannot use the 12ERE clause to restrict groups+ Eou use the 2&Q-(@ clause to restrict groups+ Eou cannot use group functions in the 12ERE clause+
department_id, &Q@"salary# employees &Q@"salary# ? P000 department_id;

SELECT FROM 12ERE @RO9> .A 12ERE

&Q@"salary# ? P000 * ERROR at line 3R OR&J0043HR ;ro)p =)nction is not alloFed 5ere

Cannot use the 12ERE clause to restrict groups


5-53 Copyright Oracle Corporation, 2001. All rights reserved.

"llegal Queries 2sing Croup Functions 6continued7 The &=ERE clause cannot be used to restrict groups" The SELECT statement on the slide results in an error because it uses the &=ERE clause to restrict the display of a'erage salaries of those departments that ha'e an a'erage salary greater than .L%000" You can correct the slide error by using the =A$ING clause to restrict groups" SELECT ROM =A$ING GRO#P 5' department_id, A$G,!alar+/ emplo+ee! A$G,!alar+/ D [*** department_id"

"ntroduction to $racle%i: SQL 5-53

E(cluding Croup
EM>LOAEES

esults

'

The ma(imum salar* per department !hen it is greater than I13:333

5-51

Copyright Oracle Corporation, 2001. All rights reserved.

estricting Croup esults #n the same way that you use the &=ERE clause to restrict the rows that you select% you use the =A$ING clause to restrict groups" To find the ma$imum salary of each department% but show only the departments that ha'e a ma$imum salary of more than .50%000% you need to do the following& 5" (ind the a'erage salary for each department by grouping by department number" 2" Jestrict the groups to those departments with a ma$imum salary greater than .50%000"

"ntroduction to $racle%i: SQL 5-51

E(cluding Croup esults: The 2&Q-(@ Clause


2se the 2&Q-(@ clause to restrict groups: 1+ o!s are grouped+ 5+ The group function is applied+ 8+ Croups matching the 2&Q-(@ clause are displa*ed+
SELECT FROM /12ERE /@RO9> .A /2&Q-(@ /OR,ER .A column, group_function table condition0 group_by_expression0 group_condition0 column0;

5-55

Copyright Oracle Corporation, 2001. All rights reserved.

The 2&Q-(@ Clause You use the =A$ING clause to specify which groups are to be displayed% and thus% you further restrict the groups on the basis of aggregate information" #n the synta$& group_condition restricts the groups of rows returned to those groups for which the specified condition is true

The 3racle ser'er performs the following steps when you use the =A$ING clause& 5" Jows are grouped" 2" The group function is applied to the group" /" The groups that match the criteria in the =A$ING clause are displayed" The =A$ING clause can precede the GRO#P 5' clause% but it is recommended that you place the GRO#P 5' clause first because that is more logical" Rroups are formed and group functions are calculated before the =A$ING clause is applied to the groups in the SELECT list" "nstructor #ote The 3racle ser'er e'aluates the clauses in the following order& S #f the statement contains a &=ERE clause% the ser'er establishes the candidate rows" S The ser'er identifies the groups specified in the GRO#P 5' clause" S The =A$ING clause further restricts result groups that do not meet the group criteria in the =A$ING clause" "ntroduction to $racle%i: SQL 5-55

2sing the 2&Q-(@ Clause

SELECT FROM @RO9> .A 2&Q-(@

department_id, M&N"salary# employees department_id M&N"salary#? 0000 ;

5-58

Copyright Oracle Corporation, 2001. All rights reserved.

The 2&Q-(@ Clause 6continued7 The slide e$ample displays department numbers and ma$imum salaries for those departments whose ma$imum salary is greater than .50%000" You can use the GRO#P 5' clause without using a group function in the SELECT list" #f you restrict rows based on the result of a group function% you must ha'e a GRO#P 5' clause as well as the =A$ING clause" The following e$ample displays the department numbers and a'erage salaries for those departments whose ma$imum salary is greater than .50%000& SELECT ROM GRO#P 5' =A$ING department_id, A$G,!alar+/ emplo+ee! department_id ma>,!alar+/D-****"

"ntroduction to $racle%i: SQL 5-58

2sing the 2&Q-(@ Clause

SELECT FROM 12ERE @RO9> .A 2&Q-(@ OR,ER .A

$o%_id, S9M"salary# >&AROLL employees $o%_id (OT L-8E +<RE><+ $o%_id S9M"salary# ? 3000 S9M"salary#;

5-5=

Copyright Oracle Corporation, 2001. All rights reserved.

The 2&Q-(@ Clause 6continued7 The slide e$ample displays the Aob #7 and total monthly salary for each Aob with a total payroll e$ceeding .5/%000" The e$ample e$cludes sales representati'es and sorts the list by the total monthly salary"

"nstructor #ote 7emo& C_;o<-0!1l% C_;o<.0!1l Purpose& To illustrate using a &=ERE clause to restrict rows by 4O5_ID and using a =A$ING clause to restrict groups by S#M,SALAR'/" "ntroduction to $racle%i: SQL 5-5=

#esting Croup Functions


-ispla* the ma(imum a1erage salar*+
M&N"&Q@"salary## SELECT FROM employees @RO9> .A department_id;

5-55

Copyright Oracle Corporation, 2001. All rights reserved.

#esting Croup Functions Rroup functions can be nested to a depth of two" The slide e$ample displays the ma$imum a'erage salary"

"ntroduction to $racle%i: SQL 5-55

Summar*

"n this lesson: *ou should ha1e learned ho! to:

2se the group functions CO9(T: M&N: M-(: &Q@ Write ?ueries that use the @RO9> .A clause Write ?ueries that use the 2&Q-(@ clause
column, group_function(column) table condition0 group_by_expression0 group_condition0 column0;

SELECT FROM /12ERE /@RO9> .A /2&Q-(@ /OR,ER .A

5-5&

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* )e'en group functions are a'ailable in )*L& O A$G O CO#NT O MA% O MIN O S#M O STDDE$ O $ARIANCE You can create subgroups by using the GRO#P 5' clause" Rroups can be e$cluded using the =A$ING clause" Place the =A$ING and GRO#P 5' clauses after the &=ERE clause in a statement" Place the ORDER 5' clause last" The 3racle ser'er e'aluates the clauses in the following order& 5" #f the statement contains a &=ERE clause% the ser'er establishes the candidate rows" 2" The ser'er identifies the groups specified in the GRO#P 5' clause" /" The =A$ING clause further restricts result groups that do not meet the group criteria in the =A$ING clause" "ntroduction to $racle%i: SQL 5-5&

4ractice 5 $1er1ie!
This practice co1ers the follo!ing topics:

Writing ?ueries that use the group functions Crouping )* ro!s to achie1e more than one result E(cluding groups )* using the 2&Q-(@ clause

5-5>

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 5 $1er1ie! +t the end of this practice% you should be familiar with using group functions and selecting groups of data" 4aper-Based Questions (or 8uestions 5-/% circle either True or (alse" Note: ;olumn aliases are used for the 8ueries"

"nstructor #ote <int for *uestion YE& +d'ise the students to think about the MANAGER_ID column in EMPLO'EES when determining the number of managers% rather than the 4O5_ID column" "ntroduction to $racle%i: SQL 5-5>

4ractice 5 7etermine the 'alidity of the following three statements" ;ircle either True or (alse" 5" Rroup functions work across many rows to produce one result per group" TrueH(alse 2" Rroup functions include nulls in calculations" TrueH(alse /" The &=ERE clause restricts rows prior to inclusion in a group calculation" TrueH(alse 4" 7isplay the highest% lowest% sum% and a'erage salary of all employees" Label the columns Ma>im3m% Minim3m% S3m% and AKerage% respecti'ely" Jound your results to the nearest whole number" Place your )*L statement in a te$t file named la<C_Z0!1l"

5" Modify the 8uery in la<C_Z0!1l to display the minimum% ma$imum% sum% and a'erage salary for each Aob type" Jesa'e la<C_Z0!1l to la<C_C0!1l" Jun the statement in la<C_C0!1l"

"ntroduction to $racle%i: SQL 5-5@

4ractice 5 6continued7 6" Nrite a 8uery to display the number of people with the same Aob"

E" 7etermine the number of managers without listing them" Label the column N3m<er oU Manager!" *int+ ,se the #1(1.*!_-2 column to determine the number of mana)ers.

L" Nrite a 8uery that displays the difference between the highest and lowest salaries" Label the column DI ERENCE"

#f you ha'e time% complete the following e$ercises& 4" 7isplay the manager number and the salary of the lowest paid employee for that manager" ?$clude anyone whose manager is not known" ?$clude any groups where the minimum salary is .6%000 or less" )ort the output in descending order of salary"

"ntroduction to $racle%i: SQL 5-5%

4ractice 5 6continued7 50" Nrite a 8uery to display each departmentGs name% location% number of employees% and the a'erage salary for all employees in that department" Label the columns Name% Location% N3m<er oU People% and Salar+% respecti'ely" Jound the a'erage salary to two decimal places"

#f you want an e$tra challenge% complete the following e$ercises& 55" ;reate a 8uery that will display the total number of employees and% of that total% the number of employees hired in 5445% 5446% 544E% and 544L" ;reate appropriate column headings"

52"

;reate a matri$ 8uery to display the Aob% the salary for that Aob based on department number% and the total salary for that Aob% for departments 20% 50% L0% and 40% gi'ing each column an appropriate heading"

"ntroduction to $racle%i: SQL 5-83

Su)?ueries

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing 25 minutes /0 minutes 55 minutes

Topic Lecture Practice Total

$)Gecti1es

After completing this lesson: *ou should )e a)le to do the follo!ing:

-escri)e the t*pes of pro)lem that su)?ueries can sol1e -efine su)?ueries List the t*pes of su)?ueries Write single-ro! and multiple-ro! su)?ueries

&-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim #n this lesson% you learn about more ad'anced features of the SELECT statement" You can write sub8ueries in the &=ERE clause of another )*L statement to obtain 'alues based on an unknown conditional 'alue" This lesson co'ers single-row sub8ueries and multiple-row sub8ueries"

"ntroduction to $racle%i: SQL &-5

2sing a Su)?uer* to Sol1e a 4ro)lem


Who has a salar* greater than A)elPsM
/ain Quer*:

Which emplo*ees ha1e salaries greater than A)elPs salar*M


Su)?uer*

What is A)elPs salar*M

&-8

Copyright Oracle Corporation, 2001. All rights reserved.

2sing a Su)?uer* to Sol1e a 4ro)lem )uppose you want to write a 8uery to find out who earns a salary greater than +belGs salary" To sol'e this problem% you need t o 8ueries& one to find what +bel earns% and a second 8uery to find who earns more than that amount" You can sol'e this problem by combining the two 8ueries% placing one 8uery inside the other 8uery" The inner 8uery or the subquery returns a 'alue that is used by the outer 8uery or the main 8uery" 6sing a sub8uery is e8ui'alent to performing two se8uential 8ueries and using the result of the first 8uery as the search 'alue in the second 8uery"

"nstructor #ote This lesson concentrates on noncorrelated sub8ueries" "ntroduction to $racle%i: SQL &-8

Su)?uer* S*nta(
SELECT FROM 12ERE select_list table expr operator "SELECT FROM

select_list table#;

The su)?uer* 6inner ?uer*7 e(ecutes once )efore the main ?uer*+ The result of the su)?uer* is used )* the main ?uer* 6outer ?uer*7+

&-=

Copyright Oracle Corporation, 2001. All rights reserved.

Su)?ueries + sub8uery is a SELECT statement that is embedded in a clause of another SELECT statement" You can build powerful statements out of simple ones by using sub8ueries" They can be 'ery useful when you need to select rows from a table with a condition that depends on the data in the table itself" You can place the sub8uery in a number of )*L clauses% including& S S S The &=ERE clause The =A$ING clause The ROM clause

#n the synta$& operator includes a comparison condition such as X% Q% or IN Note: ;omparison conditions fall into two classes& single-row operators X% Q% XQ% W% WX% WQ! and multiple-row operators IN% AN'% ALL!" The sub8uery is often referred to as a nested SELECT% sub-SELECT% or inner SELECT statement" The sub8uery generally e$ecutes first% and its output is used to complete the 8uery condition for the main or outer 8uery" "nstructor #ote +dditionally% sub8ueries can be placed in the CREATE $IE& statement% CREATE TA5LE statement% #PDATE statement% INTO clause of an INSERT statement% and SET clause of an #PDATE statement" "ntroduction to $racle%i: SQL &-=

2sing a Su)?uer*
SELECT last_name FROM employees 11333 12ERE salary ? "SELECT salary FROM employees 12ERE last_name 3 +&%el+#;

&-5

Copyright Oracle Corporation, 2001. All rights reserved.

2sing a Su)?uer* #n the slide% the inner 8uery determines the salary of employee +bel" The outer 8uery takes the result of the inner 8uery and uses this result to display all the employees who earn more than this amount"

"nstructor #ote ?$ecute the sub8uery inner 8uery! on its own first to show the 'alue that the sub8uery returns" Then e$ecute the outer 8uery using the result returned by the inner 8uery" (inally% e$ecute the entire 8uery containing the sub8uery!% and show that the result is the same" "ntroduction to $racle%i: SQL &-5

Cuidelines for 2sing Su)?ueries

Enclose su)?ueries in parentheses+ 4lace su)?ueries on the right side of the comparison condition+ The OR,ER .A clause in the su)?uer* is not needed unless *ou are performing Top-# anal*sis+ 2se single-ro! operators !ith single-ro! su)?ueries and use multiple-ro! operators !ith multiple-ro! su)?ueries+

&-&

Copyright Oracle Corporation, 2001. All rights reserved.

Cuidelines for 2sing Su)?ueries S S S + sub8uery must be enclosed in parentheses" Place the sub8uery on the right side of the comparison condition for readability" Prior to release 3racleLi% sub8ueries could not contain an ORDER 5' clause" 3nly one ORDER 5' clause can be used for a SELECT statement% and if specified it must be the last clause in the main SELECT statement" )tarting with release 3racleLi% an ORDER 5' clause can be used and is re8uired in the sub8uery to perform Top-0 analysis" Two classes of comparison conditions are used in sub8ueries& single-row operators and multiple-row operators"

"nstructor #ote + sub8uery can e$ecute multiple times in correlated sub8ueries" )tudents may ask how many sub8ueries can be written" The 3racle ser'er imposes no limit on the number of sub8ueries1 the limit is related to the buffer si9e that the 8uery uses" "ntroduction to $racle%i: SQL &-&

T*pes of Su)?ueries

Single-ro! su)?uer*
/ain ?uer* Su)?uer* returns

STQCLE N

/ultiple-ro! su)?uer*
/ain ?uer* Su)?uer* returns

STQCLE N SAQ/A#

&->

Copyright Oracle Corporation, 2001. All rights reserved.

T*pes of Su)?ueries S S )ingle-row sub8ueries& *ueries that return only one row from the inner SELECT statement Multiple-row sub8ueries& *ueries that return more than one row from the inner SELECT statement

Note: There are also multiple-column sub8ueries& *ueries that return more than one column from the inner SELECT statement"

"nstructor #ote Multiple column sub8ueries are also a'ailable" "ntroduction to $racle%i: SQL &->

Single- o! Su)?ueries
eturn onl* one ro! 2se single-ro! comparison operators
$perator A B BA D DA DB
&-@

/eaning E?ual to Creater than Creater than or e?ual to Less than Less than or e?ual to #ot e?ual to

Copyright Oracle Corporation, 2001. All rights reserved.

Single- o! Su)?ueries + single-row sub8uery is one that returns one row from the inner SELECT statement" This type of sub8uery uses a single-row operator" The slide gi'es a list of single-row operators" Example 7isplay the employees whose Aob #7 is the same as that of employee 545" SELECT la!t_name, ;o<_id ROM emplo+ee! &=ERE ;o<_id : ,SELECT ;o<_id ROM emplo+ee! &=ERE emplo+ee_id : -Z-/"

"ntroduction to $racle%i: SQL &-@

E(ecuting Single- o! Su)?ueries


SELECT last_name, $o%_id, salary FROM employees STQCLE N 12ERE $o%_id 3 "SELECT $o%_id FROM employees 12ERE employee_id 3 5&33 &(, salary ? "SELECT salary FROM employees 12ERE employee_id 3

H #

H3#;

&-%

Copyright Oracle Corporation, 2001. All rights reserved.

E(ecuting Single- o! Su)?ueries + SELECT statement can be considered as a 8uery block" The e$ample on the slide displays employees whose Aob #7 is the same as that of employee 545 and whose salary is greater than that of employee 54/" The e$ample consists of three 8uery blocks& the outer 8uery and two inner 8ueries" The inner 8uery blocks are e$ecuted first% producing the 8uery results )TK;L?J= and 2600% respecti'ely" The outer 8uery block is then processed and uses the 'alues returned by the inner 8ueries to complete its search conditions" ,oth inner 8ueries return single 'alues )TK;L?J= and 2600% respecti'ely!% so this )*L statement is called a single-row sub8uery" Note: The outer and inner 8ueries can get data from different tables"

"ntroduction to $racle%i: SQL &-%

2sing Croup Functions in a Su)?uer*


SELECT last_name, $o%_id, salary FROM employees 5533 12ERE salary 3 "SELECT M-("salary# FROM employees#;

&-13

Copyright Oracle Corporation, 2001. All rights reserved.

2sing Croup Functions in a Su)?uer* You can display data from a main 8uery by using a group function in a sub8uery to return a single row" The sub8uery is in parentheses and is placed after the comparison condition" The e$ample on the slide displays the employee last name% Aob #7% and salary of all employees whose salary is e8ual to the minimum salary" The MIN group function returns a single 'alue 2500! to the outer 8uery"

"ntroduction to $racle%i: SQL &-13

The 2&Q-(@ Clause !ith Su)?ueries

The $racle ser1er e(ecutes su)?ueries first+ The $racle ser1er returns results into the 2&Q-(@ clause of the main ?uer*+
SELECT FROM @RO9> .A 2&Q-(@ department_id, M-("salary# employees department_id 5533 M-("salary# ? "SELECT M-("salary# FROM employees 12ERE department_id 3 :0#;

&-11

Copyright Oracle Corporation, 2001. All rights reserved.

The 2&Q-(@ Clause !ith Su)?ueries You can use sub8ueries not only in the &=ERE clause% but also in the =A$ING clause" The 3racle ser'er e$ecutes the sub8uery% and the results are returned into the =A$ING clause of the main 8uery" The )*L statement on the slide displays all the departments that ha'e a minimum salary greater than that of department 50"

'
Example (ind the Aob with the lowest a'erage salary" SELECT ROM GRO#P 5' =A$ING ;o<_id, A$G,!alar+/ emplo+ee! ;o<_id A$G,!alar+/ : ,SELECT MIN,A$G,!alar+// ROM emplo+ee! GRO#P 5' ;o<_id/" "ntroduction to $racle%i: SQL &-11

What is Wrong !ith this StatementM


SELECT employee_id, last_name FROM employees 12ERE salary 3 "SELECT M-("salary# FROM employees @RO9> .A department_id#; ERROR at line HR OR&J0 H!MR sin;leJroF s)%E)ery ret)rns more t5an one roF

Single-ro! operator !ith multiple-ro! su)?uer*


&-15 Copyright Oracle Corporation, 2001. All rights reserved.

Errors !ith Su)?ueries 3ne common error with sub8ueries is more than one row returned for a single-row sub8uery" #n the )*L statement on the slide% the sub8uery contains a GRO#P 5' clause% which implies that the sub8uery will return multiple rows% one for each group it finds" #n this case% the result of the sub8uery will be 4400% 6000% 2500% 4200% E000% 5E000% and L/00" The outer 8uery takes the results of the sub8uery 4400% 6000% 2500% 4200% E000% 5E000% L/00! and uses these results in its &=ERE clause" The &=ERE clause contains an e8ual Q! operator% a single- row comparison operator e$pecting only one 'alue" The : operator cannot accept more than one 'alue from the sub8uery and therefore generates the error" To correct this error% change the : operator to IN"

"ntroduction to $racle%i: SQL &-15

Will this Statement

eturn

o!sM

SELECT last_name, $o%_id FROM employees 12ERE $o%_id 3 "SELECT $o%_id FROM employees 12ERE last_name 3 +2aas+#;

no roFs selected

Su)?uer* returns no 1alues

&-18

Copyright Oracle Corporation, 2001. All rights reserved.

4ro)lems !ith Su)?ueries + common problem with sub8ueries is no rows being returned by the inner 8uery" #n the )*L statement on the slide% the sub8uery contains a &=ERE clause" Presumably% the intention is to find the employee whose name is <aas" The statement is correct but selects no rows when e$ecuted" There is no employee named <aas" )o the sub8uery returns no rows" The outer 8uery takes the results of the sub8uery null! and uses these results in its &=ERE clause" The outer 8uery finds no employee with a Aob #7 e8ual to null% and so returns no rows" #f a Aob e$isted with a 'alue of null% the row is not returned because comparison of two null 'alues yields a null% therefore the &=ERE condition is not true"

"ntroduction to $racle%i: SQL &-18

/ultiple- o! Su)?ueries

eturn more than one ro! 2se multiple-ro! comparison operators


$perator -( &(A /eaning E?ual to an* mem)er in the list Compare 1alue to each 1alue returned )* the su)?uer* Compare 1alue to e1er* 1alue returned )* the su)?uer*

&LL

&-1=

Copyright Oracle Corporation, 2001. All rights reserved.

/ultiple- o! Su)?ueries )ub8ueries that return more than one row are called multiple-row sub8ueries" You use a multiple-row operator% instead of a single-row operator% with a multiple-row sub8uery" The multiple-row operator e$pects one or more 'alues" SELECT la!t_name, !alar+, department_id ROM emplo+ee! &=ERE !alar+ IN ,SELECT MIN,!alar+/ ROM emplo+ee! GRO#P 5' department_id/" Example (ind the employees who earn the same salary as the minimum salary for each department" The inner 8uery is e$ecuted first% producing a 8uery result" The main 8uery block is then processed and uses the 'alues returned by the inner 8uery to complete its search condition" #n fact% the main 8uery would appear to the 3racle ser'er as follows& SELECT la!t_name, !alar+, department_id ROM emplo+ee! &=ERE !alar+ IN ,.C**, Z.**, ZZ**, E***, ?***, [)**, [E**, -?***/"

"ntroduction to $racle%i: SQL &-1=

2sing the &(A $perator in /ultiple- o! Su)?ueries


SELECT employee_id, last_name, $o%_id, salary FROM employees %333: &333: =533 12ERE salary 6 &(A "SELECT salary FROM employees 12ERE $o%_id 3 +-T_>RO@+# &(, $o%_id 6? +-T_>RO@+;

'

&-15

Copyright Oracle Corporation, 2001. All rights reserved.

/ultiple- o! Su)?ueries 6continued7 The AN' operator and its synonym% the SOME operator! compares a 'alue to each 'alue returned by a sub8uery" The slide e$ample displays employees who are not #T programmers and whose salary is less than that of any #T programmer" The ma$imum salary that a programmer earns is .4%000" WAN' means less than the ma$imum" XAN' means more than the minimum" QAN' is e8ui'alent to IN" WALL means less than the ma$imum" XALL means more than the minimum"

"nstructor #ote Nhen using SOME or AN'% you often use the DISTINCT keyword to pre'ent rows from being selected se'eral times" "ntroduction to $racle%i: SQL &-15

2sing the &LL $perator in /ultiple- o! Su)?ueries


SELECT employee_id, last_name, $o%_id, salary FROM employees %333: &333: =533 12ERE salary 6 &LL "SELECT salary FROM employees 12ERE $o%_id 3 +-T_>RO@+# &(, $o%_id 6? +-T_>RO@+;

&-1&

Copyright Oracle Corporation, 2001. All rights reserved.

/ultiple- o! Su)?ueries 6continued7 The ALL operator compares a 'alue to e(ery 'alue returned by a sub8uery" The slide e$ample displays employees whose salary is less than the salary of all employees with a Aob #7 of #TKPJ3R and whose Aob is not #TKPJ3R" DALL means more than the ma$imum% and JALL means less than the minimum" The NOT operator can be used with IN% AN'% and ALL operators"

"ntroduction to $racle%i: SQL &-1&

#ull 9alues in a Su)?uer*

SELECT emp7last_name FROM employees emp 12ERE emp7employee_id (OT -( "SELECT m;r7mana;er_id FROM employees m;r#; no roFs selected

&-1>

Copyright Oracle Corporation, 2001. All rights reserved.

eturning #ulls in the esulting Set of a Su)?uer* The )*L statement on the slide attempts to display all the employees who do not ha'e any subordinates" Logically% this )*L statement should ha'e returned 52 rows" <owe'er% the )*L statement does not return any rows" 3ne of the 'alues returned by the inner 8uery is a null 'alue% and hence the entire 8uery returns no rows" The reason is that all conditions that compare a null 'alue result in a null" )o whene'er null 'alues are likely to be part of the results set of a sub8uery% do not use the NOT IN operator" The NOT IN operator is e8ui'alent to JD ALL" 0otice that the null 'alue as part of the results set of a sub8uery is not a problem if you use the IN operator" The IN operator is e8ui'alent to :AN'" (or e$ample% to display the employees who ha'e subordinates% use the following )*L statement& SELECT emp0la!t_name ROM emplo+ee! emp &=ERE emp0emplo+ee_id IN ,SELECT mgr0manager_id ROM emplo+ee! mgr/" +lternati'ely% a &=ERE clause can be included in the sub8uery to display all employees who do not ha'e any subordinates& SELECT la!t_name ROM emplo+ee! &=ERE emplo+ee_id NOT IN ,SELECT manager_id ROM emplo+ee! &=ERE manager_id IS NOT N#LL/" "ntroduction to $racle%i: SQL &-1>

Summar*

"n this lesson: *ou should ha1e learned ho! to: "dentif* !hen a su)?uer* can help sol1e a ?uestion Write su)?ueries !hen a ?uer* is )ased on un;no!n 1alues
SELECT FROM 12ERE select_list table expr operator "SELECT select_list FROM table#;

&-1@

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* #n this lesson% you should ha'e learned how to use sub8ueries" + sub8uery is a SELECT statement that is embedded in a clause of another )*L statement" )ub8ueries are useful when a 8uery is based on a search criteria with unknown intermediate 'alues" )ub8ueries ha'e the following characteristics& S S S S ;an pass one row of data to a main statement that contains a single-row operator% such as Q% WX% X% XQ% W% or WQ ;an pass multiple rows of data to a main statement that contains a multiple-row operator% such as IN +re processed first by the 3racle ser'er% and the &=ERE or =A$ING clause uses the results ;an contain group functions

"ntroduction to $racle%i: SQL &-1@

4ractice & $1er1ie!


This practice co1ers the follo!ing topics:

Creating su)?ueries to ?uer* 1alues )ased on un;no!n criteria 2sing su)?ueries to find out !hich 1alues e(ist in one set of data and not in another

&-1%

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice & #n this practice% you write comple$ 8ueries using nested SELECT statements" 4aper-Based Questions You may want to create the inner 8uery first for these 8uestions" Make sure that it runs and produces the data that you anticipate before coding the outer 8uery"

"ntroduction to $racle%i: SQL &-1%

4ractice & 5" Nrite a 8uery to display the last name and hire date of any employee in the same department as :lotkey" ?$clude :lotkey"

2" ;reate a 8uery to display the employee numbers and last names of all employees who earn more than the a'erage salary" )ort the results in ascending order of salary"

/" Nrite a 8uery that displays the employee numbers and last names of all employees who work in a department with any employee whose last name contains a u" Place your )*L statement in a te$t file named la<E_)0!1l" Jun your 8uery"

"ntroduction to $racle%i: SQL &-53

4ractice & 6continued7 4" 7isplay the last name% department number% and Aob #7 of all employees whose department location #7 is 5E00"

5" 7isplay the last name and salary of e'ery employee who reports to =ing"

6" 7isplay the department number% last name% and Aob #7 for e'ery employee in the ?$ecuti'e department"

#f you ha'e time% complete the following e$ercises& E" Modify the 8uery in la<E_)0!1l to display the employee numbers% last names% and salaries of all employees who earn more than the a'erage salary and who work in a department with any employee with a u in their name" Jesa'e la<E_)0!1l to la<E_?0!1l" Jun the statement in la<E_?0!1l"

"ntroduction to $racle%i: SQL &-51

"ntroduction to $racle%i: SQL &-55

4roducing eada)le $utput !ith iSQL.4lus

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing
/5 minutes /5 minutes E0 minutes

Topic
Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing:

4roduce ?ueries that re?uire a su)stitution 1aria)le Customi<e the iSQL.4lus en1ironment 4roduce more reada)le output Create and e(ecute script files

>-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim #n this lesson% you will learn how to include i)*LBPlus commands to produce more readable )*L output" You can create a command file containing a &=ERE clause to restrict the rows displayed" To change the condition each time the command file is run% you use substitution 'ariables" )ubstitution 'ariables can replace 'alues in the &=ERE clause% a te$t string% and e'en a column or a table name"

"ntroduction to $racle%i: SQL >-5

Su)stitution 9aria)les

+++ salar* A M ' ' departmentQid A M ' +++ lastQname A M +++

" !ant to ?uer* different 1alues+

2ser

>-8

Copyright Oracle Corporation, 2001. All rights reserved.

Su)stitution 9aria)les The e$amples so far ha'e been hard-coded" #n a finished application% the user would trigger the report% and the report would run without further prompting" The range of data would be predetermined by the fi$ed &=ERE clause in the i)*LBPlus script file" 6sing i)*LBPlus% you can create reports that prompt the user to supply their own 'alues to restrict the range of data returned by using substitution 'ariables" You can embed substitution (ariables in a command file or in a single )*L statement" + 'ariable can be thought of as a container in which the 'alues are temporarily stored" Nhen the statement is run% the 'alue is substituted"

"nstructor #ote 7emo& ?_Karno0!1l% ?_Kar+e!0!1l Purpose& To illustrate returning all rows and using a case-insensiti'e 8uery with substitution 'ariables" Nith i)*LBPlus 4"0"5"0"5% there is a bug when using Zsubstitution and wildcards T! for character 'alues" This bug has been reported" The ?_Kar+e!0!1l will produce an error in i)*LBPlus% but the concept is important for students continuing classes using other products such as (orms% Jeports!" You may want to demonstrate ?_Kar+e!0!1l in the )*LBPlus en'ironment as an option" "ntroduction to $racle%i: SQL >-8

Su)stitution 9aria)les
2se iSQL.4lus su)stitution 1aria)les to:

Temporaril* store 1alues


L Single ampersand 6V7 -ou)le ampersand 6VV7 ,EF-(E command

4ass 1aria)le 1alues )et!een SQL statements -*namicall* alter headers and footers

>-=

Copyright Oracle Corporation, 2001. All rights reserved.

Su)stitution 9aria)les #n i)*LBPlus% you can use single ampersand \! substitution 'ariables to temporarily store 'alues" You can predefine 'ariables in i)*LBPlus by using the DE INE command" DE INE creates and assigns a 'alue to a 'ariable" Examples o/ Restricte& Ran!es o/ Data S S S Jeporting figures only for the current 8uarter or specified date range Jeporting on data rele'ant only to the user re8uesting the report 7isplaying personnel only within a gi'en department

$ther "nteracti1e Effects #nteracti'e effects are not restricted to direct user interaction with the &=ERE clause" The same principles can be used to achie'e other goals" (or e$ample& S S S 7ynamically altering headers and footers 3btaining input 'alues from a file rather than from a person Passing 'alues from one )*L statement to another

i)*LBPlus does not support 'alidation checks e$cept for data type! on user input" "nstructor #ote + substitution 'ariable can be used anywhere in )*L and i)*LBPlus commands% e$cept as the first word entered at the command prompt" "ntroduction to $racle%i: SQL >-=

2sing the V Su)stitution 9aria)le


2se a 1aria)le prefi(ed !ith an ampersand 6V7 to prompt the user for a 1alue+
SELECT FROM 12ERE employee_id, last_name, salary, department_id employees employee_id 3 Vemployee_n)m ;

>-5

Copyright Oracle Corporation, 2001. All rights reserved.

Single-Ampersand Su)stitution 9aria)le Nhen running a report% users often want to restrict the data returned dynamically" i)*LBPlus pro'ides this fle$ibility by means of user 'ariables" 6se an ampersand \! to identify each 'ariable in your )*L statement" You do not need to define the 'alue of each 'ariable" Notation Description
-user"(ariable #ndicates a 'ariable in a )*L statement1 if the 'ariable does not e$ist% i)*LBPlus prompts the user for a 'alue i)*LBPlus discards a new 'ariable once it is used"!

The e$ample on the slide creates an i)*LBPlus substitution 'ariable for an employee number" Nhen the statement is e$ecuted% i)*LBPlus prompts the user for an employee number and then displays the employee number% last name% salary% and department number for that employee" Nith the single ampersand% the user is prompted e'ery time the command is e$ecuted% if the 'ariable does not e$ist"

"ntroduction to $racle%i: SQL >-5

2sing the V Su)stitution 9aria)le

5
0

>-&

Copyright Oracle Corporation, 2001. All rights reserved.

Single-Ampersand Su)stitution 9aria)le Nhen i)*LBPlus detects that the )*L statement contains an \% you are prompted to enter a 'alue for the substitution 'ariable named in the )*L statement" 3nce you enter a 'alue and click the )ubmit for ?$ecution button% the results are displayed in the output area of your i)*LBPlus session"

"ntroduction to $racle%i: SQL >-&

Character and -ate 9alues !ith Su)stitution 9aria)les


2se single ?uotation mar;s for date and character 1alues+
SELECT last_name, department_id, salary* ! FROM employees 12ERE $o%_id 3 +V$o%_title+ ;

>->

Copyright Oracle Corporation, 2001. All rights reserved.

Specif*ing Character and -ate 9alues !ith Su)stitution 9aria)les #n a &=ERE clause% date and character 'alues must be enclosed within single 8uotation marks" The same rule applies to the substitution 'ariables" ?nclose the 'ariable in single 8uotation marks within the )*L statement itself" The slide shows a 8uery to retrie'e the employee names% department numbers% and annual salaries of all employees based on the Aob title 'alue of the i)*LBPlus substitution 'ariable" Note: You can also use functions such as #PPER and LO&ER with the ampersand" 6se #PPER,7\;o<_title7/ so that the user does not ha'e to enter the Aob title in uppercase"

"ntroduction to $racle%i: SQL >->

Specif*ing Column #ames: E(pressions: and Te(t


2se su)stitution 1aria)les to supplement the follo!ing: 12ERE conditions

OR,ER .A clauses Column e(pressions Ta)le names Entire SELECT statements

>-@

Copyright Oracle Corporation, 2001. All rights reserved.

Specif*ing Column #ames: E(pressions: and Te(t 0ot only can you use the substitution 'ariables in the &=ERE clause of a )*L statement% but these 'ariables can also be used to substitute for column names% e$pressions% or te$t" Example 7isplay the employee number and any other column and any condition of employees" SELECT ROM &=ERE emplo+ee_id, \col3mn_name emplo+ee! \condition"

#f you do not enter a 'alue for the substitution 'ariable% you will get an error when you e$ecute the preceding statement" Note: + substitution 'ariable can be used anywhere in the SELECT statement% e$cept as the first word entered at the command prompt" "ntroduction to $racle%i: SQL >-@

Specif*ing Column #ames: E(pressions: and Te(t


SELECT FROM 12ERE OR,ER .A employee_id, last_name, $o%_id, Vcol)mn_name employees Vcondition Vorder_col)mn ;

>-%

Copyright Oracle Corporation, 2001. All rights reserved.

Specif*ing Column #ames: E(pressions: and Te(t 6continued7 The slide e$ample displays the employee number% name% Aob title% and any other column specified by the user at run time% from the EMPLO'EES table" You can also specify the condition for retrie'al of rows and the column name by which the resultant data has to be ordered"

"nstructor #ote 7emo& ?_e>pr0!1l Purpose& To illustrate changing column names and conditions by using substitution 'ariables "ntroduction to $racle%i: SQL >-%

-efining Su)stitution 9aria)les


Eou can predefine 1aria)les using the iSQL.4lus ,EF-(E command+
,EF-(E ariable 3 1aria)le !ith the CHA alue creates a user data t*pe+

"f *ou need to predefine a 1aria)le that includes spaces: *ou must enclose the 1alue !ithin single ?uotation mar;s !hen using the ,EF-(E command+ A defined 1aria)le is a1aila)le for the session

>-13

Copyright Oracle Corporation, 2001. All rights reserved.

-efining Su)stitution 9aria)les You can predefine user 'ariables before e$ecuting a SELECT statement" i)*LBPlus pro'ides the DE INE command for defining and setting substitution 'ariables&
%omman& DE INE variable ' value DE INE variable DE INE Description ;reates a user 'ariable with the C=AR data and assigns a 'alue to it 7isplays the 'ariable% its 'alue% and its data type 7isplays all user 'ariables with their 'alues and data types

"nstructor #ote Mention that i)*LBPlus commands can continue onto multiple lines and that they re8uire the continuation character% the hyphen" "ntroduction to $racle%i: SQL >-13

,EF-(E and 9(,EF-(E Commands


A 1aria)le remains defined until *ou either:
2se the 9(,EF-(E command to clear it E(it iSQL.4lus

Eou can 1erif* *our changes !ith the ,EF-(E command+

,EF-(E $o%_title 3 -T_>RO@ ,EF-(E $o%_title ,EF-(E OO._T-TLE 3 '-T_>RO@' "C2&R# 9(,EF-(E $o%_title ,EF-(E $o%_title S>!J0 3:R sym%ol $o%_title is 9(,EF-(E,

>-11

Copyright Oracle Corporation, 2001. All rights reserved.

The ,EF-(E and 9(,EF-(E Commands Cariables are defined until you either& S #ssue the #NDE INE command on a 'ariable S ?$it i)*LBPlus Nhen you undefine 'ariables% you can 'erify your changes with the DE INE command" Nhen you e$it i)*LBPlus% 'ariables defined during that session are lost"

"ntroduction to $racle%i: SQL >-11

2sing the ,EF-(E Command !ith V Su)stitution 9aria)le


Create the su)stitution 1aria)le using the ,EF-(E command+ 2se a 1aria)le prefi(ed !ith an ampersand 6V7 to su)stitute the 1alue in the SQL statement+

,EF-(E employee_n)m 3 !00

SELECT employee_id, last_name, salary, department_id FROM employees 12ERE employee_id 3 Vemployee_n)m ;

>-15

Copyright Oracle Corporation, 2001. All rights reserved.

2sing the ,EF-(E Command The e$ample on the slide creates an i)*LBPlus substitution 'ariable for an employee number by using the DE INE command% and at run time displays the employee number% name% salary% and department number for that employee" ,ecause the 'ariable is created using the i)*LBPlus DE INE command% the user is not prompted to enter a 'alue for the employee number" #nstead% the defined 'ariable 'alue is automatically substituted in the SELECT statement" The EMPLO'EE_N#M substitution 'ariable is present in the session until the user undefines it or e$its the i)*LBPlus session"

"ntroduction to $racle%i: SQL >-15

2sing the VV Su)stitution 9aria)le


2se the dou)le-ampersand 6VV7 if *ou !ant to reuse the 1aria)le 1alue !ithout prompting the user each time+
SELECT employee_id, last_name, $o%_id, VVcol)mn_name FROM employees OR,ER .A Vcol)mn_name;

'
>-18 Copyright Oracle Corporation, 2001. All rights reserved.

-ou)le-Ampersand Su)stitution 9aria)le You can use the double-ampersand \\! substitution 'ariable if you want to reuse the 'ariable 'alue without prompting the user each time" The user will see the prompt for the 'alue only once" #n the e$ample on the slide% the user is asked to gi'e the 'alue for 'ariable column"name only once" The 'alue supplied by the user departmentKid! is used both for display and ordering of data" i)*LBPlus stores the 'alue supplied by using the DE INE command1 it will use it again whene'er you reference the 'ariable name" 3nce a user 'ariable is in place% you need to use the #NDE INE command to delete it"

"ntroduction to $racle%i: SQL >-18

2sing the QER-FA Command


2se the QER-FA command to toggle the displa* of the su)stitution 1aria)le: )efore and after iSQL.4lus replaces su)stitution 1aria)les !ith 1alues+
SET QER-FA O( SELECT employee_id, last_name, salary, department_id FROM employees 12ERE employee_id 3 Vemployee_n)m;

old neF

3R 12ERE 3R 12ERE

employee_id 3 Vemployee_n)m employee_id 3 !00

>-1=

Copyright Oracle Corporation, 2001. All rights reserved.

The QER-FA Command To confirm the changes in the )*L statement% use the i)*LBPlus $ERI ' command" )etting SET $ERI ' ON forces i)*LBPlus to display the te$t of a command before and after it replaces substitution 'ariables with 'alues" The e$ample on the slide displays the old as well as the new 'alue of the EMPLO'EE_ID column"

"ntroduction to $racle%i: SQL >-1=

Customi<ing the iSQL.4lus En1ironment


2se SET commands to control current session+
SET system_ ariable alue

9erif* !hat *ou ha1e set )* using the S2O1 command+

SET EC2O O( S2O1 EC2O ec5o O(

>-15

Copyright Oracle Corporation, 2001. All rights reserved.

Customi<ing the iSQL.4lus En1ironment You can control the en'ironment in which i)*LBPlus is currently operating by using the SET commands" Syntax SET s$stem_variable value #n the synta$& s$stem_variable value is a 'ariable that controls one aspect of the session en'ironment is a 'alue for the system 'ariable

You can 'erify what you ha'e set by using the S=O& command" The S=O& command on the slide checks whether EC=O had been set on or off" To see all SET 'ariable 'alues% use the S=O& ALL command" (or more information% see iSQL./lus ,ser0s 1uide and Reference% >;ommand Jeference"@

"ntroduction to $racle%i: SQL >-15

SET Command 9aria)les

&RR&AS-WE FEE,.&C8 2E&,-(@ LO(@

B!0 * nC BG * n *OFF * O(C BOFF * O(C

BP0 * nC* O( * textC

SET 2E&,-(@ OFF S2O1 2E&,-(@ 2E&,-(@ OFF

>-1&

Copyright Oracle Corporation, 2001. All rights reserved.

SET Command 9aria)les


SET 0ariable an& 0alues ARRA'PSIXEQ R.*6 nS EEDP5AC2Q RE6n6O 6ONS =EAPDINGQ RO LONG R[*6nS 6ONS Description )ets the database data fetch si9e 7isplays the number of records returned by a 8uery when the 8uery selects at least n records 7etermines whether column headings are displayed in reports )ets the ma$imum width for displaying LONG 'alues

Note: The 'alue n represents a numeric 'alue" The underlined 'alues indicate default 'alues" #f you enter no 'alue with the 'ariable% i)*LBPlus assumes the default 'alue"

"ntroduction to $racle%i: SQL >-1&

iSQL.4lus Format Commands COL9M( TT-TLE .T-TLE .RE&8

/column option0 /text * OFF * O(0 /text * OFF * O(0 /O( report_element0

>-1>

Copyright Oracle Corporation, 2001. All rights reserved.

$)taining /ore eada)le eports You can control the report features by using the following commands&
%omman& COLP#MNQPcolumn optionQ TTIPTLEQ Ptext6O 5TIPTLEQ Ptext6O 5REPA2Q PON report_elementQ 6ONQ 6ONQ Description ;ontrols column formats )pecifies a header to appear at the top of each page of the report )pecifies a footer to appear at the bottom of each page of the report )uppresses duplicate 'alues and di'ides rows of data into sections by using line breaks

+ui&elines S S S S +ll format commands remain in effect until the end of the i)*LBPlus session or until the format setting is o'erwritten or cleared" Jemember to reset your i)*LBPlus settings to the default 'alues after e'ery report" There is no command for setting an i)*LBPlus 'ariable to its default 'alue1 you must know the specific 'alue or log out and log in again" #f you gi'e an alias to your column% you must reference the alias name% not the column name" "ntroduction to $racle%i: SQL >-1>

The COL9M( Command


Controls displa* of a column:
COL/9M(0 /Bcolumn*aliasC /option00

CLE/&R0: Clears an* column formats 2E&/,-(@0 text: Sets the column heading FOR/M&T0 format: Changes the displa* of the column using a format model (O>R-(T * >R-(T (9LL

>-1@

Copyright Oracle Corporation, 2001. All rights reserved.

COL9M( Command $ptions


Option CLEPARQ =EAPDINGQ text ORPMATQ format NOPRIPNTQ N#LPLQ text PRIPNTQ Description ;lears any column formats )ets the column heading a 'ertical line U! forces a line feed in the heading if you do not use Austification"! ;hanges the display of the column data <ides the column )pecifies te$t to be displayed for null 'alues )hows the column

"ntroduction to $racle%i: SQL >-1@

2sing the COL9M( Command


Create column headings+
COL9M( last_name 2E&,-(@ +Employee*(ame+ COL9M( salary O9ST-FA LEFT FORM&T S44,440700 COL9M( mana;er FORM&T 444444444 (9LL +(o mana;er+

-ispla* the current setting for the L&ST_(&ME column+


COL9M( last_name

Clear settings for the L&ST_(&ME column+


COL9M( last_name CLE&R

>-1%

Copyright Oracle Corporation, 2001. All rights reserved.

-ispla*ing or Clearing Settings To show or clear the current COL#MN command settings% use the following commands&
%omman& COLP#MNQ column COLP#MNQ COLP#MNQ col3mn CLEPARQ CLEPARQ COLP#MNQ Description 7isplays the current settings for the specified column 7isplays the current settings for all columns ;lears the settings for the specified column ;lears the settings for all columns

"ntroduction to $racle%i: SQL >-1%

COL9M( Format /odels

Element %

-escription Single <ero-suppression digit Enforces leading <ero Floating dollar sign Local currenc* 4osition of decimal point Thousand separator

E(ample %%%%%%

esult 158=

3 I L + :

3%%%%% I%%%% L%%%% %%%%+%% %:%%%

33158= I158= L158= 158=+33 1:58=

>-53

Copyright Oracle Corporation, 2001. All rights reserved.

COL9M( Format /odels The slide displays sample COL#MN format models" The 3racle ser'er displays a string of pound signs @! in place of a whole number whose digits e$ceed the number of digits pro'ided in the format model" #t also displays pound signs in place of a 'alue whose format model is alphanumeric but whose actual 'alue is numeric"

"ntroduction to $racle%i: SQL >-53

2sing the .RE&8 Command

2se the .RE&8 command to suppress duplicates+


.RE&8 O( $o%_id

>-51

Copyright Oracle Corporation, 2001. All rights reserved.

The .RE&8 Command 6se the 5REA2 command to di'ide rows into sections and suppress duplicate 'alues" To ensure that the 5REA2 command works effecti'ely% use the ORDER 5' clause to order the columns that you are breaking on" Syntax 5REA2 on col3mnP6alia!6roIQ #n the synta$& col3mnP6alia!6roI suppresses the display of duplicate 'alues for a gi'en column

;lear all 5REA2 settings by using the CLEAR command& CLEAR 5REA2

"ntroduction to $racle%i: SQL >-51

2sing the TT-TLE and .T-TLE Commands


-ispla* headers and footers+

TT-/TLE0 /text*OFF*O(0

Set the report header+

TT-TLE +Salary*Report+

Set the report footer+

.T-TLE +Con=idential+

>-55

Copyright Oracle Corporation, 2001. All rights reserved.

The TT-TLE and .T-TLE Commands 6se the TTITLE command to format page headers and the 5TITLE command for footers" (ooters appear at the bottom of the page" The synta$ for 5TITLE and TTITLE is identical" 3nly the synta$ for TTITLE is shown" You can use the 'ertical bar U! to split the te$t of the title across se'eral lines" Syntax TTIPTLEQ65TIPTLEQ Ptext6O #n the synta$& te%t O 6ON represents the title te$t enter single 8uotes if the te$t is more than one word!" toggles the title either off or on" #t is not 'isible when turned off" 6ONQ

The TTITLE e$ample on the slide sets the report header to display )alary centered on one line and Jeport centered below it" The 5TITLE e$ample sets the report footer to display ;onfidential" TTITLE automatically puts the date and a page number on the report"

"ntroduction to $racle%i: SQL >-55

The TT-TLE and .T-TLE Commands 6continued7 Note: The slide gi'es an abridged synta$ for TTITLE and 5TITLE" Carious options for TTITLE and 5TITLE are co'ered in another )*L course" "nstructor #ote )*LBPlus /"/ introduced the commands REP=EADER and REP OOTER" REP=EADER places and formats a specified report header at the top of each report or lists the current REP=EADER definition" REP OOTER places and formats a specified report footer at the bottom of each report or lists the current REP OOTER definition"

"ntroduction to $racle%i: SQL >-58

Creating a Script File to un a eport


1+ Create and test the SQL SELECT statement+ 5+ Sa1e the SELECT statement into a script file+ 8+ Load the script file into an editor+ =+ Add formatting commands )efore the SELECT statement+ 5+ 9erif* that the termination character follo!s the SELECT statement+

>-5=

Copyright Oracle Corporation, 2001. All rights reserved.

Creating a Script File to un a eport You can either enter each of the i)*LBPlus commands at the )*L prompt or put all the commands% including the SELECT statement% in a command or script! file" + typical script consists of at least one SELECT statement and se'eral i)*LBPlus commands" 7o" to %reate a Script File 5" ;reate the )*L SELECT statement at the )*L prompt" ?nsure that the data re8uired for the report is accurate before you sa'e the statement to a file and apply formatting commands" ?nsure that the rele'ant ORDER 5' clause is included if you intend to use breaks" 2" )a'e the SELECT statement to a script file" /" ?dit the script file to enter the i)*LBPlus commands" 4" +dd the re8uired formatting commands before the SELECT statement" ,e certain not to place i)*LBPlus commands within the SELECT statement" 5" Cerify that the SELECT statement is followed by a run character% either a semicolon "! or a slash Y!"

"ntroduction to $racle%i: SQL >-5=

Creating a Script File to un a eport


&+ Clear formatting commands after the SELECT statement+ >+ Sa1e the script file+ @+ Load the script file into the iSQL.4lus te(t !indo!: and clic; the E(ecute )utton+

>-55

Copyright Oracle Corporation, 2001. All rights reserved.

7o" to %reate a Script File -continue&! 6" +dd the format-clearing i)*LBPlus commands after the run character" +lternati'ely% you can store all the format-clearing commands in a reset file" E" )a'e the script file with your changes" L" Load the script file into the i)*LBPlus te$t window% and click the ?$ecute button" +ui&elines S S S You can include blank lines between i)*LBPlus commands in a script" #f you ha'e a lengthy i)*LBPlus or )*LBPlus command% you can continue it on the ne$t line by ending the current line with a hyphen A!" You can abbre'iate i)*LBPlus commands"

S #nclude reset commands at the end of the file to restore the original i)*LBPlus en'ironment" Note: REM represents a remark or comment in i)*LBPlus"

"ntroduction to $racle%i: SQL >-55

Sample

eport

'

>-5&

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample ;reate a script file to create a report that displays the Aob #7% last name% and salary for e'ery employee whose salary is less than .55%000" +dd a centered% two-line header that reads >Emplo+ee Report@ and a centered footer that reads >ConUidential0@ Jename the Aob title column to read >4o< Categor+@ split o'er two lines" Jename the employee name column to read >Emplo+ee0@ Jename the salary column to read >Salar+@ and format it as .2%500"00"

"ntroduction to $racle%i: SQL >-5&

E(ample 6continued7
SET EED5AC2 O TTITLE 7Emplo+ee6Report7 5TITLE 7ConUidential7 5REA2 ON ;o<_id COL#MN ;o<_id =EADING 74o<6Categor+7 COL#MN la!t_name =EADING 7Emplo+ee7 COL#MN !alar+ =EADING 7Salar+7 ORMAT ]BB,BBB0BB REM ** In!ert SELECT !tatement SELECT ;o<_id, la!t_name, !alar+ ROM emplo+ee! &=ERE !alar+ J -C*** ORDER 5' ;o<_id, la!t_name Y REM clear all Uormatting command! 000 SET EED5AC2 ON COL#MN ;o<_id CLEAR COL#MN la!t_name CLEAR COL#MN !alar+ CLEAR CLEAR 5REA2 000

"ntroduction to $racle%i: SQL >-5>

Summar*
"n this lesson: *ou should ha1e learned ho! to:

2se iSQL.4lus su)stitution 1aria)les to store 1alues temporaril* 2se SET commands to control the current iSQL.4lus en1ironment 2se the COL9M( command to control the displa* of a column 2se the .RE&8 command to suppress duplicates and di1ide ro!s into sections 2se the TT-TLE and .T-TLE commands to displa* headers and footers
Copyright Oracle Corporation, 2001. All rights reserved.

>-5@

Summar* #n this lesson% you should ha'e learned about substitution 'ariables and how useful they are for running reports" They gi'e you the fle$ibility to replace 'alues in a &=ERE clause% column names% and e$pressions" You can customi9e reports by writing script files with& S S S S S )ingle ampersand substitution 'ariables 7ouble ampersand substitution 'ariables The DE INE command The #NDE INE command )ubstitution 'ariables in the command line

You can create a more readable report by using the following commands& O COL#MN O TTITLE O 5TITLE O 5REA2

"ntroduction to $racle%i: SQL >-5@

4ractice > $1er1ie!


This practice co1ers the follo!ing topics:

Creating a ?uer* to displa* 1alues using su)stitution 1aria)les Starting a command file containing 1aria)les

>-5%

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice > $1er1ie! This practice gi'es you the opportunity to create files that can be run interacti'ely by using substitution 'ariables to create run-time selection criteria"

"ntroduction to $racle%i: SQL >-5%

4ractice > 7etermine whether the following two statements are true or false& 5" The following statement is 'alid& DE INE \ p_Kal : -** TrueH(alse 2" The DE INE command is a )*L command" TrueH(alse /" Nrite a script to display the employee last name% Aob% and hire date for all employees who started between a gi'en range" ;oncatenate the name and Aob together% separated by a space and comma% and label the column ?mployees" #n a separate )*L script file% use the DE INE command to pro'ide the two ranges" 6se the format MMH77HYYYY" )a'e the script files as la<?_)a0!1l and la<?_)<0!1l" DE INE loI_date : *-Y*-Y-BB[ DE INE 9ig9_date : *-Y*-Y-BBB

4" Nrite a script to display the last names% Aob #7s% and department names for e'ery employee in a gi'en location" The search condition should allow for case-insensiti'e searches of the department location" )a'e the script file as la<?_Z0!1l"

"ntroduction to $racle%i: SQL >-83

4ractice > 6continued7 5" Modify the code in la<?_Z0!1l to create a report containing the department name% employee last name% hire date% salary% and annual salary for each employee in a gi'en location" Label the columns DEPARTMENT NAME% EMPLO'EE NAME% START DATE% SALAR'% and ANN#AL SALAR'% placing the labels on multiple lines" Jesa'e the script as la<?_C0!1l% and e$ecute the commands in the script"

"ntroduction to $racle%i: SQL >-81

"ntroduction to $racle%i: SQL >-85

/anipulating -ata

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing 60 minutes /0 minutes 40 minutes

Topic Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing: -escri)e each -/L statement

"nsert ro!s into a ta)le 2pdate ro!s in a ta)le -elete ro!s from a ta)le /erge ro!s in a ta)le Control transactions

@-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim #n this lesson% you learn how to insert rows into a table% update e$isting rows in a table% and delete e$isting rows from a table" You also learn how to control transactions with the COMMIT% SA$EPOINT% and ROLL5AC2 statements"

"ntroduction to $racle%i: SQL @-5

-ata /anipulation Language

A -/L statement is e(ecuted !hen *ou:


Add ne! ro!s to a ta)le /odif* e(isting ro!s in a ta)le emo1e e(isting ro!s from a ta)le

A transaction consists of a collection of -/L statements that form a logical unit of !or;+

@-8

Copyright Oracle Corporation, 2001. All rights reserved.

-ata /anipulation Language 7ata manipulation language 7ML! is a core part of )*L" Nhen you want to add% update% or delete data in the database% you e$ecute a 7ML statement" + collection of 7ML statements that form a logical unit of work is called a transaction" ;onsider a banking database" Nhen a bank customer transfers money from a sa'ings account to a checking account% the transaction might consist of three separate operations& decrease the sa'ings account% increase the checking account% and record the transaction in the transaction Aournal" The 3racle ser'er must guarantee that all three )*L statements are performed to maintain the accounts in proper balance" Nhen something pre'ents one of the statements in the transaction from e$ecuting% the other statements of the transaction must be undone"

"nstructor #ote 7ML statements can be issued directly in i)*LBPlus% performed automatically by tools such as 3racle (orms )er'ices% or programmed with tools such as the /RL precompilers" ?'ery table has INSERT% #PDATE% and DELETE pri'ileges associated with it" These pri'ileges are automatically granted to the creator of the table% but in general they must be e$plicitly granted to other users" )tarting with 3racle E"2% you can place a sub8uery in the place of the table name in an #PDATE statement% essentially the same way you use a 'iew" "ntroduction to $racle%i: SQL @-8

Adding a #e!
,E>&RTME(TS

o! to a Ta)le
#e! ro! 'insert a ne! ro! into the ,E>&RME(TS ta)le'

@-=

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a #e! o! to a Ta)le The slide graphic illustrates adding a new department to the DEPARTMENTS table"

"ntroduction to $racle%i: SQL @-=

The -(SERT Statement S*nta(


Add ne! ro!s to a ta)le )* using the -(SERT statement+
table /"column /, column...0#0 ( alue /, alue...0#;

-(SERT -(TO Q&L9ES

$nl* one ro! is inserted at a time !ith this s*nta(+

@-5

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a #e! o! to a Ta)le 6continued7 You can add new rows to a table by issuing the INSERT statement" #n the synta$& table column (alue is the name of the table is the name of the column in the table to populate is the corresponding 'alue for the column

Note: This statement with the $AL#ES clause adds only one row at a time to a table"

"ntroduction to $racle%i: SQL @-5

"nserting #e!

o!s

"nsert a ne! ro! containing 1alues for each column+ List 1alues in the default order of the columns in the ta)le+ $ptionall*: list the columns in the -(SERT clause+

-(SERT -(TO departments"department_id, department_name, mana;er_id, location_id# Q&L9ES "M0, +>)%lic Relations+, 00, M00#; roF created7

Enclose character and date 1alues !ithin single ?uotation mar;s+

@-&

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a #e!

o! to a Ta)le 6continued7

,ecause you can insert a new row that contains 'alues for each column% the column list is not re8uired in the INSERT clause" <owe'er% if you do not use the column list% the 'alues must be listed according to the default order of the columns in the table% and a 'alue must be pro'ided for each column" DESCRI5E department!

(or clarity% use the column list in the INSERT clause" ?nclose character and date 'alues within single 8uotation marks1 it is not recommended to enclose numeric 'alues within single 8uotation marks" 0umber 'alues should not be enclosed in single 8uotes% because implicit con'ersion may take place for numeric 'alues assigned to N#M5ER data type columns if single 8uotes are included"

"ntroduction to $racle%i: SQL @-&

"nserting

o!s !ith #ull 9alues

"mplicit method: $mit the column from the column list+


#

-(SERT -(TO

departments "department_id, department_name Q&L9ES "30, +>)rc5asin;+#; roF created7

E(plicit method: Specif* the (9LL ;e*!ord in the Q&L9ES clause+

-(SERT -(TO departments Q&L9ES " 00, +Finance+, (9LL, (9LL#; roF created7

@->

Copyright Oracle Corporation, 2001. All rights reserved.

/ethods for "nserting #ull 9alues #etho& Description #mplicit ?$plicit 3mit the column from the column list" )pecify the N#LL keyword in the $AL#ES list% specify the empty string 77! in the $AL#ES list for character strings and dates"

,e sure that you can use null 'alues in the targeted column by 'erifying the N3llW status with the i)*LBPlus DESCRI5E command" The 3racle )er'er automatically enforces all data types% data ranges% and data integrity constraints" +ny column that is not listed e$plicitly obtains a null 'alue in the new row" ;ommon errors that can occur during user input& S S S S S Mandatory 'alue missing for a NOT N#LL column 7uplicate 'alue 'iolates uni8ueness constraint (oreign key constraint 'iolated 7ata type mismatch Calue too wide to fit in column

O C=EC2 constraint 'iolated

"ntroduction to $racle%i: SQL @->

"nserting Special 9alues


The SAS,&TE function records the current date and time+
-(SERT -(TO employees "employee_id, =irst_name, last_name, email, p5one_n)m%er, 5ire_date, $o%_id, salary, commission_pct, mana;er_id, department_id# Q&L9ES " 3, +Lo)is+, +>opp+, +L>O>>+, +: :7 !H7H:GM+, SAS,&TE, +&C_&CCO9(T+, G400, (9LL, !0:, 00#; roF created7

@-@

Copyright Oracle Corporation, 2001. All rights reserved.

"nserting Special 9alues )* 2sing SQL Functions You can use functions to enter special 'alues in your table" The slide e$ample records information for employee Popp in the EMPLO'EES table" #t supplies the current date and time in the =IRE_DATE column" #t uses the S'SDATE function for current date and time" You can also use the #SER function when inserting rows in a table" The #SER function records the current username" %on/irmin! A&&itions to the Table SELECT emplo+ee_id, la!t_name, ;o<_id, 9ire_date, commi!!ion_pct ROM emplo+ee! &=ERE emplo+ee_id : --)"

"ntroduction to $racle%i: SQL @-@

"nserting Specific -ate 9alues

Add a ne! emplo*ee+

-(SERT -(TO employees Q&L9ES " H, +,en+, +Rap5ealy+, +,R&>2E&L+, +: :7 !M7H:G +, TO_,&TE"+FE. 3, 444+, +MO( ,,, AAAA+#, +&C_&CCO9(T+, 000, (9LL, 00, 30#; roF created7

9erif* *our addition+

@-%

Copyright Oracle Corporation, 2001. All rights reserved.

"nserting Specific -ate and Time 9alues The DDAMONA'' format is usually used to insert a date 'alue" Nith this format% recall that the century defaults to the current century" ,ecause the date also contains time information% the default time is midnight 00&00&00!" #f a date must be entered in a format other than the default format% for e$ample% with another century% or a specific time% you must use the TO_DATE function" The e$ample on the slide records information for employee Japhealy in the EMPLO'EES table" #t sets the =IRE_DATE column to be (ebruary /% 5444" #f you use the following statement instead of the one shown on the slide% the year of the hireKdate is interpreted as 2044" INSERT INTO emplo+ee! $AL#ES ,--Z, 7Den7, 7Rap9eal+7, 7DRAP=EAL7, 7C-C0-.?0ZCE-7, 7*)A E5ABB7, 7AC_ACCO#NT7, --***, N#LL, -**, )*/" #f the RR format is used% the system pro'ides the correct century automatically% e'en if it is not the current one" "nstructor #ote The default date format in 3racle4i is DDAMONARR" Prior to release L"56% the default format was DDAMONA''" "ntroduction to $racle%i: SQL @-%

Creating a Script

2se R su)stitution in a SQL statement to prompt for 1alues+ V is a placeholder for the 1aria)le 1alue+
"department_id, department_name, location_id# "Vdepartment_id, +Vdepartment_name+,Vlocation#;

-(SERT -(TO departments Q&L9ES

roF created7
@-13 Copyright Oracle Corporation, 2001. All rights reserved.

Creating a Script to /anipulate -ata You can sa'e commands with substitution 'ariables to a file and e$ecute the commands in the file" The e$ample abo'e records information for a department in the DEPARTMENTS table" Jun the script file and you are prompted for input for the Z substitution 'ariables" The 'alues you input are then substituted into the statement" This allows you to run the same script file o'er and o'er% but supply a different set of 'alues each time you run it"

"nstructor #ote ,e sure to mention the following points about the script& S S 7o not prefi$ the i)*LBPlus substitution parameter with the ampersand in the DE INE command" 6se a dash to continue an i)*LBPlus command on the ne$t line" "ntroduction to $racle%i: SQL @-13

Cop*ing o!s from Another Ta)le


Write *our -(SERT statement !ith a su)?uer*+
-(SERT -(TO sales_reps"id, name, salary, commission_pct# SELECT employee_id, last_name, salary, commission_pct FROM employees 12ERE $o%_id L-8E +<RE><+; H roFs created7

-o not use the Q&L9ES clause+ /atch the num)er of columns in the -(SERT clause to those in the su)?uer*+

@-11

Copyright Oracle Corporation, 2001. All rights reserved.

Cop*ing o!s from Another Ta)le You can use the INSERT statement to add rows to a table where the 'alues are deri'ed from e$isting tables" #n place of the $AL#ES clause% you use a sub8uery" Syntax INSERT INTO table P column ,, column/ Q sub3uer$4 #n the synta$& table column sub3uer$ is the table name is the name of the column in the table to populate is the sub8uery that returns rows into the table

The number of columns and their data types in the column list of the INSERT clause must match the number of 'alues and their data types in the sub8uery" To create a copy of the rows of a table% use SELECT B in the sub8uery" INSERT INTO cop+_emp SELECT * ROM emplo+ee!" (or more information% see Oracle9i SQL Reference% >SELECT%@ sub8ueries section" "nstructor #ote Please run the script [_creta<!0!1l to create the COP'_EMP and SALES_REPS tables before demonstrating the code e$amples" 7o not get into too many details on copying rows from another table" "ntroduction to $racle%i: SQL @-11

Changing -ata in a Ta)le


EM>LOAEES

2pdate ro!s in the EM>LOAEES ta)le+

@-15

Copyright Oracle Corporation, 2001. All rights reserved.

Changing -ata in a Ta)le The slide graphic illustrates changing the department number for employees in department 60 to department /0"

"ntroduction to $racle%i: SQL @-15

The 9>,&TE Statement S*nta(


/odif* e(isting ro!s !ith the 9>,&TE statement+
table column 3 alue /, column 3 condition0; alue, ...0

9>,&TE SET /12ERE

2pdate more than one ro! at a time: if re?uired+

@-18

Copyright Oracle Corporation, 2001. All rights reserved.

2pdating o!s You can modify e$isting rows by using the #PDATE statement" #n the synta$& table column value condition is the name of the table is the name of the column in the table to populate is the corresponding 'alue or sub8uery for the column identifies the rows to be updated and is composed of column names e$pressions% constants% sub8ueries% and comparison operators

;onfirm the update operation by 8uerying the table to display the updated rows" (or more information% see Oracle9i SQL Reference% >#PDATE"@ Note: #n general% use the primary key to identify a single row" 6sing other columns can une$pectedly cause se'eral rows to be updated" (or e$ample% identifying a single row in the EMPLO'EES table by name is dangerous% because more than one employee may ha'e the same name"

"ntroduction to $racle%i: SQL @-18

2pdating

o!s in a Ta)le

Specific ro! or ro!s are modified if *ou specif* the 12ERE clause+
9>,&TE employees SET department_id 3 M0 12ERE employee_id 3 3; roF )pdated7

All ro!s in the ta)le are modified if *ou omit the 12ERE clause+
9>,&TE copy_emp SET department_id 3 !! roFs )pdated7 0;

@-1=

Copyright Oracle Corporation, 2001. All rights reserved.

2pdating o!s 6continued7 The #PDATE statement modifies specific rows if the &=ERE clause is specified" The slide e$ample transfers employee 55/ Popp! to department E0" #f you omit the &=ERE clause% all the rows in the table are modified" SELECT la!t_name, department_id ROM cop+_emp"

'

Note: The COP'_EMP table has the same data as the EMPLO'EES table" "ntroduction to $racle%i: SQL @-1=

2pdating T!o Columns !ith a Su)?uer*

2pdate emplo*ee 11=Ps Go) and salar* to match that of emplo*ee 535+
9>,&TE SET employees $o%_id 3 "SELECT FROM 12ERE salary 3 "SELECT FROM 12ERE 12ERE employee_id 3 roF )pdated7 $o%_id employees employee_id 3 !0:#, salary employees employee_id 3 !0:# H;

@-15

Copyright Oracle Corporation, 2001. All rights reserved.

2pdating T!o Columns !ith a Su)?uer* You can update multiple columns in the SET clause of an #PDATE statement by writing multiple sub8ueries" Syntax #PDATE table SET column

: ,SELECT column ROM table &=ERE condition/

P , column

P&=ERE

,SELECT column ROM table &=ERE condition/Q condition Q "

Note: #f no rows are updated% a message >* roI! 3pdated"@ is returned"

"ntroduction to $racle%i: SQL @-15

2pdating o!s Based on Another Ta)le


2se su)?ueries in 9>,&TE statements to update ro!s in a ta)le )ased on 1alues from another ta)le+
9>,&TE SET 12ERE copy_emp department_id $o%_id 3 3 "SELECT department_id FROM employees 12ERE employee_id 3 00# "SELECT $o%_id FROM employees 12ERE employee_id 3 !00#;

roF )pdated7

@-1&

Copyright Oracle Corporation, 2001. All rights reserved.

2pdating o!s Based on Another Ta)le You can use sub8ueries in #PDATE statements to update rows in a table" The e$ample on the slide updates the COP'_EMP table based on the 'alues from the EMPLO'EES table" #t changes the department number of all employees with employee 200Gs Aob #7 to employee 500Gs current department number"

"ntroduction to $racle%i: SQL @-1&

2pdating o!s: "ntegrit* Constraint Error

9>,&TE employees SET department_id 3 :: 12ERE department_id 3 0; 9>,&TE employees * ERROR at line R OR&J0!!4 R inte;rity constraint "2R7EM>_,E>T_F8# Uiolated J parent Key not =o)nd

-epartment num)er 55 does not e(ist

@-1>

Copyright Oracle Corporation, 2001. All rights reserved.

"ntegrit* Constraint Error #f you attempt to update a record with a 'alue that is tied to an integrity constraint% an error is returned" #n the e$ample on the slide% department number 55 does not e$ist in the parent table% DEPARTMENTS% and so you recei'e the parent 2ey 'iolation ORAA*..B-" Note: #ntegrity constraints ensure that the data adheres to a predefined set of rules" + subse8uent lesson co'ers integrity constraints in greater depth"

"nstructor #ote ?$plain integrity constraints% and re'iew the concepts of primary key and foreign key" "ntroduction to $racle%i: SQL @-1>

emo1ing a
,E>&RTME(TS

o! from a Ta)le

-elete a ro! from the ,E>&RTME(TS ta)le+

@-1@

Copyright Oracle Corporation, 2001. All rights reserved.

emo1ing a o! from a Ta)le The slide graphic remo'es the (inance department from the DEPARTMENTS table assuming that there are no constraints defined on the DEPARTMENTS table!"

"nstructor #ote +fter all the rows ha'e been eliminated with the DELETE statement% only the data structure of the table remains" + more efficient method of emptying a table is with the TR#NCATE statement" You can use the TR#NCATE statement to 8uickly remo'e all rows from a table or cluster" Jemo'ing rows with the TR#NCATE statement is faster than remo'ing them with the DELETE statement for the following reasons& S S S The TR#NCATE statement is a data definition language 77L! statement and generates no rollback information" #t is co'ered in a subse8uent lesson" Truncating a table does not fire the delete triggers of the table" #f the table is the parent of a referential integrity constraint% you cannot truncate the table" 7isable the constraint before issuing the TR#NCATE statement" "ntroduction to $racle%i: SQL @-1@

The ,ELETE Statement

Eou can remo1e e(isting ro!s from a ta)le )* using the ,ELETE statement+
,ELETE /FROM0 /12ERE table condition0;

@-1%

Copyright Oracle Corporation, 2001. All rights reserved.

-eleting o!s You can remo'e e$isting rows by using the DELETE statement" #n the synta$& table condition is the table name identifies the rows to be deleted and is composed of column names% e$pressions% constants% sub8ueries% and comparison operators

Note: #f no rows are deleted% a message >* roI! deleted"@ is returned& (or more information% see Oracle9i SQL Reference% >DELETE"@

"nstructor #ote The DELETE statement does not ask for confirmation" <owe'er% the delete operation is not made permanent until the data transaction is committed" Therefore% you can undo the operation with the ROLL5AC2 statement if you make a mistake" "ntroduction to $racle%i: SQL @-1%

-eleting

o!s from a Ta)le

Specific ro!s are deleted if *ou specif* the 12ERE clause+


,ELETE FROM departments 12ERE department_name 3 +Finance+; roF deleted7

All ro!s in the ta)le are deleted if *ou omit the 12ERE clause+
,ELETE FROM copy_emp; !! roFs deleted7

@-53

Copyright Oracle Corporation, 2001. All rights reserved.

-eleting o!s 6continued7 You can delete specific rows by specifying the &=ERE clause in the DELETE statement" The slide e$ample deletes the (inance department from the DEPARTMENTS table" You can confirm the delete operation by displaying the deleted rows using the SELECT statement" SELECT ROM &=ERE * department! department_name : 7 inance7"

no roI! !elected0 #f you omit the &=ERE clause% all rows in the table are deleted" The second e$ample on the slide deletes all the rows from the COP'_EMP table% because no &=ERE clause has been specified" Example Jemo'e rows identified in the &=ERE clause" DELETE &=ERE ROM emplo+ee! emplo+ee_id : --Z"

- roI deleted0 DELETE &=ERE ROM department! department_id IN ,)*, Z*/"

. roI! deleted0 "ntroduction to $racle%i: SQL @-53

-eleting o!s Based on Another Ta)le


2se su)?ueries in ,ELETE statements to remo1e ro!s from a ta)le )ased on 1alues from another ta)le+
,ELETE FROM employees 12ERE department_id 3 "SELECT department_id FROM departments 12ERE department_name L-8E +<>)%lic<+#; roF deleted7

@-51

Copyright Oracle Corporation, 2001. All rights reserved.

-eleting o!s Based on Another Ta)le You can use sub8ueries to delete rows from a table based on 'alues from another table" The e$ample on the slide deletes all the employees who are in a department where the department name contains the string >Public"@ The sub8uery searches the DEPARTMENTS table to find the department number based on the department name containing the string >Public"@ The sub8uery then feeds the department number to the main 8uery% which deletes rows of data from the EMPLO'EES table based on this department number"

"ntroduction to $racle%i: SQL @-51

-eleting o!s: "ntegrit* Constraint Error

,ELETE FROM departments 12ERE department_id 3 G0;

,ELETE FROM departments * ERROR at line R OR&J0!!4!R inte;rity constraint "2R7EM>_,E>T_F8# Uiolated J c5ild record =o)nd

Eou cannot delete a ro! that contains a primar* ;e* that is used as a foreign ;e* in another ta)le+
@-55 Copyright Oracle Corporation, 2001. All rights reserved.

"ntegrit* Constraint Error #f you attempt to delete a record with a 'alue that is tied to an integrity constraint% an error is returned" The e$ample on the slide tries to delete department number 60 from the DEPARTMENTS table% but it results in an error because department number is used as a foreign key in the EMPLO'EES table" #f the parent record that you attempt to delete has child records% then you recei'e the child record found 'iolation ORAA*..B." The following statement works because there are no employees in department E0& DELETE ROM department! &=ERE department_id : ?*" - roI deleted0

"nstructor #ote #f referential integrity constraints are in use% you may recei'e an 3racle ser'er error message when you attempt to delete a row" <owe'er% if the referential integrity constraint contains the ON DELETE CASCADE option% then the selected row and its children are deleted from their respecti'e tables" "ntroduction to $racle%i: SQL @-55

2sing a Su)?uer* in an -(SERT Statement


-(SERT -(TO "SELECT employee_id, last_name, email, 5ire_date, $o%_id, salary, department_id FROM employees 12ERE department_id 3 :0# Q&L9ES "44444, +Taylor+, +,T&ALOR+, TO_,&TE"+0MJO9(J44+, +,,JMO(JRR+#, +ST_CLER8+, :000, :0#; roF created7

@-58

Copyright Oracle Corporation, 2001. All rights reserved.

2sing a Su)?uer* in an -(SERT Statement You can use a sub8uery in place of the table name in the INTO clause of the INSERT statement" The select list of this sub8uery must ha'e the same number of columns as the column list of the $AL#ES clause" +ny rules on the columns of the base table must be followed in order for the INSERT statement to work successfully" (or e$ample% you could not put in a duplicate employee #7% nor lea'e out a 'alue for a mandatory not null column"

"ntroduction to $racle%i: SQL @-58

2sing a Su)?uer* in an -(SERT Statement


SELECT employee_id, 9erif* the resultslast_name, email, 5ire_date, $o%_id, salary, department_id FROM employees 12ERE department_id 3 :0;

@-5=

Copyright Oracle Corporation, 2001. All rights reserved.

2sing a Su)?uer* in an -(SERT Statement The e$ample shows the results of the sub8uery that was used to identify the table for the INSERT statement"

"ntroduction to $racle%i: SQL @-5=

2sing the 1-T2 C2EC8 O>T-O( Ne*!ord on -/L Statements


A su)?uer* is used to identif* the ta)le and columns of the -/L statement+ The 1-T2 C2EC8 O>T-O( ;e*!ord prohi)its *ou from changing ro!s that are not in the su)?uer*+

-(SERT -(TO

"SELECT employee_id, last_name, email, 5ire_date, $o%_id, salary FROM employees 12ERE department_id 3 :0 1-T2 C2EC8 O>T-O(# Q&L9ES "4444P, +Smit5+, +OSM-T2+, TO_,&TE"+0MJO9(J44+, +,,JMO(JRR+#, +ST_CLER8+, :000#; -(SERT -(TO * ERROR at line R OR&J0 H0!R UieF 1-T2 C2EC8 O>T-O( F5ereJcla)se Uiolation

@-55

Copyright Oracle Corporation, 2001. All rights reserved.

The 1-T2 C2EC8 O>T-O( Ne*!ord )pecify &IT= C=EC2 OPTION to indicate that% if the sub8uery is used in place of a table in an INSERT% #PDATE% or DELETE statement% no changes that would produce rows that are not included in the sub8uery are permitted to that table" #n the e$ample shown% the &IT= C=EC2 OPTION keyword is used" The sub8uery identifies rows that are in department 50% but the department #7 is not in the SELECT list% and a 'alue is not pro'ided for it in the $AL#ES list" #nserting this row would result in a department #7 of null% which is not in the sub8uery"

"ntroduction to $racle%i: SQL @-55

$1er1ie! of the E(plicit -efault Feature

With the e(plicit default feature: *ou can use the ,EF&9LT ;e*!ord as a column 1alue !here the column default is desired+ The addition of this feature is for compliance !ith the SQL: 1%%% Standard+ This allo!s the user to control !here and !hen the default 1alue should )e applied to data+ E(plicit defaults can )e used in -(SERT and 9>,&TE statements+

@-5&

Copyright Oracle Corporation, 2001. All rights reserved.

E(plicit -efaults The DE A#LT keyword can be used in INSERT and #PDATE statements to identify a default column 'alue" #f no default 'alue e$ists% a null 'alue is used"

"ntroduction to $racle%i: SQL @-5&

2sing E(plicit -efault 9alues


,EF&9LT !ith -(SERT:

-(SERT -(TO departments "department_id, department_name, mana;er_id# Q&L9ES "300, +En;ineerin;+, ,EF&9LT#;

,EF&9LT !ith 9>,&TE:


0;

9>,&TE departments SET mana;er_id 3 ,EF&9LT 12ERE department_id 3

@-5>

Copyright Oracle Corporation, 2001. All rights reserved.

2sing E(plicit -efault 9alues )pecify DE A#LT to set the column to the 'alue pre'iously specified as the default 'alue for the column" #f no default 'alue for the corresponding column has been specified% 3racle sets the column to null" #n the first e$ample shown% the INSERT statement uses a default 'alue for the MANAGER_ID column" #f there is no default 'alue defined for the column% a null 'alue is inserted instead" The second e$ample uses the #PDATE statement to set the MANAGER_ID column to a default 'alue for department 50" #f no default 'alue is defined for the column% it changes the 'alue to null" Note: Nhen creating a table% you can specify a default 'alue for a column" This is discussed in the >;reating and Managing Tables@ lesson"

"ntroduction to $racle%i: SQL @-5>

The MER@E Statement


4ro1ides the a)ilit* to conditionall* update or insert data into a data)ase ta)le 4erforms an 9>,&TE if the ro! e(ists: and an -(SERT if it is a ne! ro!:
A1oids separate updates "ncreases performance and ease of use "s useful in data !arehousing applications

@-5@

Copyright Oracle Corporation, 2001. All rights reserved.

MER@E Statements )*L has been e$tended to include the MERGE statement" 6sing this statement% you can update or insert a row conditionally into a table% thus a'oiding multiple #PDATE statements" The decision whether to update or insert into the target table is based on a condition in the ON clause" )ince the MERGE command combines the INSERT and #PDATE commands% you need both INSERT and #PDATE pri'ileges on the target table and the SELECT pri'ilege on the source table" The MERGE statement is deterministic" You cannot update the same row of the target table multiple times in the same MERGE statement" +n alternati'e approach is to use PLH)*L loops and multiple 7ML statements" The MERGE statement% howe'er% is easy to use and more simply e$pressed as a single )*L statement" The MERGE statement is suitable in a number of data warehousing applications" (or e$ample% in a data warehousing application% you may need to work with data coming from multiple sources% some of which may be duplicates" Nith the MERGE statement% you can conditionally add or modify rows"

"ntroduction to $racle%i: SQL @-5@

The MER@E Statement S*nta(


Eou can conditionall* insert or update ro!s in a ta)le )* using the MER@E statement+
MER@E -(TO table_name table_alias 9S-(@ "table| ie!|sub_"uery# alias O( "#oin condition# 12E( M&TC2E, T2E( 9>,&TE SET col1 $ col_ al1, col2 $ col2_ al 12E( (OT M&TC2E, T2E( -(SERT "column_list# Q&L9ES "column_ alues#;

@-5%

Copyright Oracle Corporation, 2001. All rights reserved.

/erging o!s You can update e$isting rows and insert new rows conditionally by using the MERGE statement" #n the synta$& INTO clause #SING clause ON clause &=EN MATC=ED 6 specifies the target table you are updating or inserting into identifies the source of the data to be updated or inserted1 can be a table% 'iew% or sub8uery the condition upon which the MERGE operation either updates or inserts instructs the ser'er how to respond to the results of the Aoin condition

&=EN NOT MATC=ED (or more information% see Oracle9i SQL Reference, >MERGE"@

"ntroduction to $racle%i: SQL @-5%

/erging

o!s

"nsert or update ro!s in the CO>A_EM> ta)le to match the EM>LOAEES ta)le+
MER@E -(TO copy_emp c 9S-(@ employees e O( "c7employee_id 3 e7employee_id# 12E( M&TC2E, T2E( 9>,&TE SET c7=irst_name 3 e7=irst_name, c7last_name 3 e7last_name, 777 c7department_id 3 e7department_id 12E( (OT M&TC2E, T2E( -(SERT Q&L9ES"e7employee_id, e7=irst_name, e7last_name, e7email, e7p5one_n)m%er, e75ire_date, e7$o%_id, e7salary, e7commission_pct, e7mana;er_id, e7department_id#;

@-83

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of /erging o!s MERGE INTO cop+_emp c #SING emplo+ee! e ON ,c0emplo+ee_id : e0emplo+ee_id/ &=EN MATC=ED T=EN #PDATE SET c0Uir!t_name : e0Uir!t_name, c0la!t_name : e0la!t_name, c0email : e0email, c0p9one_n3m<er : e0p9one_n3m<er, c09ire_date : e09ire_date, c0;o<_id : e0;o<_id, c0!alar+ : e0!alar+, c0commi!!ion_pct : e0commi!!ion_pct, c0manager_id : e0manager_id, c0department_id : e0department_id &=EN NOT MATC=ED T=EN INSERT $AL#ES,e0emplo+ee_id, e0Uir!t_name, e0la!t_name, e0email, e0p9one_n3m<er, e09ire_date, e0;o<_id, e0!alar+, e0commi!!ion_pct, e0manager_id, e0department_id/" The e$ample shown matches the EMPLO'EE_ID in the COP'_EMP table to the EMPLO'EE_ID in the EMPLO'EES table" #f a match is found% the row in the COP'_EMP table is updated to match the row in the EMPLO'EES table" #f the row is not found% it is inserted into the COP'_EMP table" "ntroduction to $racle%i: SQL @-83

/erging
SELECT * FROM CO>A_EM>; no roFs selected

o!s

MER@E -(TO copy_emp c 9S-(@ employees e O( "c7employee_id 3 e7employee_id# 12E( M&TC2E, T2E( 9>,&TE SET 777 12E( (OT M&TC2E, T2E( -(SERT Q&L9ES777; SELECT * FROM CO>A_EM>; !0 roFs selected7

@-81

Copyright Oracle Corporation, 2001. All rights reserved.

E(ample of /erging o!s The condition c0emplo+ee_id : e0emplo+ee_id is e'aluated" ,ecause the COP'_EMP table is empty% the condition returns false& there are no matches" The logic falls into the &=EN NOT MATC=ED clause% and the MERGE command inserts the rows of the EMPLO'EES table into the COP'_EMP table" #f rows e$isted in the COP'_EMP table and employee #7s matched in both tables the COP'_EMP and EMPLO'EES tables!% the e$isting rows in the COP'_EMP table would be updated to match the EMPLO'EES table"

"nstructor #ote #n a data warehousing en'ironment% you may ha'e a large fact table and a smaller dimension table with rows that need to be inserted into the large fact table conditionally" The MERGE statement is useful in this situation" You may want to ha'e a break here" "ntroduction to $racle%i: SQL @-81

-ata)ase Transactions
A data)ase transaction consists of one of the follo!ing:

-/L statements !hich constitute one consistent change to the data $ne --L statement $ne -CL statement

@-85

Copyright Oracle Corporation, 2001. All rights reserved.

-ata)ase Transactions The 3racle ser'er ensures data consistency based on transactions" Transactions gi'e you more fle$ibility and control when changing data% and they ensure data consistency in the e'ent of user process failure or system failure" Transactions consist of 7ML statements that make up one consistent change to the data" (or e$ample% a transfer of funds between two accounts should include the debit to one account and the credit to another account in the same amount" ,oth actions should either fail or succeed together1 the credit should not be committed without the debit" Transaction T*pes Type
7ata manipulation language 7ML! 7ata definition language 77L! 7ata control language 7;L! Description ;onsists of any number of 7ML statements that the 3racle ser'er treats as a single entity or a logical unit of work ;onsists of only one 77L statement ;onsists of only one 7;L statement

"ntroduction to $racle%i: SQL @-85

-ata)ase Transactions
Begin !hen the first -/L SQL statement is e(ecuted End !ith one of the follo!ing e1ents:
A COMM-T or ROLL.&C8 statement is issued A --L or -CL statement e(ecutes 6automatic commit7 The user e(its iSQL.4lus The s*stem crashes

@-88

Copyright Oracle Corporation, 2001. All rights reserved.

When -oes a Transaction Start and EndM + transaction begins when the first 7ML statement is encountered and ends when one of the following occurs& S + COMMIT or ROLL5AC2 statement is issued S S S S + 77L statement% such as CREATE% is issued + 7;L statement is issued The user e$its i)*LBPlus + machine fails or the system crashes

+fter one transaction ends% the ne$t e$ecutable )*L statement automatically starts the ne$t transaction" + 77L statement or a 7;L statement is automatically committed and therefore implicitly ends a transaction"

"nstructor #ote Please run the script [_crete!t0!1l to create the test table and insert data into the table" "ntroduction to $racle%i: SQL @-88

Ad1antages of COMM-T and ROLL.&C8 Statements


With COMM-T and ROLL.&C8 statements: *ou can:

Ensure data consistenc* 4re1ie! data changes )efore ma;ing changes permanent Croup logicall* related operations

@-8=

Copyright Oracle Corporation, 2001. All rights reserved.

"ntroduction to $racle%i: SQL @-8=

Controlling Transactions
%ime

&'(()%

Transaction ,ELETE
SA9E4$"#T A

-(SERT 9>,&TE
SA9E4$"#T B

-(SERT

ROLL.&C8 to S&QE>O-(T .

ROLL.&C8 ROLL.&C8 to S&QE>O-(T &

@-85

Copyright Oracle Corporation, 2001. All rights reserved.

E(plicit Transaction Control Statements You can control the logic of transactions by using the COMMIT% SA$EPOINT% and ROLL5AC2 statements"
Statement COMMIT SA$EPOINT name ROLL5AC2 ROLL5AC2 TO 516*7"-(+ name Description ?nds the current transaction by making all pending data changes permanent Marks a sa'epoint within the current transaction ROLL5AC2 ends the current transaction by discarding all pending data changes ROLL5AC2 TO SA$EPOINT rolls back the current transaction to the specified sa'epoint% thereby discarding any changes and or sa'epoints created after the sa'epoint to which you are rolling back" #f you omit the TO SA$EPOINT clause% the ROLL5AC2 statement rolls back the entire transaction" +s sa'epoints are logical% there is

Note: SA$EPOINT is not +0)# standard )*L" "nstructor #ote )a'epoints are not schema obAects and cannot be referenced in the data dictionary" "ntroduction to $racle%i: SQL @-85

olling Bac; Changes to a /ar;er


Create a mar;er in a current transaction )* using the S&QE>O-(T statement+ oll )ac; to that mar;er )* using the ROLL.&C8 TO S&QE>O-(T statement+

9>,&TE777 S&QE>O-(T )pdate_done; SaUepoint created7 -(SERT777 ROLL.&C8 TO )pdate_done; Roll%acK complete7

@-8&

Copyright Oracle Corporation, 2001. All rights reserved.

olling Bac; Changes to a Sa1epoint You can create a marker in the current transaction by using the SA$EPOINT statement which di'ides the transaction into smaller sections" You can then discard pending changes up to that marker by using the ROLL5AC2 TO SA$EPOINT statement" #f you create a second sa'epoint with the same name as an earlier sa'epoint% the earlier sa'epoint is deleted"

"nstructor #ote )a'epoints are especially useful in PLH)*L and /RL programs in which recent changes can be undone conditionally based on run-time conditions" "ntroduction to $racle%i: SQL @-8&

"mplicit Transaction 4rocessing

An automatic commit occurs under the follo!ing circumstances:


--L statement is issued -CL statement is issued #ormal e(it from iSQL.4lus: !ithout e(plicitl* issuing COMM-T or ROLL.&C8 statements

An automatic roll)ac; occurs under an a)normal termination of iSQL.4lus or a s*stem failure+

@-8>

Copyright Oracle Corporation, 2001. All rights reserved.

"mplicit Transaction 4rocessing


Status +utomatic commit %ircumstances 77L statement or 7;L statement is issued" i)*LBPlus e$ited normally% without e$plicitly issuing COMMIT or ROLL5AC2 commands" +bnormal termination of i)*LBPlus or system failure"

+utomatic rollback

Note: + third command is a'ailable in i)*LBPlus" The A#TOCOMMIT command can be toggled on or off" #f set to on% each indi'idual 7ML statement is committed as soon as it is e$ecuted" You cannot roll back the changes" #f set to off% the COMMIT statement can still be issued e$plicitly" +lso% the COMMIT statement is issued when a 77L statement is issued or when you e$it from i)*LBPlus" S*stem Failures Nhen a transaction is interrupted by a system failure% the entire transaction is automatically rolled back" This pre'ents the error from causing unwanted changes to the data and returns the tables to their state at the time of the last commit" #n this way% the 3racle ser'er protects the integrity of the tables" (rom i)*LBPlus% a normal e$it from the session is accomplished by clicking the ?$it button" Nith )*LBPlus% a normal e$it is accomplished by typing the command E%IT at the prompt" ;losing the window is interpreted as an abnormal e$it"

"ntroduction to $racle%i: SQL @-8>

State of the -ata Before COMM-T or ROLL.&C8


The pre1ious state of the data can )e reco1ered+ The current user can re1ie! the results of the -/L operations )* using the SELECT statement+ $ther users cannot 1ie! the results of the -/L statements )* the current user+ The affected ro!s are lockedK other users cannot change the data !ithin the affected ro!s+

@-8@

Copyright Oracle Corporation, 2001. All rights reserved.

Committing Changes ?'ery data change made during the transaction is temporary until the transaction is committed" )tate of the data before COMMIT or ROLL5AC2 statements are issued& S S S 7ata manipulation operations primarily affect the database buffer1 therefore% the pre'ious state of the data can be reco'ered" The current user can re'iew the results of the data manipulation operations by 8uerying the tables" 3ther users cannot 'iew the results of the data manipulation operations made by the current user" The 3racle ser'er institutes read consistency to ensure that each user sees data as it e$isted at the last commit" The affected rows are locked1 other users cannot change the data in the affected rows"

"nstructor #ote Nith the 3racle ser'er% data changes can actually be written to the database files before transactions are committed% but they are still only temporary" #f a number of users are making changes simultaneously to the same table% then each user sees only his or her changes until other users commit their changes" ,y default% the 3racle ser'er has ro 3le(el loc2in)" #t is possible to alter the default locking mechanism" "ntroduction to $racle%i: SQL @-8@

State of the -ata after COMM-T

-ata changes are made permanent in the data)ase+ The pre1ious state of the data is permanentl* lost+ All users can 1ie! the results+ Loc;s on the affected ro!s are releasedK those ro!s are a1aila)le for other users to manipulate+ All sa1epoints are erased+

@-8%

Copyright Oracle Corporation, 2001. All rights reserved.

Committing Changes 6continued7 Make all pending changes permanent by using the COMMIT statement" (ollowing a COMMIT statement& S S S S S 7ata changes are written to the database" The pre'ious state of the data is permanently lost" +ll users can 'iew the results of the transaction" The locks on the affected rows are released1 the rows are now a'ailable for other users to perform new data changes" +ll sa'epoints are erased"

"ntroduction to $racle%i: SQL @-8%

Committing -ata

/a;e the changes+

,ELETE FROM employees 12ERE employee_id 3 44444; roF deleted7 -(SERT -(TO departments Q&L9ES "!40, +Corporate TaT+, (9LL, roF inserted7 M00#;

Commit the changes+

COMM-T; Commit complete7

@-=3

Copyright Oracle Corporation, 2001. All rights reserved.

Committing Changes 6continued7 The slide e$ample deletes a row from the EMPLO'EES table and inserts a new row into the DEPARTMENTS table" #t then makes the change permanent by issuing the COMMIT statement" Example Jemo'e departments 240 and /00 in the DEPARTMENTS table% and update a row in the COP'_EMP table" Make the data change permanent" DELETE ROM department! &=ERE department_id IN ,.B*, )**/" . roI! deleted0 #PDATE cop+_emp SET department_id : [* &=ERE emplo+ee_id : .*E" - roI 3pdated0 COMMIT" Commit Complete0 "nstructor #ote 6se this e$ample to e$plain how COMMIT ensures that two related operations occur together or not at all" #n this case% COMMIT pre'ents empty departments from being created" "ntroduction to $racle%i: SQL @-=3

State of the -ata After

$LLBACN

-iscard all pending changes )* using the ROLL.&C8 statement:

-ata changes are undone+ 4re1ious state of the data is restored+ Loc;s on the affected ro!s are released+
,ELETE FROM copy_emp; !! roFs deleted7 ROLL.&C8; Roll%acK complete7

@-=1

Copyright Oracle Corporation, 2001. All rights reserved.

olling Bac; Changes 7iscard all pending changes by using the ROLL5AC2 statement" (ollowing a ROLL5AC2 statement& S 7ata changes are undone" S The pre'ious state of the data is restored" S The locks on the affected rows are released" Example Nhile attempting to remo'e a record from the TEST table% you can accidentally empty the table" You can correct the mistake% reissue the proper statement% and make the data change permanent" ,ELETE FROM test; .C,*** roI! deleted0 ROLL.&C8; Roll<ac^ complete0 ,ELETE FROM test 12ERE id 3 00; - roI deleted0 SELECT * FROM test 12ERE id 3 00; No roI! !elected0 COMM-T; Commit complete0 "ntroduction to $racle%i: SQL @-=1

Statement-Le1el

oll)ac;

"f a single -/L statement fails during e(ecution: onl* that statement is rolled )ac;+ The $racle ser1er implements an implicit sa1epoint+ All other changes are retained+ The user should terminate transactions e(plicitl* )* e(ecuting a COMM-T or ROLL.&C8 statement+

@-=5

Copyright Oracle Corporation, 2001. All rights reserved.

Statement-Le1el

oll)ac;s

Part of a transaction can be discarded by an implicit rollback if a statement e$ecution error is detected" #f a single 7ML statement fails during e$ecution of a transaction% its effect is undone by a statementle'el rollback% but the changes made by the pre'ious 7ML statements in the transaction are not discarded" They can be committed or rolled back e$plicitly by the user" 3racle issues an implicit commit before and after any data definition language 77L! statement" )o% e'en if your 77L statement does not e$ecute successfully% you cannot roll back the pre'ious statement because the ser'er issued a commit" Terminate your transactions e$plicitly by e$ecuting a COMMIT or ROLL5AC2 statement" "nstructor #ote The 3racle ser'er implements locks on data to pro'ide data concurrency in the database" Those locks are released when certain e'ents occur such as a system failure! or when the transaction is completed" #mplicit locks on the database are obtained when a 7ML statement is successfully e$ecuted" The 3racle )er'er locks data at the lowest le'el possible by default " Manually ac8uire locks on the database tables by e$ecuting a LOC2 TA5LE statement or the SELECT statement with the OR #PDATE clause" )tarting with 3racle4i% the 7,+ has the choice of managing undo segments or ha'ing 3racle automatically manage undo data in an undo tablespace" Please read the #nstructor 0ote on page L-52" (or more information on locking% refer to Oracle9i &oncepts, >7ata ;oncurrency and ;onsistency"@ "ntroduction to $racle%i: SQL @-=5

ead Consistenc*

ead consistenc* guarantees a consistent 1ie! of the data at all times+ Changes made )* one user do not conflict !ith changes made )* another user+ ead consistenc* ensures that on the same data:
eaders do not !ait for !riters+ Writers do not !ait for readers+

@-=8

Copyright Oracle Corporation, 2001. All rights reserved.

ead Consistenc* 7atabase users access the database in two ways& S S Jead operations SELECT statement! Nrite operations INSERT% #PDATE% DELETE

statements! You need read consistency so that the following occur& S S S S The database reader and writer are ensured a consistent 'iew of the data" Jeaders do not 'iew data that is in the process of being changed" Nriters are ensured that the changes to the database are done in a consistent way" ;hanges made by one writer do not disrupt or conflict with changes another writer is making"

The purpose of read consistency is to ensure that each user sees data as it e$isted at the last commit% before a 7ML operation started"

"nstructor #ote Please read the #nstructor note on page L-5/" "ntroduction to $racle%i: SQL @-=8

"mplementation of
2ser A

ead Consistenc*

9>,&TE employees SET salary 3 M000 12ERE last_name 3 +@oyal+;

-ata )loc;s oll)ac; segments

SELECT * FROM )ser&7employees;

ead consistent image

changed and unchanged data )efore change OoldS data

2ser B

@-==

Copyright Oracle Corporation, 2001. All rights reserved.

"mplementation of ead Consistenc* Jead consistency is an automatic implementation" #t keeps a partial copy of the database in undo segments" Nhen an insert% update% or delete operation is made to the database% the 3racle ser'er takes a copy of the data before it is changed and writes it to a undo se)ment" +ll readers% e$cept the one who issued the change% still see the database as it e$isted before the changes started1 they 'iew the rollback segmentGs >snapshot@ of the data" ,efore changes are committed to the database% only the user who is modifying the data sees the database with the alterations1 e'eryone else sees the snapshot in the undo segment" This guarantees that readers of the data read consistent data that is not currently undergoing change" Nhen a 7ML statement is committed% the change made to the database becomes 'isible to anyone e$ecuting a SELECT statement" The space occupied by the old data in the undo segment file is freed for reuse" #f the transaction is rolled back% the changes are undone& S The original% older 'ersion% of the data in the undo segment is written back to the table" S +ll users see the database as it e$isted before the transaction began" "nstructor #ote Nhen you commit a transaction% the 3racle ser'er releases the rollback information but does not immediately destroy it" The information remains in the undo segment to create read-consistent 'iews of pertinent data for 8ueries that started before the transaction committed" )tarting with 3racle4i% the 7,+ has the choice of managing undo segments or ha'ing 3racle automatically manage undo data in an undo tablespace" This is discussed in the 7,+ courses" "ntroduction to $racle%i: SQL @-==

Loc;ing

"n an $racle data)ase: loc;s:

4re1ent destructi1e interaction )et!een concurrent transactions e?uire no user action Automaticall* use the lo!est le1el of restricti1eness Are held for the duration of the transaction Are of t!o t*pes: e(plicit loc;ing and implicit loc;ing

@-=5

Copyright Oracle Corporation, 2001. All rights reserved.

What Are Loc;sM Locks are mechanisms that pre'ent destructi'e interaction between transactions accessing the same resource% either a user obAect such as tables or rows! or a system obAect not 'isible to users such as shared data structures and data dictionary rows!" 7o" the Oracle Database Loc8s Data 3racle locking is performed automatically and re8uires no user action" #mplicit locking occurs for )*L statements as necessary% depending on the action re8uested" #mplicit locking occurs for all )*L statements e$cept SELECT" The users can also lock data manually% which is called e$plicit locking"

"nstructor #ote )ee the #nstructor 0ote on page L-52" "ntroduction to $racle%i: SQL @-=5

"mplicit Loc;ing

T!o loc; modes:


E(clusi1e: Loc;s out other users Share: Allo!s other users to access -/L: Ta)le share: ro! e(clusi1e Queries: #o loc;s re?uired --L: 4rotects o)Gect definitions

High le1el of data concurrenc*:

Loc;s held until commit or roll)ac;

@-=&

Copyright Oracle Corporation, 2001. All rights reserved.

-/L Loc;ing Nhen performing data manipulation language 7ML! operations% the 3racle ser'er pro'ides data concurrency through 7ML locking" 7ML locks occur at two le'els& S S + share lock is automatically obtained at the table le'el during 7ML operations" Nith share lock mode% se'eral transactions can ac8uire share locks on the same resource" +n e$clusi'e lock is ac8uired automatically for each row modified by a 7ML statement" ?$clusi'e locks pre'ent the row from being changed by other transactions until the transaction is committed or rolled back" This lock ensures that no other user can modify the same row at the same time and o'erwrite changes not yet committed by another user" 77L locks occur when you modify a database obAect such as a table"

"nstructor #ote + SELECT000 OR #PDATE statement also implements a lock" This is co'ered in the 3racle4i PLH)*L course" "ntroduction to $racle%i: SQL @-=&

Summar*
"n this lesson: *ou should ha1e learned ho! to use -/L statements and control transactions+
Statement -(SERT 9>,&TE ,ELETE MER@E COMM-T S&QE>O-(T ROLL.&C8
@-=>

-escription Adds a ne! ro! to the ta)le /odifies e(isting ro!s in the ta)le emo1es e(isting ro!s from the ta)le Conditionall* inserts or updates data in a ta)le /a;es all pending changes permanent "s used to roll)ac; to the sa1epoint mar;er -iscards all pending data changes
Copyright Oracle Corporation, 2001. All rights reserved.

Summar* #n this lesson% you should ha'e learned how to manipulate data in the 3racle database by using the INSERT% #PDATE% and DELETE statements" ;ontrol data changes by using the COMMIT% SA$EPOINT% and ROLL5AC2 statements" The 3racle ser'er guarantees a consistent 'iew of data at all times" Locking can be implicit or e$plicit"

"ntroduction to $racle%i: SQL @-=>

4ractice @ $1er1ie!
This practice co1ers the follo!ing topics:

"nserting ro!s into the ta)les 2pdating and deleting ro!s in the ta)le Controlling transactions

@-=@

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice @ $1er1ie! #n this practice% you add rows to the M'_EMPLO'EE table% update and delete data from the table% and control your transactions"

"ntroduction to $racle%i: SQL @-=@

4ractice @ #nsert data into the M'_EMPLO'EE table" 5" Jun the statement in the la<[_-0!1l script to build the M'_EMPLO'EE table to be used for the lab" 2" 7escribe the structure of the M'_EMPLO'EE table to identify the column names"

/" +dd the first row of data to the M'_EMPLO'EE table from the following sample data" 7o not list the columns in the INSERT clause" -, . ) Z C L&ST_(&ME Patel Danc! 5iri NeIman Rope<3rn F-RST_(&ME Ralp9 5ett+ 5en C9ad A3dre+ 9SER-, rpatel <danc! <<iri cneIman arope<3r S&L&RA [BC [E* --** ?C* -CC*

4" Populate the M'_EMPLO'EE table with the second row of sample data from the preceding list" This time% list the columns e$plicitly in the INSERT clause" 5" ;onfirm your addition to the table"

"ntroduction to $racle%i: SQL @-=%

4ractice @ 6continued7 6" Nrite an insert statement in a te$t file named loademp0!1l to load rows into the M'_EMPLO'EE table" ;oncatenate the first letter of the first name and the first se'en characters of the last name to produce the user #7" E" Populate the table with the ne$t two rows of sample data by running the insert statement in the script that you created" L" ;onfirm your additions to the table"

4" Make the data additions permanent" 6pdate and delete data in the M'_EMPLO'EE table" 50" ;hange the last name of employee / to 7re$ler" 55" ;hange the salary to 5000 for all employees with a salary less than 400" 52" Cerify your changes to the table"

5/" 7elete ,etty 7ancs from the M'_EMPLO'EE table" 54" ;onfirm your changes to the table"

"ntroduction to $racle%i: SQL @-53

4ractice @ 6continued7 55" ;ommit all pending changes" ;ontrol data transaction to the M'_EMPLO'EE table" 56" Populate the table with the last row of sample data by modifying the statements in the script that you created in step 6" Jun the statements in the script" 5E" ;onfirm your addition to the table"

5L" Mark an intermediate point in the processing of the transaction" 54" ?mpty the entire table" 20" ;onfirm that the table is empty" 25" 7iscard the most recent DELETE operation without discarding the earlier INSERT operation" 22" ;onfirm that the new row is still intact"

2/" Make the data addition permanent"

"ntroduction to $racle%i: SQL @-51

"nstructor #ote 6for page @-=5 - @-=57 7emo& [_!elect0!1l Purpose& To illustrate the concept that a reader does not lock another reader Login to i)*LBPlus using the teac9Yoracle account" Login to i)*LBPlus using an unused ora>>Yoracle account" Jun the [_!elect0!1l script from the teac9Yoracle account" This script selects all records from the DEPARTMENTS table!" Jun the [_!elect0!1l script in the ora>>Yoracle account" This script selects all records from the DEPARTMENTS table!" #n both the logins% the script e$ecutes successfully" This demonstrates the concept& a reader does not loc2 another reader. 7emo& [_grant0!1l% [_3pdate0!1l% [_!elect0!1l Purpose& To illustrate that a writer does not lock a reader Jun the [_grant0!1l script in the teac9Yoracle account" This script grants SELECT and #PDATE pri'ileges on the DEPARTMENTS table to the ora>> account!" Jun the [_3pdate0!1l script in the teac9Yoracle account" This script updates the DEPARTMENTS table% changing location of the department #7 20 to location 5500" The update places a lock on the DEPARTMENTS table!" Jun the [_!elect0!1l script in the teac9Yoracle account" This script selects all records from the DEPARTMENTS table" 3bser'e that the location of department #7 20 is changed to location #7 5500!" Jun the [_!elect0!1l script in the ora>>Yoracle account" This script selects all records from the DEPARTMENTS table!" 3bser'e that the script e$ecutes successfully in the ora>>Yoracle account% but the location for department #7 20 still has the location #7 of 5L00" This demonstrates the concept& a riter does not loc2 a reader. 7emo& [_3pdate0!1l% [_roll<ac^0!1l% [_!elect0!1l Purpose& To illustrate that a writer locks another writer Jun the [_3pdate0!1l script in the ora>>Yoracle account" The script does not e$ecute because the DEPARTMENTS table is locked by the teac9Yoracle account"! )witch to the teac9Yoracle account and run the [_roll<ac^0!1l script" This script rolls back the transaction% thereby releasing the lock on the DEPARTMENTS table"! )witch to the ora>>Yoracle account" You see that the [_3pdate0!1l script has e$ecuted successfully because the lock on the DEPARTMENTS table has been released Jun the [_!elect0!1l script in the ora>>Yoracle account" This script selects all records from the DEPARTMENTS table" 3bser'e that the location of department #7 20 is changed to location #7 5500"! This demonstrates the concept& a riter loc2s a riter"

"ntroduction to $racle%i: SQL @-55

ead Consistenc* E(ample


$utput
!H000

Time t1 t5 t8 t=

Session 1
SELECT salary FROM employees 12ERE last_name3+8in;+;

Session 5

9>,&TE employees SET salary3salary+ 0000 12ERE last_name3+8in;+; SELECT salary FROM employees 12ERE last_name3+8in;+; COMM-T; SELECT salary FROM employees 12ERE last_name3+8in;+;

!H000

3H000

t5

@-58

Copyright Oracle Corporation, 2001. All rights reserved.

"nstructor #ote 6for page @-=87 ead Consistenc* E(ample (or the duration of a )*L statement% read consistency guarantees that the selected data is consistent to the time point when the processing of the statement started" 3racle ser'er keeps noncommitted data in data blocks of undo segments before images!" +s long as the changes are not committed% all users see the original data" The 3racle ser'er uses data of both table segments and undo segments to generate a read-consistent 'iew on the data" #n the e$ample in the slide% the update of session 2 is not 'isible to process 5 until session 2 has committed the update from t4 on!" (or the select statement at time point t/% the salary of =ing must be read from a data block of a undo segment that belongs to the transaction of session 2"

"ntroduction to $racle%i: SQL @-58

"ntroduction to $racle%i: SQL @-5=

Creating and /anaging Ta)les

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing /0 minutes 20 minutes 50 minutes

Topic Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing:

-escri)e the main data)ase o)Gects Create ta)les -escri)e the data t*pes that can )e used !hen specif*ing column definition Alter ta)le definitions -rop: rename: and truncate ta)les

%-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim #n this lesson% you learn about tables% the main database obAects% and their relationships to each other" You also learn how to create% alter% and drop tables"

"ntroduction to $racle%i: SQL %-5

-ata)ase $)Gects
$)Gect Ta)le -escription Basic unit of storageK composed of ro!s and columns Logicall* represents su)sets of data from one or more ta)les #umeric 1alue generator "mpro1es the performance of some ?ueries Ci1es alternati1e names to o)Gects

9ie!

Se?uence "nde( S*non*m

%-8

Copyright Oracle Corporation, 2001. All rights reserved.

-ata)ase $)Gects +n 3racle database can contain multiple data structures" ?ach structure should be outlined in the database design so that it can be created during the build stage of database de'elopment" S S S S S S S Table& )tores data Ciew& )ubset of data from one or more tables )e8uence& 0umeric 'alue generator #nde$& #mpro'es the performance of some 8ueries )ynonym& Ri'es alternati'e names to obAects Tables can be created at any time% e'en while users are using the database" You do not need to specify the si9e of any table" The si9e is ultimately defined by the amount of space allocated to the database as a whole" #t is important% howe'er% to estimate how much space a table will use o'er time" Table structure can be modified online"

$racle%i Ta)le Structures

Note: More database obAects are a'ailable but are not co'ered in this course" "nstructor #ote Tables can ha'e up to 5%000 columns and must conform to standard database obAect-naming con'entions" ;olumn definitions can be omitted when using the AS sub8uery clause" Tables are created without data unless a 8uery is specified" Jows are usually added by using INSERT statements" "ntroduction to $racle%i: SQL %-8

#aming ules
Ta)le names and column names:

/ust )egin !ith a letter /ust )e 1J83 characters long /ust contain onl* AJT: aJ<: 3J%: Q: I: and U /ust not duplicate the name of another o)Gect o!ned )* the same user /ust not )e an $racle ser1er reser1ed !ord

%-=

Copyright Oracle Corporation, 2001. All rights reserved.

#aming ules 0ame database tables and columns according to the standard rules for naming any 3racle database obAect& S S S S Table names and column names must begin with a letter and be 5F/0 characters long" 0ames must contain only the characters +F:% aF9% 0F4% K underscore!% .% and Y legal characters% but their use is discouraged!" 0ames must not duplicate the name of another obAect owned by the same 3racle ser'er user" 0ames must not be an 3racle ser'er reser'ed word"

Namin! +ui&elines 6se descripti'e names for tables and other database obAects" Note: 0ames are case insensiti'e" (or e$ample% EMPLO'EES is treated as the same name as eMPlo+ee! or eMpLO'EES" (or more information% see Oracle9i SQL Reference,>3bAect 0ames and *ualifiers"@

"ntroduction to $racle%i: SQL %-=

The CRE&TE T&.LE Statement


Eou must ha1e:
L CRE&TE T&.LE pri1ilege A storage area
CRE&TE T&.LE /schema70table "column datatype /,EF&9LT expr0/, 7770#;

Eou specif*:
Ta)le name Column name: column data t*pe: and column si<e

%-5

Copyright Oracle Corporation, 2001. All rights reserved.

The CRE&TE T&.LE Statement ;reate tables to store data by e$ecuting the )*L CREATE TA5LE statement" This statement is one of the data definition language 77L! statements% that are co'ered in subse8uent lessons" 77L statements are a subset of )*L statements used to create% modify% or remo'e 3racle4i database structures" These statements ha'e an immediate effect on the database% and they also record information in the data dictionary" To create a table% a user must ha'e the CREATE TA5LE pri'ilege and a storage area in which to create obAects" The database administrator uses data control language 7;L! statements% which are co'ered in a later lesson% to grant pri'ileges to users" #n the synta$& schema table DE A#LT expr column datat$pe "nstructor #ote Please read the #nstructor note on page 4-/E "ntroduction to $racle%i: SQL %-5 is the same as the ownerGs name is the name of the table specifies a default 'alue if a 'alue is omitted in the INSERT statement is the name of the column is the columnGs data type and length

eferencing Another 2serPs Ta)les

Ta)les )elonging to other users are not in the userPs schema+ Eou should use the o!nerPs name as a prefi( to those ta)les+

%-&

Copyright Oracle Corporation, 2001. All rights reserved.

eferencing Another 2serPs Ta)les + schema is a collection of obAects" )chema obAects are the logical structures that directly refer to the data in a database" )chema obAects include tables% 'iews% synonyms% se8uences% stored procedures% inde$es% clusters% and database links" #f a table does not belong to the user% the ownerGs name must be prefi$ed to the table" (or e$ample% if there is a schema named #SER_5% and #SER_5 has an EMPLO'EES table% then specify the following to retrie'e data from that table& SELECT * ROM 3!er_<0emplo+ee!"

"ntroduction to $racle%i: SQL %-&

The ,EF&9LT $ption


Specif* a default 1alue for a column during an insert+

777 5ire_date ,&TE ,EF&9LT SAS,&TE, 777

Literal 1alues: e(pressions: or SQL functions are legal 1alues+ Another columnPs name or a pseudocolumn are illegal 1alues+ The default data t*pe must match the column data t*pe+

%->

Copyright Oracle Corporation, 2001. All rights reserved.

The ,EF&9LT $ption + column can be gi'en a default 'alue by using the DE A#LT option" This option pre'ents null 'alues from entering the columns if a row is inserted without a 'alue for the column" The default 'alue can be a literal% an e$pression% or a )*L function% such as S'SDATE and #SER% but the 'alue cannot be the name of another column or a pseudocolumn% such as NE%T$AL or C#RR$AL" The default e$pression must match the data type of the column" Note: C#RR$AL and NE%T$AL are e$plained later"

"nstructor #ote <ere is an e$ample for a pseudocolumn" (or each row returned by a 8uery% the RO&N#M pseudocolumn returns a number indicating the order in which 3racle ser'er selects the row from a table or set of Aoined rows" The first row selected has a RO&N#M of 5% the second has 2% and so on" The default 'alue works with the DE A#LT keyword for INSERT and #PDATE statements discussed in the >Manipulating 7ata@ lesson" "ntroduction to $racle%i: SQL %->

Creating Ta)les
Create the ta)le+

CRE&TE T&.LE dept "deptno (9M.ER"!#, dname Q&RC2&R!" H#, loc Q&RC2&R!" 3##; Ta%le created7

Confirm ta)le creation+


,ESCR-.E dept

%-@

Copyright Oracle Corporation, 2001. All rights reserved.

Creating Ta)les The e$ample on the slide creates the DEPT table% with three columns& DEPTNO% DNAME% and LOC" #t further confirms the creation of the table by issuing the DESCRI5E command" )ince creating a table is a 77L statement% an automatic commit takes place when this statement is e$ecuted"

"nstructor #ote ?$plain that additional synta$ for CREATE TA5LE could include constraints and so on" (or more information on the CREATE TA5LE synta$% refer to& Oracle9i SQL Reference, >CREATE TA5LE" @ "ntroduction to $racle%i: SQL %-@

Ta)les in the $racle -ata)ase


2ser Ta)les:
Are a collection of ta)les created and maintained )* the user Contain user information "s a collection of ta)les created and maintained )* the $racle Ser1er Contain data)ase information

-ata -ictionar*:

%-%

Copyright Oracle Corporation, 2001. All rights reserved.

Ta)les in the $racle -ata)ase 6ser tables are tables created by the user% such as EMPLO'EES" There is another collection of tables and 'iews in the 3racle database known as the data dictionary" This collection is created and maintained by the 3racle ser'er and contains information about the database" +ll data dictionary tables are owned by the S'S user" The base tables are rarely accessed by the user because the information in them is not easy to understand" Therefore% users typically access data dictionary 'iews because the information is presented in a format that is easier to understand" #nformation stored in the data dictionary includes names of the 3racle ser'er users% pri'ileges granted to users% database obAect names% table constraints% and auditing information" There are four categories of data dictionary 'iews1 each category has a distinct prefi$ that reflects its intended use" $re/ix Description #SER_ These 'iews contain information about obAects owned by the user
ALL_ D5A_ $] These 'iews contain information about all of the tables obAect tables and relational tables! accessible to the user" These 'iews are restricted 'iews% which can be accessed only by people who ha'e been assigned the 7,+ role" These 'iews are dynamic performance 'iews% database ser'er performance% memory% and locking"

"ntroduction to $racle%i: SQL %-%

Quer*ing the -ata -ictionar*

See the names of ta)les o!ned )* the user+


SELECT ta%le_name FROM )ser_ta%les ;

9ie! distinct o)Gect t*pes o!ned )* the user+


SELECT ,-ST-(CT o%$ect_type FROM )ser_o%$ects ;

9ie! ta)les: 1ie!s: s*non*ms: and se?uences o!ned )* the user+


SELECT * FROM )ser_catalo; ;

%-13

Copyright Oracle Corporation, 2001. All rights reserved.

Quer*ing the -ata -ictionar* You can 8uery the data dictionary tables to 'iew 'arious database obAects owned by you" The data dictionary tables fre8uently used are these& O #SER_TA5LES O #SER_O54ECTS O #SER_CATALOG Note: #SER_CATALOG has a synonym called CAT" You can use this synonym instead of #SER_CATALOG in )*L statements" SELECT ROM * CAT"

"ntroduction to $racle%i: SQL %-13

-ata T*pes
-ata T*pe Q&RC2&R!"si*e# C2&R"si*e# (9M.ER"p,s) ,&TE LO(@ CLO. R&1 and LO(@ R&1 .LO. .F-LE RO1-, -escription 9aria)le-length character data Fi(ed-length character data 9aria)le-length numeric data -ate and time 1alues 9aria)le-length character data up to 5 giga)*tes Character data up to = giga)*tes a! )inar* data Binar* data up to = giga)*tes Binar* data stored in an e(ternal fileK up to = giga)*tes A &= )ase num)er s*stem representing the uni?ue address of a ro! in its ta)le+

%-11

Copyright Oracle Corporation, 2001. All rights reserved.

-ata T*pes
Data type $ARC=AR.,si8e/ C=AR P,si8e/Q N#M5ER P,p,s/Q Description Cariable-length character data a ma$imum si4e must be specified& Minimum si4e is 51 ma$imum si4e is 4000! (i$ed-length character data of length si4e bytes default and minimum si4e is 51 ma$imum si4e is 2000! 0umber ha'ing precision p and scale s The precision is the total number of decimal digits% and the scale is the number of digits to the right of the decimal point1 the precision can range from 5 to /L and the scale can range from -L4 to 52E! 7ate and time 'alues to the nearest second between Danuary 5% 4E52 ,";"% and 7ecember /5% 4444 +"7" Cariable-length character data up to 2 gigabytes ;haracter data up to 4 gigabytes

DATE LONG CLO5

"ntroduction to $racle%i: SQL %-11

-ata T*pes 6continued7


Data type RA&,si8e/ LONG RA& 5LO5 5 ILE RO&ID Description Jaw binary data of length si4e a ma$imum si4e must be specified" ma$imum si4e is 2000! Jaw binary data of 'ariable length up to 2 gigabytes ,inary data up to 4 gigabytes ,inary data stored in an e$ternal file1 up to 4 gigabytes + 64 base number system representing the uni8ue address of a row in its table"

S S S S S

+ LONG column is not copied when a table is created using a sub8uery" + LONG column cannot be included in a GRO#P 5' or an ORDER 5' clause" 3nly one LONG column can be used per table" 0o constraints can be defined on a LONG column" You may want to use a CLO5 column rather than a LONG column"

"nstructor #ote 3racleL introduced large obAect LO5! data types that can store large and unstructured data such as te$t% image% 'ideo% and spatial data% up to 4 gigabytes in si9e" #n 3racle4i% LONG columns can be easily migrated to LO5 columns" Jefer students to Oracle9i 5i)ration Release 9.6.7 1uide. "nstructor #ote 6for page %-187 The date and time data types shown on the ne$t page are new to release 3racle4i"

"ntroduction to $racle%i: SQL %-15

-ateTime -ata T*pes


-atetime enhancements !ith $racle%i:

#e! -atetime data t*pes ha1e )een introduced+ #e! data t*pe storage is a1aila)le+ Enhancements ha1e )een made to time <ones and local time <one+

-ata T*pe -escription T-MEST&M> -ate !ith fractional seconds -(TERQ&L AE&R TO MO(T2 Stored as an inter1al of *ears and months -(TERQ&L ,&A TO SECO(, Stored as an inter1al of da*s to hours minutes and seconds

%-18

Copyright Oracle Corporation, 2001. All rights reserved.

$ther -ateTime -ata T*pes


Data Type TIMESTAMP INTER$AL 'EAR TO MONT= INTER$AL DA' TO SECOND Description +llows the time to be stored as a date with fractional seconds" There are se'eral 'ariations of the data type" +llows time to be stored as an inter'al of years and months" 6sed to represent the difference between two datetime 'alues% where the only significant portions are the year and month" +llows time to be stored as an inter'al of days to hours% minutes% and seconds" 6seful in representing the precise difference between two datetime 'alues"

"ntroduction to $racle%i: SQL %-18

-ateTime -ata T*pes


The T-MEST&M> data t*pe is an e(tension of the ,&TE data t*pe+ "t stores the *ear: month: and da* of the ,&TE data t*pe: plus hour: minute: and second 1alues as !ell as the fractional second 1alue+ The T-MEST&M> data t*pe is specified as follo!s:
T-MEST&M>/"=ractional_seconds_precision#0

%-1=

Copyright Oracle Corporation, 2001. All rights reserved.

-ateTime -ata T*pes The Uractional_!econd!_preci!ion optionally specifies the number of digits in the fractional part of the SECOND datetime field and can be a number in the range 0 to 4" The default is 6" Example CREATE TA5LE neI_emplo+ee! ,emplo+ee_id N#M5ER, Uir!t_name $ARC=AR.,-C/, la!t_name $ARC=AR.,-C/, 000 !tart_date TIMESTAMP,?/, 000/" #n the preceding e$ample% we are creating a table NE&_EMPLO'EES with a column !tart_date with a data type of TIMESTAMP" The precision of G?G indicates the fractional seconds precision which if not specified defaults to GEG" +ssume that two rows are inserted into the NE&_EMPLO'EES table" The output shows the differences in the display" + DATE data type defaults to display the format of DDAMONARR!& SELECT !tart_date ROM neI_emplo+ee!" -?A4#NA[? -.0**0**0****** AM .-ASEPA[B -.0**0**0****** AM "ntroduction to $racle%i: SQL %-1=

T-MEST&M> 1-T2 T-ME WO(E -ata T*pe


T-MEST&M> 1-T2 T-ME WO(E is a 1ariant of T-MEST&M> that includes a time <one displacement in its 1alue+ The time <one displacement is the difference: in hours and minutes: )et!een local time and 2TC+
T-MEST&M>/"=ractional_seconds_precision#0 1-T2 T-ME WO(E

%-15

Copyright Oracle Corporation, 2001. All rights reserved.

-atetime -ata T*pes 6T; stands for ;oordinated 6ni'ersal Time2formerly Rreenwich Mean Time" Two TIMESTAMP &IT= TIME XONE 'alues are considered identical if they represent the same instant in 6T;% regardless of the TIME XONE offsets stored in the data" ,ecause TIMESTAMP &IT= TIME XONE can also store time 9one information% it is particularly suited for recording date information that must be gathered or coordinated across geographic regions" (or e$ample% TIMESTAMP 7-BBBA*ZA-C [8**8** A[8**7 is the same as TIMESTAMP 7-BBBA*ZA-C --8**8** AC8**7 That is% L&00 a"m" Pacific )tandard Time is the same as 55&00 a"m" ?astern )tandard Time" This can also be specified as TIMESTAMP 7-BBBA*ZA-C [8**8** #SYPaciUic7 Note: Uractional_!econd!_preci!ion optionally specifies the number of digits in the fractional part of the SECOND datetime field and can be a number in the range 0 to 4" The default is 6"

"ntroduction to $racle%i: SQL %-15

T-MEST&M> 1-T2 LOC&L T-ME -ata T*pe


T-MEST&M> 1-T2 LOC&L T-ME WO(E is another 1ariant of T-MEST&M> that includes a time <one displacement in its 1alue+ -ata stored in the data)ase is normali<ed to the data)ase time <one+ The time <one displacement is not stored as part of the column dataK $racle returns the data in the usersP local session time <one+ T-MEST&M> 1-T2 LOC&L T-ME WO(E data t*pe is specified as follo!s:
T-MEST&M>/"=ractional_seconds_precision#0 1-T2 LOC&L T-ME WO(E

%-1&

Copyright Oracle Corporation, 2001. All rights reserved.

-ateTime -ata T*pes 6nlike TIMESTAMP &IT= TIME XONE% you can specify columns of type TIMESTAMP &IT= LOCAL TIME XONE as part of a primary or uni8ue key" The time 9one displacement is the difference in hours and minutes! between local time and 6T;" There is no literal for TIMESTAMP &IT= LOCAL TIME XONE" Note: Uractional_!econd!_preci!ion optionally specifies the number of digits in the fractional part of the SECOND datetime field and can be a number in the range 0 to 4" The default is 6" Example CREATE TA5LE time_e>ample ,order_date TIMESTAMP &IT= LOCAL TIME XONE/" INSERT INTO time_e>ample $AL#ES,7-CANO$A** *B8)Z8.[ AM7/" SELECT * ROM time_e>ample" order_date AAAAAAAAAAAAAAAAAAAAAAAAAAAA -CANO$A** *B0)Z0.[0****** AM The TIMESTAMP &IT= LOCAL TIME XONE type is appropriate for two-tier applications where you want to display dates and times using the time 9one of the client system" "ntroduction to $racle%i: SQL %-1&

-(TERQ&L AE&R TO MO(T2 -ata T*pe


-(TERQ&L AE&R TO MO(T2 stores a period of time using the AE&R and MO(T2 datetime fields+
-(TERQ&L AE&R /"year_precision#0 TO MO(T2 -(TERQ&L + !3J!+ AE&R"3# TO MO(T2 -ndicates an interUal o= !3 years, ! mont5s7 -(TERQ&L + !3+ AE&R"3# -ndicates an interUal o=

!3 years 0 mont5s7

-(TERQ&L +300+ MO(T2"3# -ndicates an interUal o= 300 mont5s7 -(TERQ&L + !3+ AE&R Ret)rns an error, %eca)se t5e de=a)lt precision is !, and + !3+ 5as 3 di;its7
%-1> Copyright Oracle Corporation, 2001. All rights reserved.

-(TERQ&L AE&R TO MO(T2 -ata T*pe INTER$AL 'EAR TO MONT= stores a period of time using the 'EAR and MONT= datetime fields" 6se INTER$AL 'EAR TO MONT= to represent the difference between two datetime 'alues% where the only significant portions are the year and month" (or e$ample% you might use this 'alue to set a reminder for a date 520 months in the future% or check whether 6 months ha'e elapsed since a particular date" )pecify INTER$AL 'EAR TO MONT= as follows& INTER$AL 'EAR P,+ear_preci!ion/Q TO MONT= #n the synta$& +ear_preci!ion is the number of digits in the 'EAR datetime field" The default 'alue of +ear_preci!ion is 2"

Example CREATE TA5LE time_e>ample. ,loan_d3ration INTER$AL 'EAR ,)/ TO MONT=/" INSERT INTO time_e>ample. ,loan_d3ration/ $AL#ES ,INTER$AL 7-.*7 MONT=,)//" SELECT TO_C=AR, !+!date(loan_d3ration, 7ddAmonA++++7/ ROM time_e>ample." AAtoda+7! date i! .EASepA.**-

"ntroduction to $racle%i: SQL %-1>

-(TERQ&L ,&A TO SECO(, -ata T*pe


-(TERQ&L ,&A TO SECO(, stores a period of time in terms of da*s: hours: minutes: and seconds+
-(TERQ&L ,&A /"day_precision#0 TO SECO(, /"=ractional_seconds_precision#0 -(TERQ&L +H :R !R 07!!!+ ,&A TO SECO(,"3# -ndicates H days, : 5o)rs, ! min)tes, 0 seconds, and !!! t5o)sandt5s o= a second7-(TERQ&L + !3+ AE&R"3#7 -(TERQ&L +M+ ,&A -ndicates M days7 -(TERQ&L + P0+ ,&A"3# -ndicates P0 days7

%-1@

Copyright Oracle Corporation, 2001. All rights reserved.

-(TERQ&L ,&A TO SECO(, -ata T*pe INTER$AL DA' TO SECOND stores a period of time in terms of days% hours% minutes% and seconds" 6se INTER$AL DA' TO SECOND to represent the precise difference between two datetime 'alues" (or e$ample% you might use this 'alue to set a reminder for a time /6 hours in the future% or to record the time between the start and end of a race" To represent long spans of time% including multiple years% with high precision% you can use a large 'alue for the days portion" )pecify INTER$AL DA' TO SECOND as follows& INTER$AL DA' P,da+_preci!ion/Q TO SECOND P,Uractional_!econd!_preci!ion/Q #n the synta$& da+_preci!ion is the number of digits in the DA' datetime field" +ccepted 'alues are 0 to 4" The default is 2"

Uractional_!econd!_preci!ion is the number of digits in the fractional part of the SECOND datetime field" +ccepted 'alues are 0 to 4" The default is 6"

"ntroduction to $racle%i: SQL %-1@

-(TERQ&L ,&A TO SECO(, -ata T*pe


-(TERQ&L ,&A TO SECO(, stores a period of time in terms of da*s: hours: minutes: and seconds+
-(TERQ&L +H :R !R 07!!!+ ,&A TO SECO(,"3# -ndicates H days, : 5o)rs, ! min)tes, 0 seconds, and !!! t5o)sandt5s o= a second7 -(TERQ&L +H :R !+ ,&A TO M-(9TE -ndicates H days, : 5o)rs and ! min)tes7 -(TERQ&L +H00 :+ ,&A"3# TO 2O9R -ndicates H00 days : 5o)rs7 -(TERQ&L + indicates R !R 07!!!!!!!+ 2O9R TO SECO(,"M# 5o)rs, ! min)tes, and 07!!!!!!! seconds7

%-1%

Copyright Oracle Corporation, 2001. All rights reserved.

-(TERQ&L ,&A TO SECO(, -ata T*pe Example CREATE TA5LE time_e>ample) ,da+_d3ration INTER$AL DA' ,)/ TO SECOND/" INSERT INTO time_e>ample) ,da+_d3ration/ $AL#ES ,INTER$AL 7-[*7 DA',)//" SELECT !+!date ( da+_d3ration V=alU 'earV ROM time_e>ample)" AAtoda+7! date i! .EASepA.**-

"ntroduction to $racle%i: SQL %-1%

Creating a Ta)le )* 2sing a Su)?uer* S*nta(


Create a ta)le and insert ro!s )* com)ining the CRE&TE T&.LE statement and the &S sub"uery option+

CRE&TE T&.LE table /"column, column777#0 &S sub"uery;

/atch the num)er of specified columns to the num)er of su)?uer* columns+ -efine columns !ith column names and default 1alues+

%-53

Copyright Oracle Corporation, 2001. All rights reserved.

Creating a Ta)le from o!s in Another Ta)le + second method for creating a table is to apply the AS sub3uer$ clause% which both creates the table and inserts rows returned from the sub8uery" #n the synta$& table column sub3uer$ Cuidelines S S S S S The table is created with the specified column names% and the rows retrie'ed by the SELECT statement are inserted into the table" The column definition can contain only the column name and default 'alue" #f column specifications are gi'en% the number of columns must e8ual the number of columns in the sub8uery SELECT list" #f no column specifications are gi'en% the column names of the table are the same as the column names in the sub8uery" The integrity rules are not passed onto the new table% only the column data type definitions" is the name of the table is the name of the column% default 'alue% and integrity constraint is the SELECT statement that defines the set of rows to be inserted into the new table

"ntroduction to $racle%i: SQL %-53

Creating a Ta)le )* 2sing a Su)?uer*


CRE&TE T&.LE deptP0 &S SELECT employee_id, last_name, salary* ! &((S&L, 5ire_date FROM employees 12ERE department_id 3 P0; Ta%le created7 ,ESCR-.E deptP0

%-51

Copyright Oracle Corporation, 2001. All rights reserved.

Creating a Ta)le from o!s in Another Ta)le 6continued7 The slide e$ample creates a table named DEPT[*% which contains details of all the employees working in department L0" 0otice that the data for the DEPT[* table comes from the EMPLO'EES table" You can 'erify the e$istence of a database table and check column definitions by using the i)*LBPlus DESCRI5E command" ,e sure to gi'e a column alias when selecting an e$pression" The e$pression SALAR'*-. is gi'en the alias ANNSAL" Nithout the alias% this error is generated& ERROR at line )8 ORAA**BB[8 m3!t name t9i! e>pre!!ion Iit9 a col3mn alia!

"nstructor #ote To create a table with the same structure as an e$isting table% but without the data from the e$isting table% use a sub8uery with a &=ERE clause that always e'aluates as false" (or e$ample& CREATE ,SELECT ROM &=ERE TA5LE COP'_TA5LE AS * emplo+ee! - : ./" "ntroduction to $racle%i: SQL %-51

The &LTER T&.LE Statement


2se the &LTER T&.LE statement to:

Add a ne! column /odif* an e(isting column -efine a default 1alue for the ne! column -rop a column

%-55

Copyright Oracle Corporation, 2001. All rights reserved.

The &LTER T&.LE Statement +fter you create a table% you may need to change the table structure because& you omitted a column% your column definition needs to be changed% or you need to remo'e columns" You can do this by using the ALTER TA5LE statement"

"ntroduction to $racle%i: SQL %-55

The &LTER T&.LE Statement


2se the &LTER T&.LE statement to add: modif*: or drop columns+
&LTER T&.LE table &,, "column datatype /,EF&9LT expr0 /, column datatype0777#; &LTER T&.LE table MO,-FA "column datatype /,EF&9LT expr0 /, column datatype0777#; &LTER T&.LE table ,RO> "column#;

%-58

Copyright Oracle Corporation, 2001. All rights reserved.

The &LTER T&.LE Statement 6continued7 You can add% modify% and drop columns to a table by using the ALTER TA5LE statement" #n the synta$& table MODI '6DROP column datat$pe DE A#LT expr is the name of the table ADD6 is the type of modification is the name of the new column is the data type and length of the new column specifies the default 'alue for a new column

Note: The slide gi'es the abridged synta$ for ALTER TA5LE" More about ALTER TA5LE is co'ered in a subse8uent lesson"

"nstructor #ote #n 3racleLi and later% there are new options for the ALTER TA5LE command% including the ability to drop a column from a table% which are co'ered later in this lesson" "ntroduction to $racle%i: SQL %-58

Adding a Column
#e! column ,E>TP0

OAdd a ne! column to the ,E>TP0 ta)le+S

,E>TP0

%-5=

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a Column The graphic adds the 4O5_ID column to the DEPT[* table" 0otice that the new column becomes the last column in the table"

"ntroduction to $racle%i: SQL %-5=

Adding a Column
Eou use the &,, clause to add columns+
&LTER T&.LE deptP0 &,, "$o%_id Q&RC2&R!"4##; Ta%le altered7

The ne! column )ecomes the last column+

%-55

Copyright Oracle Corporation, 2001. All rights reserved.

Cuidelines for Adding a Column S S You can add or modify columns" You cannot specify where the column is to appear" The new column becomes the last column"

The e$ample on the slide adds a column named 4O5_ID to the DEPT[* table" The 4O5_ID column becomes the last column in the table" Note: #f a table already contains rows when a column is added% then the new column is initially null for all the rows"

"ntroduction to $racle%i: SQL %-55

/odif*ing a Column

Eou can change a columnPs data t*pe: si<e: and default 1alue+

&LTER T&.LE deptP0 MO,-FA "last_name Q&RC2&R!"30##; Ta%le altered7

A change to the default 1alue affects onl* su)se?uent insertions to the ta)le+

%-5&

Copyright Oracle Corporation, 2001. All rights reserved.

/odif*ing a Column You can modify a column definition by using the ALTER TA5LE statement with the MODI ' clause" ;olumn modification can include changes to a columnGs data type% si9e% and default 'alue" Cuidelines S S S S S You can increase the width or precision of a numeric column" You can increase the width of numeric or character columns" You can decrease the width of a column only if the column contains only null 'alues or if the table has no rows" You can change the data type only if the column contains null 'alues" You can con'ert a C=AR column to the $ARC=AR. data type or con'ert a $ARC=AR. column to the C=AR data type only if the column contains null 'alues or if you do not change the si9e" + change to the default 'alue of a column affects only subse8uent insertions to the table"

"ntroduction to $racle%i: SQL %-5&

-ropping a Column
2se the ,RO> COL9M( clause to drop columns *ou no longer need from the ta)le+
&LTER T&.LE deptP0 ,RO> COL9M( $o%_id; Ta%le altered7

%-5>

Copyright Oracle Corporation, 2001. All rights reserved.

-ropping a Column You can drop a column from a table by using the ALTER TA5LE statement with the DROP COL#MN clause" This is a feature a'ailable in 3racleLi and later" Cuidelines S S S S The column may or may not contain data" 6sing the ALTER TA5LE statement% only one column can be dropped at a time" The table must ha'e at least one column remaining in it after it is altered" 3nce a column is dropped% it cannot be reco'ered"

"nstructor #ote Nhen a column is dropped from a table% any other columns in that table that are marked with the SET #N#SED option are dropped too"

"ntroduction to $racle%i: SQL %-5>

The SET 9(9SE, $ption


Eou use the SET 9(9SE, option to mar; one or more columns as unused+ Eou use the ,RO> 9(9SE, COL9M(S option to remo1e the columns that are mar;ed as unused+
&LTER T&.LE table SET 9(9SE, "column#;

OR
&LTER T&.LE ta%le SET 9(9SE, COL9M( column; &LTER T&.LE table ,RO> 9(9SE, COL9M(S;

%-5@

Copyright Oracle Corporation, 2001. All rights reserved.

The SET 9(9SE, $ption The SET #N#SED option marks one or more columns as unused so that they can be dropped when the demand on system resources is lower" This is a feature a'ailable in 3racleLi and later" )pecifying this clause does not actually remo'e the target columns from each row in the table that is% it does not restore the disk space used by these columns!" Therefore% the response time is faster than if you e$ecuted the DROP clause" 6nused columns are treated as if they were dropped% e'en though their column data remains in the tableGs rows" +fter a column has been marked as unused% you ha'e no access to that column" + SELECT * 8uery will not retrie'e data from unused columns" #n addition% the names and types of columns marked unused will not be displayed during a DESCRI5E% and you can add to the table a new column with the same name as an unused column" SET #N#SED information is stored in the #SER_#N#SED_COL_TA5S dictionary 'iew" The ,RO> 9(9SE, COL9M(S $ption DROP #N#SED COL#MNS remo'es from the table all columns currently marked as unused" You can use this statement when you want to reclaim the e$tra disk space from unused columns in the table" #f the table contains no unused columns% the statement returns with no errors" ALTER TA5LE dept[* SET #N#SED ,la!t_name/" Ta<le altered0 ALTER TA5LE dept[* DROP #N#SED COL#MNS" Ta<le altered0 "ntroduction to $racle%i: SQL %-5@

-ropping a Ta)le
All data and structure in the ta)le is deleted+ An* pending transactions are committed+ All inde(es are dropped+ Eou cannot roll )ac; the ,RO> T&.LE statement+
,RO> T&.LE deptP0; Ta%le dropped7

%-5%

Copyright Oracle Corporation, 2001. All rights reserved.

-ropping a Ta)le The DROP TA5LE statement remo'es the definition of an 3racle table" Nhen you drop a table% the database loses all the data in the table and all the inde$es associated with it" Syntax DROP TA5LE table #n the synta$& table +ui&elines S S S +ll data is deleted from the table" +ny 'iews and synonyms remain but are in'alid" +ny pending transactions are committed" is the name of the table

S 3nly the creator of the table or a user with the DROP AN' TA5LE pri'ilege can remo'e a table" Note: The DROP TA5LE statement% once e$ecuted% is irre'ersible" The 3racle ser'er does not 8uestion the action when you issue the DROP TA5LE statement" #f you own that table or ha'e a highle'el pri'ilege% then the table is immediately remo'ed" +s with all 77L statements% DROP TA5LE is committed automatically"

"ntroduction to $racle%i: SQL %-5%

Changing the #ame of an $)Gect

To change the name of a ta)le: 1ie!: se?uence: or s*non*m: *ou e(ecute the RE(&ME statement+
RE(&ME dept TO detail_dept; Ta%le renamed7

Eou must )e the o!ner of the o)Gect+

%-83

Copyright Oracle Corporation, 2001. All rights reserved.

enaming a Ta)le +dditional 77L statements include the RENAME statement% which is used to rename a table% 'iew% se8uence% or a synonym" Syntax RENAME #n the synta$& old_name ne9_name is the old name of the table% 'iew% se8uence% or synonym" is the new name of the table% 'iew% se8uence% or synonym" old_name TO ne9_name4

You must be the owner of the obAect that you rename"

"ntroduction to $racle%i: SQL %-83

Truncating a Ta)le
The TR9(C&TE T&.LE statement:
emo1es all ro!s from a ta)le eleases the storage space used )* that ta)le

TR9(C&TE T&.LE detail_dept; Ta%le tr)ncated7

Eou cannot roll )ac; ro! remo1al !hen using TR9(C&TE+ Alternati1el*: *ou can remo1e ro!s )* using the ,ELETE statement+

%-81

Copyright Oracle Corporation, 2001. All rights reserved.

Truncating a Ta)le +nother 77L statement is the TR#NCATE TA5LE statement% which is used to remo'e all rows from a table and to release the storage space used by that table" Nhen using the TR#NCATE TA5LE statement% you cannot roll back row remo'al" Syntax TR#NCATE #n the synta$& table is the name of the table You must be the owner of the table or ha'e DELETE TA5LE system pri'ileges to truncate a table" The DELETE statement can also remo'e all rows from a table% but it does not release storage space" The TR#NCATE command is faster" Jemo'ing rows with the TR#NCATE statement is faster than remo'ing them with the DELETE statement for the following reasons& S S S The TR#NCATE statement is a data definition language 77L! statement and generates no rollback information" Truncating a table does not fire the delete triggers of the table" #f the table is the parent of a referential integrity constraint% you cannot truncate the table" 7isable the constraint before issuing the TR#NCATE statement" TA5LE table4

"ntroduction to $racle%i: SQL %-81

Adding Comments to a Ta)le

Eou can add comments to a ta)le or column )* using the COMME(T statement+
COMME(T O( T&.LE employees -S +Employee -n=ormation+; Comment created7

Comments can )e 1ie!ed through the data dictionar* 1ie!s:


L &LL_COL_COMME(TS L 9SER_COL_COMME(TS L &LL_T&._COMME(TS L 9SER_T&._COMME(TS

%-85

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a Comment to a Ta)le You can add a comment of up to 2%000 bytes about a column% table% 'iew% or snapshot by using the COMMENT statement" The comment is stored in the data dictionary and can be 'iewed in one of the following data dictionary 'iews in the COMMENTS column& O ALL_COL_COMMENTS O #SER_COL_COMMENTS O ALL_TA5_COMMENTS O #SER_TA5_COMMENTS Syntax COMMENT ON TA5LE table 6 COL#MN table&column IS Tte>tT" #n the synta$& table column te%t is the name of the table is the name of the column in a table is the te$t of the comment emplo+ee! IS T T"

You can drop a comment from the database by setting it to empty string TT!& COMMENT ON TA5LE

"ntroduction to $racle%i: SQL %-85

Summar*
"n this lesson: *ou should ha1e learned ho! to use --L statements to create: alter: drop: and rename ta)les+
Statement CRE&TE T&.LE &LTER T&.LE ,RO> T&.LE RE(&ME TR9(C&TE COMME(T -escription Creates a ta)le /odifies ta)le structures emo1es the ro!s and ta)le structure Changes the name of a ta)le: 1ie!: se?uence: or s*non*m emo1es all ro!s from a ta)le and releases the storage space Adds comments to a ta)le or 1ie!

%-88

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* #n this lesson% you should ha'e learned how to use 77L commands to create% alter% drop% and rename tables" You also learned how to truncate a table and add comments to a table" CRE&TE T&.LE S ;reate a table" S ;reate a table based on another table by using a sub8uery" &LTER T&.LE S Modify table structures" S ;hange column widths% change column data types% and add columns" ,RO> T&.LE S Jemo'e rows and a table structure" S 3nce e$ecuted% this statement cannot be rolled back" RE(&ME S Jename a table% 'iew% se8uence% or synonym" TR9(C&TE S Jemo'e all rows from a table and release the storage space used by the table" S The DELETE statement remo'es only rows" COMME(T S +dd a comment to a table or a column" S *uery the data dictionary to 'iew the comment" "ntroduction to $racle%i: SQL %-88

4ractice % $1er1ie!
This practice co1ers the follo!ing topics:

Creating ne! ta)les Creating a ne! ta)le )* using the CRE&TE T&.LE &S s*nta( /odif*ing column definitions 9erif*ing that the ta)les e(ist Adding comments to ta)les -ropping ta)les Altering ta)les

%-8=

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice % $1er1ie! ;reate new tables by using the CREATE TA5LE statement" ;onfirm that the new table was added to the database" ;reate the synta$ in the command file% and then e$ecute the command file to create the table"

"nstructor #ote ?$plain what a table instance chart is" Tell students how to interpret a table instance chart" ?$plain that they need to look out for the entries in the ;olumn 0ame% 7ata Type% and Length fields" The other entries are optional% and if these entries e$ist% they are constraints that need to be incorporated as a part of the table definition" Point out to students that the practices are based on the tables that they are creating e$clusi'ely for this lesson" They need to be careful not to alter the other tables in the schema" "ntroduction to $racle%i: SQL %-8=

4ractice % 5" ;reate the DEPT table based on the following table instance chart" Place the synta$ in a script called la<B_-0!1l% then e$ecute the statement in the script to create the table" ;onfirm that the table is created"
%olumn Name 9ey Type Nulls:Uni1ue F9 Table F9 %olumn Data type Len!th N#M5ER E $ARC=AR. 25 ID NAME

2" Populate the DEPT table with data from the DEPARTMENTS table" #nclude only columns that you need" /" ;reate the EMP table based on the following table instance chart" Place the synta$ in a script called la<B_)0!1l% and then e$ecute the statement in the script to create the table" ;onfirm that the table is created"
%olumn Name 9ey Type Nulls:Uni1ue F9 Table F9 %olumn Data type Len!th N#M5ER E $ARC=AR. 25 $ARC=AR. 25 N#M5ER E ID LAST_NAME IRST_NAME DEPT_ID

"ntroduction to $racle%i: SQL %-85

4ractice % 6continued7 4" Modify the EMP table to allow for longer employee last names" ;onfirm your modification"

5" ;onfirm that both the DEPT and EMP tables are stored in the data dictionary" *int+ #SER_TA5LES!

6" ;reate the EMPLO'EES. table based on the structure of the EMPLO'EES table" #nclude only the EMPLO'EE_ID% IRST_NAME% LAST_NAME% SALAR'% and DEPARTMENT_ID columns" 0ame the columns in your new table ID% IRST_NAME% LAST_NAME% SALAR' % and DEPT_ID% respecti'ely" E" 7rop the EMP table" L" Jename the EMPLO'EES. table as EMP" 4" +dd a comment to the DEPT and EMP table definitions describing the tables" ;onfirm your additions in the data dictionary" 50" 7rop the IRST_NAME column from the EMP table" ;onfirm your modification by checking the description of the table" 55" #n the EMP table% mark the DEPT_ID column in the EMP table as #N#SED" ;onfirm your modification by checking the description of the table" 52" 7rop all the #N#SED columns from the EMP table" ;onfirm your modification by checking the description of the table"

"ntroduction to $racle%i: SQL %-8&

"nstructor #ote 6for page %-57 There is an option% CREATE GLO5AL TEMPORAR' TA5LE, that identifies a table as temporary and 'isible to all sessions" The data in a temporary table is 'isible only to the session that inserts data into the table" + temporary table has a definition that persists like the definitions of regular tables% but it contains either session-specific or transaction-specific data" You specify whether the data is session- or transaction-specific with the ON COMMIT keywords" Temporary tables use temporary segments" 6nlike permanent tables% temporary tables and their inde$es do not automatically allocate a segment when they are created" #nstead% segments are allocated when the first INSERT or CREATE TA5LE AS SELECT! statement is performed" This means that if a SELECT% #PDATE% or DELETE statement is performed before the first INSERT% then the table appears to be empty" You can perform 77L commands ALTER TA5LE% DROP TA5LE% CREATE INDE%% and so on! on a temporary table only when no session is currently bound to it" + session gets bound to a temporary table when an INSERT is performed on it" The session gets unbound by a TR#NCATE% at session termination% or by doing a COMMIT or A5ORT for a transaction-specific temporary table" Temporary segments are deallocated at the end of the transaction for transaction-specific temporary tables and at the end of the session for session-specific temporary tables" (or more information on temporary tables and CREATE TA5LE% refer to Oracle9i &oncepts, >Temporary Tables"@

"ntroduction to $racle%i: SQL %-8>

"ntroduction to $racle%i: SQL %-8@

"ncluding Constraints

Copyright Oracle Corporation, 2001. All rights reserved.

Schedule:

Timing 45 minutes 25 minutes E0 minutes

Topic Lecture Practice Total

$)Gecti1es
After completing this lesson: *ou should )e a)le to do the follo!ing: -escri)e constraints

Create and maintain constraints

13-5

Copyright Oracle Corporation, 2001. All rights reserved.

Lesson Aim #n this lesson% you learn how to implement business rules by including integrity constraints"

"ntroduction to $racle%i: SQL 13-5

What are ConstraintsM


Constraints enforce rules at the ta)le le1el+ Constraints pre1ent the deletion of a ta)le if there are dependencies+ The follo!ing constraint t*pes are 1alid:
L (OT (9LL L 9(-D9E L >R-M&RA 8EA L FORE-@( 8EA L C2EC8

13-8

Copyright Oracle Corporation, 2001. All rights reserved.

Constraints The 3racle )er'er uses constraints to pre'ent in'alid data entry into tables" You can use constraints to do the following& S S S ?nforce rules on the data in a table whene'er a row is inserted% updated% or deleted from that table" The constraint must be satisfied for the operation to succeed" Pre'ent the deletion of a table if there are dependencies from other tables Pro'ide rules for 3racle tools% such as 3racle 7e'eloper

Data ,nte!rity %onstraints %onstraint Description


NOT N#LL #NI_#E PRIMAR' 2E' OREIGN 2E' C=EC2 )pecifies that the column cannot contain a null 'alue )pecifies a column or combination of columns whose 'alues must be uni8ue for all rows in the table 6ni8uely identifies each row of the table ?stablishes and enforces a foreign key relationship between the column and a column of the referenced table )pecifies a condition that must be true

(or more information% see Oracle9i SQL Reference, >CONSTRAINT"@ "ntroduction to $racle%i: SQL 13-8

Constraint Cuidelines

#ame a constraint or the $racle ser1er generates a name )* using the SAS_Cn format+ Create a constraint either:
At the same time as the ta)le is created: or After the ta)le has )een created

-efine a constraint at the column or ta)le le1el+ 9ie! a constraint in the data dictionar*+

13-=

Copyright Oracle Corporation, 2001. All rights reserved.

Constraint Cuidelines +ll constraints are stored in the data dictionary" ;onstraints are easy to reference if you gi'e them a meaningful name" ;onstraint names must follow the standard obAect-naming rules" #f you do not name your constraint% the 3racle ser'er generates a name with the format S'S_Cn% where n is an integer so that the constraint name is uni8ue" ;onstraints can be defined at the time of table creation or after the table has been created" You can 'iew the constraints defined for a specific table by looking at the #SER_CONSTRAINTS data dictionary table"

"ntroduction to $racle%i: SQL 13-=

-efining Constraints

CRE&TE T&.LE /schema70table "column datatype /,EF&9LT expr0 /column_constraint0, 777 /table_constraint0 /,7770#;

CRE&TE T&.LE employees" employee_id (9M.ER"G#, =irst_name Q&RC2&R!"!0#, 777 $o%_id Q&RC2&R!" 0# (OT (9LL, CO(STR&-(T emp_emp_id_pK >R-M&RA 8EA "EM>LOAEE_-,##;

13-5

Copyright Oracle Corporation, 2001. All rights reserved.

-efining Constraints The slide gi'es the synta$ for defining constraints while creating a table" #n the synta$& schema table DE A#LT expr column is the same as the ownerGs name is the name of the table specifies a default 'alue to use if a 'alue is omitted in the INSERT statement is the name of the column datat$pe is the is an integrity is an

columnGs data type and length column_constraint

constraint as part of the column definition table_constraint integrity constraint as part of the table definition (or more information% see Oracle9i SQL Reference, >CREATE TA5LE"@

"ntroduction to $racle%i: SQL 13-5

-efining Constraints
Column constraint le1el

column /CO(STR&-(T constraint_name0 constraint_type,

Ta)le constraint le1el

column,... /CO(STR&-(T constraint_name0 constraint_type "column, 777#,

13-&

Copyright Oracle Corporation, 2001. All rights reserved.

-efining Constraints 6continued7 ;onstraints are usually created at the same time as the table" ;onstraints can be added to a table after its creation and also temporarily disabled" ;onstraints can be defined at one of two le'els"
%onstraint Le*el ;olumn Table Description Jeferences a single column and is defined within a specification for the owning column1 can define any type of integrity constraint Jeferences one or more columns and is defined separately from the definitions of the columns in the table1 can define any constraints e$cept NOT N#LL

#n the synta$& constraint_name constraint_t$pe is the name of the constraint is the type of the constraint

"nstructor #ote ?$plain that the column le'el and the table le'el refer to location in the synta$" "ntroduction to $racle%i: SQL 13-&

The (OT (9LL Constraint


Ensures that null 1alues are not permitted for the column:

'
(OT (9LL constraint 6#o ro! can contain a null 1alue for this column+7 A)sence of (OT (9LL constraint 6An* ro! can contain null for this column+7

(OT (9LL constraint

13->

Copyright Oracle Corporation, 2001. All rights reserved.

The (OT (9LL Constraint The NOT N#LL constraint ensures that the column contains no null 'alues" ;olumns without the NOT N#LL constraint can contain null 'alues by default"

"ntroduction to $racle%i: SQL 13->

The (OT (9LL Constraint


"s defined at the column le1el:
CRE&TE T&.LE employees" employee_id (9M.ER"G#, last_name Q&RC2&R!"!:# (OT (9LL, salary (9M.ER"P,!#, commission_pct (9M.ER"!,!#, 5ire_date ,&TE CO(STR&-(T emp_5ire_date_nn (OT (9LL, 777

S*stem named

2ser named

13-@

Copyright Oracle Corporation, 2001. All rights reserved.

The (OT (9LL Constraint 6continued7 The NOT N#LL constraint can be specified only at the column le'el% not at the table le'el" The slide e$ample applies the NOT N#LL constraint to the LAST_NAME and =IRE_DATE columns of the EMPLO'EES table" ,ecause these constraints are unnamed% the 3racle ser'er creates names for them" You can specify the name of the constraint when you specify the constraint& 000 la!t_name $ARC=AR.,.C/ CONSTRAINT emp_la!t_name_nn NOT N#LL000 Note: The constraint e$amples described in this lesson may not be present in the sample tables pro'ided with the course" #f desired% these constraints can be added to the tables"

"ntroduction to $racle%i: SQL 13-@

The 9(-D9E Constraint


9(-D9E constraint

EM>LOAEES

'
-(SERT -(TO

Allo!ed #ot allo!ed: alread* e(ists

13-%

Copyright Oracle Corporation, 2001. All rights reserved.

The 9(-D9E Constraint + #NI_#E key integrity constraint re8uires that e'ery 'alue in a column or set of columns key! be uni8ue2that is% no two rows of a table can ha'e duplicate 'alues in a specified column or set of columns" The column or set of columns! included in the definition of the #NI_#E key constraint is called the unique 2ey" #f the #NI_#E constraint comprises more than one column% that group of columns is called a composite unique 2ey" #NI_#E constraints allow the input of nulls unless you also define NOT N#LL constraints for the same columns" #n fact% any number of rows can include nulls for columns without NOT N#LL constraints because nulls are not considered e8ual to anything" + null in a column or in all columns of a composite #NI_#E key! always satisfies a #NI_#E constraint" Note: ,ecause of the search mechanism for #NI_#E constraints on more than one column% you cannot ha'e identical 'alues in the non-null columns of a partially null composite #NI_#E key constraint"

"nstructor #ote ?$plain to students that since the 4SMIT= e-mail #7 already e$ists after the first insertion% the second entry is not allowed" "ntroduction to $racle%i: SQL 13-%

The 9(-D9E Constraint


-efined at either the ta)le le1el or the column le1el:
CRE&TE T&.LE employees" employee_id (9M.ER"G#, last_name Q&RC2&R!"!:# (OT (9LL, email Q&RC2&R!"!:#, salary (9M.ER"P,!#, commission_pct (9M.ER"!,!#, 5ire_date ,&TE (OT (9LL, 777 CO(STR&-(T emp_email_)K 9(-D9E"email##;

13-13

Copyright Oracle Corporation, 2001. All rights reserved.

The 9(-D9E Constraint 6continued7 #NI_#E constraints can be defined at the column or table le'el" + composite uni8ue key is created by using the table le'el definition" The e$ample on the slide applies the #NI_#E constraint to the EMAIL column of the EMPLO'EES table" The name of the constraint is EMP_EMAIL_#2"" Note: The 3racle ser'er enforces the #NI_#E constraint by implicitly creating a uni8ue inde$ on the uni8ue key column or columns"

"ntroduction to $racle%i: SQL 13-13

The >R-M&RA 8EA Constraint


,E>&RTME(TS
>R-M&RA 8EA

'
#ot allo!ed 6#ull 1alue7 -(SERT -(TO

#ot allo!ed 653 alread* e(ists7


13-11 Copyright Oracle Corporation, 2001. All rights reserved.

The >R-M&RA 8EA Constraint + PRIMAR' 2E' constraint creates a primary key for the table" 3nly one primary key can be created for each table" The PRIMAR' 2E' constraint is a column or set of columns that uni8uely identifies each row in a table" This constraint enforces uni8ueness of the column or column combination and ensures that no column that is part of the primary key can contain a null 'alue"

"ntroduction to $racle%i: SQL 13-11

The >R-M&RA 8EA Constraint


-efined at either the ta)le le1el or the column le1el:
CRE&TE T&.LE departments" department_id (9M.ER"H#, department_name Q&RC2&R!"30# CO(STR&-(T dept_name_nn (OT (9LL, mana;er_id (9M.ER"G#, location_id (9M.ER"H#, CO(STR&-(T dept_id_pK >R-M&RA 8EA"department_id##;

13-15

Copyright Oracle Corporation, 2001. All rights reserved.

The >R-M&RA 8EA Constraint 6continued7 PRIMAR' 2E' constraints can be defined at the column le'el or table le'el" + composite PRIMAR' 2E' is created by using the table-le'el definition" + table can ha'e only one PRIMAR' 2E' constraint but can ha'e se'eral #NI_#E constraints" The e$ample on the slide defines a PRIMAR' 2E' constraint on the DEPARTMENT_ID column of the DEPARTMENTS table" The name of the constraint is DEPT_ID_P2" Note: + #NI_#E inde$ is automatically created for a PRIMAR' 2E' column"

"nstructor #ote The e$ample shown will not work in your schema because the DEPARTMENTS table already e$ists" To demonstrate this code% modify the name of the table within the script and then run the script"

"ntroduction to $racle%i: SQL 13-15

The FORE-@( 8EA Constraint


,E>&RTME(TS

>R-M&RA 8EA

'
FORE-@( 8EA

EM>LOAEES

'
-(SERT -(TO

#ot allo!ed 6% does not e(ist7 Allo!ed

13-18

Copyright Oracle Corporation, 2001. All rights reserved.

The FORE-@( 8EA Constraint The OREIGN 2E'% or referential integrity constraint% designates a column or combination of columns as a foreign key and establishes a relationship between a primary key or a uni8ue key in the same table or a different table" #n the e$ample on the slide% DEPARTMENT_ID has been defined as the foreign key in the EMPLO'EES table dependent or child table!1 it references the DEPARTMENT_ID column of the DEPARTMENTS table the referenced or parent table!" + foreign key 'alue must match an e$isting 'alue in the parent table or be N#LL" (oreign keys are based on data 'alues and are purely logical% not physical% pointers"

"nstructor #ote ?$plain to students that you cannot create a foreign key without e$isting primary key 'alues" "ntroduction to $racle%i: SQL 13-18

The FORE-@( 8EA Constraint


-efined at either the ta)le le1el or the column le1el:
CRE&TE T&.LE employees" employee_id (9M.ER"G#, last_name Q&RC2&R!"!:# (OT (9LL, email Q&RC2&R!"!:#, salary (9M.ER"P,!#, commission_pct (9M.ER"!,!#, 5ire_date ,&TE (OT (9LL, 777 department_id (9M.ER"H#, CO(STR&-(T emp_dept_=K FORE-@( 8EA "department_id# REFERE(CES departments"department_id#, CO(STR&-(T emp_email_)K 9(-D9E"email##;

13-1=

Copyright Oracle Corporation, 2001. All rights reserved.

The FORE-@( 8EA Constraint 6continued7 OREIGN 2E' constraints can be defined at the column or table constraint le'el" + composite foreign key must be created by using the table-le'el definition" The e$ample on the slide defines a OREIGN 2E' constraint on the DEPARTMENT_ID column of the EMPLO'EES table% using table-le'el synta$" The name of the constraint is EMP_DEPTID_ 2" The foreign key can also be defined at the column le'el% pro'ided the constraint is based on a single column" The synta$ differs in that the keywords OREIGN 2E' do not appear" (or e$ample& CREATE TA5LE emplo+ee! ,000 department_id N#M5ER,Z/ CONSTRAINT emp_deptid_U^ RE ERENCES department!,department_id/, 000 /

"ntroduction to $racle%i: SQL 13-1=

FORE-@( 8EA Constraint Ne*!ords


FORE-@( 8EA: -efines the column in the child ta)le at the ta)le constraint le1el REFERE(CES: "dentifies the ta)le and column in the parent ta)le O( ,ELETE C&SC&,E: -eletes the dependent ro!s in the child ta)le !hen a ro! in the parent ta)le is deleted+ O( ,ELETE SET (9LL: Con1erts dependent foreign ;e* 1alues to null

13-15

Copyright Oracle Corporation, 2001. All rights reserved.

The FORE-@( 8EA Constraint 6continued7 The foreign key is defined in the child table% and the table containing the referenced column is the parent table" The foreign key is defined using a combination of the following keywords& O OREIGN 2E' is used to define the column in the child table at the table constraint le'el" O RE ERENCES identifies the table and column in the parent table" O ON DELETE CASCADE indicates that when the row in the parent table is deleted% the dependent rows in the child table will also be deleted" O ON DELETE SET N#LL con'erts foreign key 'alues to null when the parent 'alue is remo'ed" The default beha'ior is called the restrict rule% which disallows the update or deletion of referenced data" Nithout the ON DELETE CASCADE or the ON DELETE SET N#LL options% the row in the parent table cannot be deleted if it is referenced in the child table"

"ntroduction to $racle%i: SQL 13-15

The C2EC8 Constraint


-efines a condition that each ro! must satisf* The follo!ing e(pressions are not allo!ed:
eferences to C9RRQ&L: (ENTQ&L: LEQEL: and RO1(9M pseudocolumns Calls to SAS,&TE: 9-,: 9SER: and 9SERE(Q functions Queries that refer to other 1alues in other ro!s

777, salary (9M.ER"!# CO(STR&-(T emp_salary_min C2EC8 "salary ? 0#,777

13-1&

Copyright Oracle Corporation, 2001. All rights reserved.

The C2EC8 Constraint The C=EC2 constraint defines a condition that each row must satisfy" The condition can use the same constructs as 8uery conditions% with the following e$ceptions& S Jeferences to the C#RR$AL% NE%T$AL% LE$EL% and RO&N#M pseudocolumns S S ;alls to S'SDATE% #ID% #SER% and #SEREN$ functions *ueries that refer to other 'alues in other rows

+ single column can ha'e multiple C=EC2 constraints which refer to the column in its definition" There is no limit to the number of C=EC2 constraints which you can define on a column" C=EC2 constraints can be defined at the column le'el or table le'el" CREATE TA5LE emplo+ee! ,000 !alar+ N#M5ER,[,./ CONSTRAINT emp_!alar+_min C=EC2 ,!alar+ D */, 000 "nstructor #ote ?$plain what pseudocolumns are" Pseudocolumns are not actual columns in a table but they beha'e like columns" (or e$ample% you can select 'alues from a pseudocolumn" <owe'er% you cannot insert into% update% or delete from a pseudocolumn" Pseudocolumns can be used in )*L statements" "ntroduction to $racle%i: SQL 13-1&

Adding a Constraint S*nta(


2se the &LTER T&.LE statement to:

Add or drop a constraint: )ut not modif* its structure Ena)le or disa)le constraints Add a (OT (9LL constraint )* using the MO,-FA clause
&LTER T&.LE table &,, /CO(STR&-(T constraint0 type "column#;

13-1>

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a Constraint You can add a constraint for e$isting tables by using the ALTER TA5LE statement with the ADD clause" #n the synta$& table is the name of the table constraint is the name of the constraint t$pe is the constraint type column is the name of the column affected by the constraint The constraint name synta$ is optional% although recommended" #f you do not name your constraints% the system will generate constraint names" +ui&elines S You can add% drop% enable% or disable a constraint% but you cannot modify its structure" S You can add a NOT N#LL constraint to an e$isting column by using the MODI ' clause of the ALTER TA5LE statement" Note: You can define a NOT N#LL column only if the table is empty or if the column has a 'alue for e'ery row" "nstructor #ote You can defer checking constraints for 'alidity until the end of the transaction" + constraint is deferred if the system checks that it is satisfied only on commit" #f a deferred constraint is 'iolated% then committing causes the transaction to roll back" + constraint is immediate if it is checked at the end of each statement" #f it is 'iolated% the statement is rolled back immediately" "ntroduction to $racle%i: SQL 13-1>

Adding a Constraint
Add a FORE-@( 8EA constraint to the EM>LOAEES ta)le indicating that a manager must alread* e(ist as a 1alid emplo*ee in the EM>LOAEES ta)le+
&LTER T&.LE employees &,, CO(STR&-(T emp_mana;er_=K FORE-@( 8EA"mana;er_id# REFERE(CES employees"employee_id#; Ta%le altered7

13-1@

Copyright Oracle Corporation, 2001. All rights reserved.

Adding a Constraint 6continued7 The e$ample on the slide creates a OREIGN 2E' constraint on the EMPLO'EES table" The constraint ensures that a manager e$ists as a 'alid employee in the EMPLO'EES table"

"nstructor #ote To add a NOT N#LL constraint% use the ALTER TA5LE MODI ' synta$& ALTER TA5LE emplo+ee! MODI ' ,!alar+ CONSTRAINT emp_!alar+_nn NOT N#LL/" "ntroduction to $racle%i: SQL 13-1@

-ropping a Constraint
emo1e the manager constraint from the EM>LOAEES ta)le+
employees emp_mana;er_=K;

&LTER T&.LE ,RO> CO(STR&-(T Ta%le altered7

emo1e the >R-M&RA 8EA constraint on the ,E>&RTME(TS ta)le and drop the associated FORE-@( 8EA constraint on the EM>LOAEES7,E>&RTME(T_-, column+

&LTER T&.LE departments ,RO> >R-M&RA 8EA C&SC&,E; Ta%le altered7


13-1% Copyright Oracle Corporation, 2001. All rights reserved.

-ropping a Constraint To drop a constraint% you can identify the constraint name from the #SER_CONSTRAINTS and #SER_CONS_COL#MNS data dictionary 'iews" Then use the ALTER TA5LE statement with the DROP clause" The CASCADE option of the DROP clause causes any dependent constraints also to be dropped" Syntax ALTER TA5LE table DROP PRIMAR' 2E' 6 #NI_#E ,column/ 6 CONSTRAINT constraint PCASCADEQ" #n the synta$& table column constraint is the name of the table is the name of the column affected by the constraint is the name of the constraint

Nhen you drop an integrity constraint% that constraint is no longer enforced by the 3racle ser'er and is no longer a'ailable in the data dictionary"

"ntroduction to $racle%i: SQL 13-1%

-isa)ling Constraints
E(ecute the ,-S&.LE clause of the &LTER T&.LE statement to deacti1ate an integrit* constraint+

Appl* the C&SC&,E option to disa)le dependent integrit* constraints+


employees emp_emp_id_pK C&SC&,E;

&LTER T&.LE ,-S&.LE CO(STR&-(T Ta%le altered7

13-53

Copyright Oracle Corporation, 2001. All rights reserved.

-isa)ling a Constraint You can disable a constraint without dropping it or re-creating it by using the ALTER TA5LE statement with the DISA5LE clause" Syntax ALTER TA5LE table DISA5LE CONSTRAINT constraint PCASCADEQ" #n the synta$& table constraint +ui&elines S S S You can use the DISA5LE clause in both the CREATE TA5LE statement and the ALTER TA5LE statement" The CASCADE clause disables dependent integrity constraints" 7isabling a uni8ue or primary key constraint remo'es the uni8ue inde$" is the name of the table is the name of the constraint

"ntroduction to $racle%i: SQL 13-53

Ena)ling Constraints

Acti1ate an integrit* constraint currentl* disa)led in the ta)le definition )* using the E(&.LE clause+
employees emp_emp_id_pK;

&LTER T&.LE E(&.LE CO(STR&-(T Ta%le altered7

A 9(-D9E or >R-M&RA 8EA inde( is automaticall* created if *ou ena)le a 9(-D9E ;e* or >R-M&RA 8EA constraint+

13-51

Copyright Oracle Corporation, 2001. All rights reserved.

Ena)ling a Constraint You can enable a constraint without dropping it or re-creating it by using the ALTER TA5LE statement with the ENA5LE clause" Syntax ALTER ENA5LE TA5LE table CONSTRAINT constraint4

#n the synta$& table is the name of the table constraint is the name of the constraint +ui&elines S #f you enable a constraint% that constraint applies to all the data in the table" +ll the data in the table must fit the constraint" S #f you enable a #NI_#E key or PRIMAR' 2E' constraint% a #NI_#E or PRIMAR' 2E' inde$ is created automatically" S You can use the ENA5LE clause in both the CREATE TA5LE statement and the ALTER TA5LE statement" S ?nabling a primary key constraint that was disabled with the CASCADE option does not enable any foreign keys that are dependent upon the primary key" "nstructor #ote Please read the #nstructor 0ote on page 50-24 for information on the $ALIDATE and NO$ALIDATE options" "ntroduction to $racle%i: SQL 13-51

Cascading Constraints

The C&SC&,E CO(STR&-(TS clause is used along !ith the ,RO> COL9M( clause+ The C&SC&,E CO(STR&-(TS clause drops all referential integrit* constraints that refer to the primar* and uni?ue ;e*s defined on the dropped columns+ The C&SC&,E CO(STR&-(TS clause also drops all multicolumn constraints defined on the dropped columns+

13-55

Copyright Oracle Corporation, 2001. All rights reserved.

Cascading Constraints This statement illustrates the usage of the CASCADE CONSTRAINTS clause" +ssume table TESTis created as follows& CREATE TA5LE te!t- , p^ N#M5ER PRIMAR' 2E', U^ N#M5ER, col- N#M5ER, col. N#M5ER, CONSTRAINT U^_con!traint OREIGN 2E' ,U^/ RE ERENCES te!t-, CONSTRAINT c^- C=EC2 ,p^ D * and col- D */, CONSTRAINT c^. C=EC2 ,col. D *//" +n error is returned for the following statements& ALTER TA5LE te!t- DROP ,p^/" -- pk is a parent key ALTER TA5LE te!t- DROP ,col-/" -- col5 is referenced by multicolumn constraint c^-

"ntroduction to $racle%i: SQL 13-55

Cascading Constraints

E(ample:
&LTER T&.LE test ,RO> "pK# C&SC&,E CO(STR&-(TS; Ta%le altered7 &LTER T&.LE test ,RO> "pK, =K, col # C&SC&,E CO(STR&-(TS; Ta%le altered7

13-58

Copyright Oracle Corporation, 2001. All rights reserved.

Cascading Constraints 6continued7 )ubmitting the following statement drops column P2% the primary key constraint% the U^_con!traint foreign key constraint% and the check constraint% C2-& ALTER TA5LE te!t- DROP ,p^/ CASCADE CONSTRAINTS" #f all columns referenced by the constraints defined on the dropped columns are also dropped% then CASCADE CONSTRAINTS is not re8uired" (or e$ample% assuming that no other referential constraints from other tables refer to column P2% it is 'alid to submit the following statement without the CASCADE CONSTRAINTS clause& ALTER TA5LE te!t- DROP ,p^, U^, col-/"

"nstructor #ote Let the students know that if any constraint is referenced by columns from other tables or remaining columns in the target table% then you must specify CASCADE CONSTRAINTS" 3therwise% the statement aborts and the error ORAA-.BB-8 col3mn i! reUerenced in a m3lticol3mn con!traint is returned" "ntroduction to $racle%i: SQL 13-58

9ie!ing Constraints
Quer* the 9SER_CO(STR&-(TS ta)le to 1ie! all constraint definitions and names+
SELECT FROM 12ERE constraint_name, constraint_type, searc5_condition )ser_constraints ta%le_name 3 +EM>LOAEES+;

'

13-5=

Copyright Oracle Corporation, 2001. All rights reserved.

9ie!ing Constraints +fter creating a table% you can confirm its e$istence by issuing a DESCRI5E command" The only constraint that you can 'erify is the NOT N#LL constraint" To 'iew all constraints on your table% 8uery the #SER_CONSTRAINTS table" The e$ample on the slide displays the constraints on the EMPLO'EES table" Note: ;onstraints that are not named by the table owner recei'e the system-assigned constraint name" #n constraint type% C stands for C=EC2% P for PRIMAR' 2E'% R for referential integrity% and # for #NI_#E key" 0otice that the NOT N#LL constraint is really a C=EC2 constraint"

"nstructor #ote Point out to students that the NOT N#LL constraint is stored in the data dictionary as a C=EC2 constraint" 7raw their attention to the constraint type% for the NOT N#LL constraints in the slide" The entry in the con!traint_t+pe field is C as in C=EC2! for these constraints" "ntroduction to $racle%i: SQL 13-5=

9ie!ing the Columns Associated !ith Constraints


9ie! the columns associated !ith the constraint names in the 9SER_CO(S_COL9M(S 1ie!+
SELECT FROM 12ERE constraint_name, col)mn_name )ser_cons_col)mns ta%le_name 3 +EM>LOAEES+;

'

13-55

Copyright Oracle Corporation, 2001. All rights reserved.

9ie!ing Constraints 6continued7 You can 'iew the names of the columns in'ol'ed in constraints by 8uerying the #SER_CONS_COL#MNS data dictionary 'iew" This 'iew is especially useful for constraints that use system-assigned names"

"ntroduction to $racle%i: SQL 13-55

Summar*
"n this lesson: *ou should ha1e learned ho! to create constraints+ T*pes of constraints:
L (OT (9LL L 9(-D9E L >R-M&RA 8EA L FORE-@( 8EA L C2EC8

Eou can ?uer* the 9SER_CO(STR&-(TS ta)le to 1ie! all constraint definitions and names+

13-5&

Copyright Oracle Corporation, 2001. All rights reserved.

Summar* #n this lesson% you should ha'e learned how the 3racle ser'er uses constraints to pre'ent in'alid data entry into tables" You also learned how to implement the constraints in 77L statements" The following constraint types are 'alid& O NOT N#LL O #NI_#E O PRIMAR' 2E' O OREIGN 2E' O C=EC2 You can 8uery the #SER_CONSTRAINTS table to 'iew all constraint definitions and names"

"ntroduction to $racle%i: SQL 13-5&

4ractice 13 $1er1ie!
This practice co1ers the follo!ing topics:

Adding constraints to e(isting ta)les Adding more columns to a ta)le -ispla*ing information in data dictionar* 1ie!s

13-5>

Copyright Oracle Corporation, 2001. All rights reserved.

4ractice 13 $1er1ie! #n this practice% you will add constraints and more columns to a table using the statements co'ered in this lesson" Note: #t is recommended that you name the constraints that you define during the practices"

"ntroduction to $racle%i: SQL 13-5>

4ractice 13 5" +dd a table-le'el PRIMAR' 2E' constraint to the EMP table on the ID column" The constraint should be named at creation" 0ame the constraint m+_emp_id_p^" 7int: The constraint is enabled as soon as the ALTER TA5LE command e$ecutes successfully" 2" ;reate a PRIMAR' 2E' constraint to the DEPT table using the ID column" The constraint should be named at creation" 0ame the constraint m+_dept_id_p^" 7int: The constraint is enabled as soon as the ALTER TA5LE command e$ecutes successfully" /" +dd a column DEPT_ID to the EMP table" +dd a foreign key reference on the EMP table that ensures that the employee is not assigned to a none$istent department" 0ame the constraint m+_emp_dept_id_U^" 4" ;onfirm that the constraints were added by 8uerying the #SER_CONSTRAINTS 'iew" 0ote the types and names of the constraints" )a'e your statement te$t in a file called la<-*_Z0!1l"

5" 7isplay the obAect names and types from the #SER_O54ECTS data dictionary 'iew for the EMP and DEPT tables" 0otice that the new tables and a new inde$ were created" #f you ha'e time% complete the following e$ercise& 6" Modify the EMP table" +dd a COMMISSION column of N#M5ER data type% precision 2% scale 2" +dd a constraint to the commission column that ensures that a commission 'alue is greater than 9ero"

"ntroduction to $racle%i: SQL 13-5@

"nstructor #ote 6for pages 13-517 You can also set constraints to $ALIDATE or NO$ALIDATE% in any combination with ENA5LE or DISA5LE% where& O $ALIDATE ensures that e$isting data conforms to the constraint" O NO$ALIDATE means that some e$isting data may not conform to the constraint" #n addition& O ENA5LE $ALIDATE is the same as ENA5LE" The constraint is checked and is guaranteed to hold for all rows" O ENA5LE NO$ALIDATE means that the constraint is checked% but it does not ha'e to be true for all rows" This allows e$isting rows to 'iolate the constraint while ensuring that all new or modified rows are 'alid" S #n an ALTER TA5LE statement% ENA5LE NO$ALIDATE resumes constraint checking on disabled constraints without first 'alidating all data in the table" O DISA5LE NO$ALIDATE is the same as DISA5LE" The constraint is not checked and is not necessarily true" O DISA5LE $ALIDATE disables the constraint% drops the inde$ on the constraint% and disallows any modification of the constrained columns" Transitions between these states are go'erned by the following rules& O ENA5LE implies $ALIDATE% unless NO$ALIDATE is specified" O DISA5LE implies NO$ALIDATE% unless $ALIDATE is specified" O $ALIDATE and NO$ALIDATE do not ha'e any default implications for the ENA5LE and DISA5LE states" S S S Nhen a uni8ue or primary key mo'es from the DISA5LE state to the ENA5LE state% and there is no e$isting inde$% a uni8ue inde$ is automatically created" )imilarly% when a uni8ue or primary key mo'es from ENA5LE to DISA5LE and it is enabled with a uni8ue inde$% the uni8ue inde$ is dropped" Nhen any constraint is mo'ed from the NO$ALIDATE state to the $ALIDATE state% all data must be checked" This can be 'ery slow"! <owe'er% mo'ing from $ALIDATE to NO$ALIDATE simply forgets that the data was e'er checked" Mo'ing a single constraint from the ENA5LE NO$ALIDATE state to the ENA5LE $ALIDATE state does not block reads% writes% or other 77L statements" #t can be done in parallel" ALTER TA5LE emplo+ee! ENA5LE NO$ALIDATE CONSTRAINT EMP_EMAIL_#2" ALTER TA5LE emplo+ee! ENA5LE NO$ALIDATE PRIMAR' 2E' ENA5LE NO$ALIDATE #NI_#E ,emplo+ee_id, la!t_name/" The following statements enable or 'alidate disabled integrity constraints& ALTER TA5LE emplo+ee! MODI ' CONSTRAINT emp_email_3^ $ALIDATE" ALTER TA5LE emplo+ee! MODI ' PRIMAR' 2E' ENA5LE NO$ALIDATE" "ntroduction to $racle%i: SQL 13-5%

The following statements enable no'alidate disabled integrity constraints&

"ntroduction to $racle%i: SQL 13-83