Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 32

Selecting Data from Oracle

In this chapter, you will understand and demonstrate knowledge in the following areas: Selecting rows Limiting selected output Using single-row functions The first exam in the Oracle ertified !rofessional series co"ers many #asic areas of data#ase usage and design$ %"ery Oracle user, de"eloper, and &'( should ha"e complete mastery in these areas #efore mo"ing on into other test areas such as data#ase design, administration, #ackup and reco"ery, and tuning$ This unit assumes little or no prior knowledge of Oracle in order to help the user go from ne"er using Oracle to ha"ing enough expertise in the Oracle ser"er product to maintain and enhance existing applications and de"elop small new ones$ The fi"e chapters in this unit will function as the #asis for understanding the rest of the #ook$ This chapter will co"er se"eral aspects of data retrie"al from the Oracle data#ase, including selecting rows, limiting the selection, single-row functions, )oining data from two or more ta#les, grouping functions, su#*ueries, and specifying "aria#les at execution time$ The content of this chapter co"ers material comprising +, percent of test content on O ! %xam +$

Selecting Rows
In this section, you will co"er the following areas related to selecting rows: -riting select statements !erforming arithmetic e*uations .andling /ULL "alues 0enaming columns with column aliases !utting columns together with concatenation %diting S1L *ueries within S1L2!lus Use of Oracle for many people #egins with usage of an existing Oracle application in an organi3ation$ The first tool many people see for selecting data directly from the Oracle relational data#ase management system is called S1L2!lus$ -hen users first start S1L2!lus, in most cases they must enter their Oracle username and password in order to #egin a session with the Oracle data#ase$ There are some exceptions to this rule that utili3e the password authentication pro"ided with the operating system$ The next unit, co"ering O ! %xam 4, will explore the methods and implications of starting S1L2!lus sessions without supplying an Oracle username and password$ The following examples show how you might #egin a session$ $> sqlplus jason/athena or

$> sqlplus / ( session is an interacti"e runtime en"ironment in which the user enters a command to retrie"e data and Oracle performs a series of acti"ities to o#tain the data that the user asked for$ -hat does interacti"e mean5 It means that Oracle and the user ha"e an interacti"e 6con"ersation6 in which the user asks Oracle to pro"ide certain pieces of information and Oracle pro"ides it$ on"ersation implies language$ In order for the user and Oracle to communicate, they must #oth speak the same language$ The language users 6speak6 to Oracle in order to retrie"e data is a special type of language called Structured 1uery Language, or S1L for short$ S1L can #e pronounced as three indi"idual letters, or in the same way as 6se*uel$6 S1L is a 6functional6 language$ ( functional language is one that allows the users to specify the types of things they want to see happen in terms of the results they want$ ontrast this approach to other languages you may ha"e heard a#out or programmed in, such as 77 or O'OL$ These other languages are often referred to as 6procedural6 programming languages #ecause the code written in these languages implies an end result #y explicitly defining the means, or the procedure, #y which to get there$ In contrast, S1L explicitly defines the end result, lea"ing it up to Oracle to determine the method #y which to o#tain the data$ &ata selection can #e accomplished using the following code listing$ SELECT * FROM emp WHERE empid = 39334; This S1L statement asks Oracle to pro"ide all data from the %8! ta#le where the "alue in a certain column called %8!I& e*uals 9:99;$ The following #lock of code from an imaginary procedural programming language similar to illustrates how the same function may #e handled #y explicitly defining the means to the end$ Include <stdio.h> Include <string.h> Include <rdbms.h> Int *empid; Char *statement; Type emp_rec is record ( Int empid; Char[10] emp_name; Int salary; ) Void main() { Access_table(emp); Open(statement.memaddr); Strcpy("SELECT * FROM EMP WHERE EMPID = 39334",statement.text); parse(statement);

execute(statement); for (I=1,I=statement.results,I+1) { fetch(statement.result[I],emp_rec); printf(emp_rec); } close(statement.memaddr); } Of course, that -like #lock of code would not compile anywhere #ut in the imagination of the reader, #ut the point of the example is clear<other languages define a means toward an end, while S1L allows the user to define the end in and of itself$

Writing SELECT Statements


The most common type of S1L statement executed in most data#ase en"ironments is the query, or select statement$ Select statements are designed to pull re*uested data from the data#ase$ -here is data stored in the data#ase5 &ata is stored in special data#ase o#)ects called tables$ ( ta#le in Oracle is similar in concept to Ta#le +-+$ It has columns and rows, each of which is meant to #e uni*ue$ =or more information a#out ta#les, see the next chapter$ S1L pro"ides a reada#le interface used to pull data from the %8! ta#le as designated in the preceding statement$ Empid 9:99; ;:?9: A@;@9 @4@9: ;:9:4 Lastname Smith 1ian .arper -alla Spanky Fname

Salary
>ina Lee 0od 0a)endra Stacy ,?,@@@ :@,@@@ ;?,@@@ A@,@@@ +@@,@@@

Table 1: E ! The user can issue a simple select statement that is designed to pull all data from the ta#le shown in Ta#le +-+$ -hen S1L2!lus is started, it produces se"eral components of information, including the "ersion of S1L2!lus #eing used, the date, the "ersion of the Oracle data#ase #eing accessed, the "ersion

of !LBS1L in use, and the ser"er options a"aila#le on the data#ase$ The following code #lock demonstrates S1L2!lus$ SQL*Plus: Release 3.2.3.0.0 - Production on Tue Feb 03 18:53:11 1998 Copyright (c) Oracle Corporation 1979, 1994. All rights reserved. Connected to: Oracle7 Release 7.3.4.0.1 With the distributed and replication options PL/SQL Release 2.3.0.0.0 Production SQL> SELECT * FROM HRAPP.EMP; EMPID LASTNAME FIRSTNAME SALARY ----- -------- --------- -----39334 SMITH GINA 75000 49539 QIAN LEE 90000 60403 HARPER ROD 45000 02039 WALLA RAJENDRA 60000 49392 SPANKY STACY 100000 The line in #old in this excerpt from a S1L2!lus session illustrates the entry of a simple S1L statement$ The *uery re*uests Oracle to gi"e all data from all columns in the %8! ta#le$ Oracle replies with the contents of the %8! ta#le as diagrammed in Ta#le +-+$ /ote that the user did not tell Oracle how to retrie"e the data, the user simply expressed the data they wanted using S1L syntax and Oracle returned it$ hapter +, shows how Oracle performs these tasks #ehind the scenes$$ =or now, make sure you understand how to specify a schema owner, the ta#le name, and the column name in a select statement in S1L2!lus$ The following code #lock demonstrates proper usage$ SELECT table_name.column_name, table_name.column_name FROM schema.table_name;
Tip: "lways #se a semicolon $%& to end S'L statements w(en entering t(em directly into S'L)!l#s*

The main components of a select statement are outlined$ The first component is the select clause$ This part is re*uired in order for Oracle to identify that it must now perform a select statement$ The second component of a select statement is the list of columns from which the user would like to "iew data$ In the statement issued in the example S1L2!lus session a#o"e, the column listing as descri#ed in the statement format was su#stituted with a special wildcard C2D character, which indicates to Oracle that the user wants to "iew data from e"ery column in the data#ase$ The user could ha"e executed the following *uery and o#tained the following data instead$ The last aspect of the select statement of importance is the from clause$ This special clause tells Oracle what data#ase ta#le to pull the information from$ Usually, the data#ase user will need to specify the schema, or owner, to which the ta#le #elongs, in addition to naming the ta#le from which the data should come$

SELECT empid, lastname, salary FROM HRAPP.EMP; EMPID LASTNAME SALARY ----- -------- -----39334 SMITH 75000 49539 QIAN 90000 60403 HARPER 45000 02039 WALLA 60000 49392 SPANKY 100000 /otice in the statement issued a#o"e that the ta#le named in the from clause is .0(!!$%8!$ This means that Oracle should pull data from the %8! ta#le in the .0(!! schema$ -hen a user is granted the a#ility to create data#ase o#)ects, the o#)ects he or she creates #elong to the user$ Ownership creates a logical grouping of the data#ase o#)ects #y owner, and the grouping is called a schema$
Tip: " sc(ema is a logical gro#ping of database ob+ects based on t(e #ser t(at owns t(e ob+ect*

E,ercises
+$ -hat is a select statement5 /ame the two re*uired components of a select statement$ 4$ .ow should the user end a select statement in S1L2!lus5 9$ -hat is a schema5

!erforming "rit(metic E-#ations


In addition to simple selection of data from a ta#le, Oracle allows the user to perform different types of acti"ities using the data$ The most #asic of these acti"ities is arithmetic$ (ll #asic arithmetic operations are a"aila#le in Oracle, including addition, su#traction, multiplication, and di"ision$ The operators used to denote arithmetic in Oracle S1L are the same as in daily use$ To #etter understand use of arithmetic e*uations in Oracle, the following example is offered$ (ssume, for example, that the user of the data#ase is performing a simple annual re"iew that in"ol"es gi"ing each user a cost-ofli"ing increase in the amount of E percent of their salary$ The process would in"ol"e multiplying each personFs salary #y +$@E$ The user could execute the process manually with pencil or calculator, #ut look at how much easier it is for the user to execute a slightly more complicated *uery to determine the result with S1L: SELECT empid, salary, salary*1.08 FROM HRAPP.EMP; EMPID LASTNAME SALARY SALARY*1.08 ----- -------- ------ ----------39334 SMITH 75000 81000

49539 QIAN 90000 97200 60403 HARPER 45000 48600 02039 WALLA 60000 64800 49392 SPANKY 100000 108000 S1L allows the user to execute all types of arithmetic operations, including ., /, ), 0$ Oracle allows the user to execute special S1L statements designed to perform mathematical pro#lems without selecting data as well$ The feature of Oracle related to arithmetic functions of this type is a special ta#le called &U(L$ &U(L is an empty ta#le that is used to fulfill the S1L select from construct$ SELECT 64+36 FROM DUAL; 64+36 ----100 There is no data actually in &U(LG rather, it simply exists as a S1L construct to support the re*uirement of a ta#le specification in the from clause$ (dditionally, the &U(L ta#le contains only one column and one row$
Tip: D1"L is a special table consisting of one col#mn and all 21LL 3al#es* D1"L is #sed to satisfy t(e S'L synta, constr#ct stating t(at all S'L statements m#st contain a from cla#se t(at names t(e table from w(ic( t(e data will be selected* W(en a #ser does not want to p#ll data from any table4 b#t rat(er wants simply to #se an arit(metic operation on a constant 3al#e4 t(e #ser can incl#de t(e 3al#es4 operations4 and t(e from D1"L cla#se*

E,ercises
+$ .ow can the user perform arithmetic on selected columns in Oracle5 4$ -hat is the &U(L ta#le5 -hy is it used5 9$ .ow does the user specify arithmetic operations on num#ers not selected from any ta#le5

5andling 21LL 6al#es


Sometimes, a *uery for some information will produce a nothing result$ In data#ase terms, nothing is called NULL$ /ULL is an expression that represents a nothing "alue$ In set theory, the mathematical foundation for relational data#ases, /ULL represents the "alue of an empty dataset, or a dataset containing no "alues$ Unless specified otherwise, a column in a ta#le is designed to accommodate the placement of nothing into the column$ (n example of retrie"ing a /ULL is listed in the following code #lock$ /otice that some of the employees ha"e no spouse$ /othing in Oracle is represented with the /ULL "alue$ /ULL is similar to nothing in that it represents no data present for this column in the row$ SELECT empid, lastname, firstname, spouse FROM HRAPP.EMP;

EMPID LASTNAME FIRSTNAME SPOUSE ----- -------- --------- -----39334 SMITH GINA FRED 49539 QIAN LEE 60403 HARPER ROD SUSAN 02039 WALLA RAJENDRA HARPREET 49392 SPANKY STACY .owe"er, there arise times when the user will not want to see nothing$ Instead of retrie"ing an empty data field, there may #e occasions where the user wants to see some default message$ Oracle pro"ides this functionality with a special function called n3l$ &$ This is the first function co"ered, so some extra attention will #e paid to using it in Oracle$ In the case a#o"e, assume that the user does not want to see #lank spaces for spouse information$ Instead, the user wants the output of the *uery to contain the word 6unmarried6 instead$ The *uery #elow illustrates how the user can issue the *uery against Oracle to o#tain the desired result$ The n3l$ & function is used to modify the S!OUS% column such that if the "alue in the S!OUS% column is /ULL, it will return the text string HunmarriedF$ Text strings in Oracle must #e enclosed in single *uotes$ SELECT empid, lastname, firstname, NVL(spouse,unmarried) FROM HRAPP.EMP; EMPID LASTNAME FIRSTNAME NVL(spous ----- -------- --------- --------39334 SMITH GINA FRED 49539 QIAN LEE unmarried 60403 HARPER ROD SUSAN 02039 WALLA RAJENDRA HARPREET 49392 SPANKY STACY unmarried /otice, first of all, that if the column specified in n3l$ & is not /ULL, the "alue in the column is returned, while when the column is /ULL, the special string is returned$ The n3l$ & function can #e used on columns of all datatypes$ ( discussion of different datatypes will appear later$ =or now, it is important to understand that the syntax for n3l$ & is as follows: NVL(column_name, value_if_null)

E,ercises
+$ -hat does /ULL mean in the context of Oracle S1L5 4$ -hat is the n3l$ & function5 .ow is it used5

7Renaming7 Col#mns wit( Col#mn "liases


(s the user may ha"e noticed in some of the earlier examples, when Oracle returns data to the user, Oracle creates special headings for each column so that the user knows what the data is$ The heading returned corresponds

directly with the name of the column passed to Oracle as part of the select statement: SELECT empid, lastname, firstname, NVL(spouse,unmarried) FROM HRAPP.EMP; EMPID LASTNAME FIRSTNAME NVL(spous ----- -------- --------- --------39334 SMITH GINA FRED 49539 QIAN LEE unmarried 60403 HARPER ROD SUSAN 02039 WALLA RAJENDRA HARPREET 49392 SPANKY STACY unmarried %ach of the columns a#o"e in #old correspond to the column names indicated in the select statement, including the n3l$ & operation on S!OUS%$ 'y default, Oracle reprints the column name exactly as it was included in the select statement$ Unfortunately, although this method exactly descri#es the data selected in the *uery, it does not usually gi"e a descripti"e explanation of the column data$ ompounding the pro#lem is the fact that Oracle truncates the expression to fit a certain column length corresponding to the datatype of the column returned$ Oracle pro"ides a solution to this situation with the use of column aliases in the select statement$ (ny column can #e gi"en another name #y the user when the select statement is issued$ This feature gi"es the user the a#ility to fit more descripti"e names into the space allotted #y the column datatype definition$ SELECT empid, lastname, firstname, NVL(spouse,unmarried) spouse FROM HRAPP.EMP; EMPID LASTNAME FIRSTNAME SPOUSE ----- -------- --------- --------39334 SMITH GINA FRED 49539 QIAN LEE unmarried 60403 HARPER ROD SUSAN 02039 WALLA RAJENDRA HARPREET 49392 SPANKY STACY unmarried (s indicated in #old #y the a#o"e code, the S!OUS% column is again named S!OUS%, e"en with the n3l$ & operation performed on it$ The alias is specified after the column is named in the select statement according to the following method$ In order to specify an alias, simply name the alias after identifying the column to #e selected, with or without an operation performed on it, separated #y white space$ (lternately, the user can issue the as keyword to denote the alias$ The column with the operation in it is specified as usual, #ut instead of naming the column alias after white space following that column with operation, the as keyword can clearly identify the alias for others reading the *uery$ /ote the use of as to denote the alias in the following code #lock: SELECT empid, lastname, firstname, NVL(spouse,unmarried) AS spouse

FROM HRAPP.EMP; EMPID LASTNAME FIRSTNAME SPOUSE ----- -------- --------- --------39334 SMITH GINA FRED 49539 QIAN LEE unmarried 60403 HARPER ROD SUSAN 02039 WALLA RAJENDRA HARPREET 49392 SPANKY STACY unmarried To summari3e, column aliases are useful for identifying the data in the output from S1L *ueries with meaningful headings$ (liases can #e specified in two ways, either #y naming the alias after the column specification separated #y white space, or with the use of the as keyword to mark the alias more clearly for other readers of the *uery, as shown here: SELECT column_with_or_without_operation alias, ; or SELECT column_with_or_without_operation AS alias, ;

E,ercises
+$ -hat is a column alias5 =or what situations might column aliases #e useful5 4$ -hat are two ways to define aliases for columns5

!#tting Col#mns Toget(er wit( Concatenation


0enaming a column in a select statement and using the n3l$ & operation are not the only things that can #e done to change the output of a *uery$ %ntire columns can #e put together to produce more interesting or reada#le output$ The method used to merge the output of certain columns into something new is accomplished with a special operation called concatenation$ The concatenation operator looks like two pipe characters put together, or ||$ onsider the running example of output from %8!$ In the following example, the user wants to change the name output to #e in the format lastname, firstname$ SELECT empid, lastname||, ||firstname full_name, NVL(spouse,unmarried) spouse, FROM HRAPP.EMP; EMPID ----39334 49539 60403 02039 49392 FULL_NAME SPOUSE ---------------- --------SMITH, GINA FRED QIAN, LEE unmarried HARPER, ROD SUSAN WALLA, RAJENDRA HARPREET SPANKY, STACY unmarried

(gain, #y using the concatenation operator in con)unction with a text string enclosed in single *uotes, the output of two or more columns, or e"en the output of one column, can #e put together to express new meaning$ =or good measure, the use of column aliases is recommended in order to make the name of the concatenated columns a#o"e more meaningful$

E,ercises
+$ -hat is column concatenation5 4$ -hat special character se*uence is used to concatenate columns5

Editing S'L '#eries Wit(in S'L)!l#s


(s the user gains more exposure to S1L2!lus, he or she will undou#tedly notice an annoying feature of the S1L2!lus command line<it canFt #ack up to pre"ious lines$ In other words, the user must type in the *uery "ery carefully, making sure that each line of the statement is correct #efore hitting the %/T%0 key and mo"ing on to type the next line$ So far, this limitation of the S1L command line hasnFt presented much difficulty$ .owe"er, as the *ueries the user can write get more and more complicated, the user will grow frustrated$ S1L2!lus does allow some correction of statement entry with the use of a special command called c(ange, a##re"iated as c$ onsider the following example to illustrate the point: SELECT empid, lastname||, ||firstname full_name, NVL(sppuse,unmarried) spouse, FROM HRAPP.EMP; NVL(sppuse,unmarried) spouse, FROM HRAPP.EMP; * ERROR at line 2: ORA-00904: invalid column name SQL> 2 2> NVL(sppuse,unmarried) spouse, FROM HRAPP.EMP; SQL> c/sppuse/spouse 2> NVL(spouse,unmarried) spouse, FROM HRAPP.EMP; SQL> / EMPID ----39334 49539 60403 FULL_NAME ---------------SMITH, GINA QIAN, LEE HARPER, ROD SPOUSE --------FRED unmarried SUSAN

02039 WALLA, RAJENDRA HARPREET 49392 SPANKY, STACY unmarried In this example, the user issues a select statement containing a typographical error, spp#se$ Oracle notices the error and alerts the user to it with OR"/ 889:;$ To change it, the user first references the line containing the mistake, in this case with the num#er 4$ (t this point, Oracle indicates the current "ersion of the S1L statement$ Then the user issues the c(ange command, a##re"iated as c$ The old text appears after the first slash, and the new text follows the second slash$ Oracle makes the change and then displays the new "ersion of the line$ The user can then execute the S1L statement, using the slash CBD command$ Other errors that may #e produced #y the user$

OR"/889:<: FRO

=eyword 2ot Fo#nd W(ere E,pected

This error indicates that the from keyword was not included or was misspelled$

OR"/889;:: Table or 6iew Does 2ot E,ist


This error indicates that the ta#le or "iew typed in does not exist$ Usually, the reason for O0(-@@:;4 is a typo in the name of the ta#le or "iew, or #ecause the schema owner was not specified in front of the ta#le name$ This error is fixed either #y correcting the typing pro#lem or #y adding the schema owner onto the front of the ta#le name$ (n alternati"e solution exists for the latter cause in creating synonyms for ta#les that are accessi#le to other users$ This solution will #e discussed in a later section$ In any case, the method used to correct the typing pro#lem is to first select the line num#er from the special #uffer that S1L2!lus maintains the current *uery in$ The name of the #uffer is afiedt$#uf on many operating systems$ The line of the #uffer is identified #y entering the line num#er and pressing %/T%0 as indicated #y the entry at the prompt as indicated$ (fter that line is chosen, the change command is entered in the following syntax$ c/old_value/new_value (fter making the change to the first appearance of old_value in the current line, Oracle redisplays the current line, with the change made$ /ote that the change will #e made to the first appearance of old_value only$ If the change must #e made to a specific place in the line, more characters can #e added to the old_value parameter as appropriate$ =inally, the corrected text can #e reexecuted #y entering a slash C0D at the prompt as indicated$ It takes some acclimation #efore the user will use S1L2!lus line editor to change command as freely as they would use their own fa"orite text editor$ =ortunately, Oracle makes pro"isions for the users to utili3e their fa"orite text editor to edit the statement created in afiedt$#uf$ Instead of entering all the additional commands to identify the line to #e edited, followed #y the exact character se*uence to change, Oracle allows the user to type in the edit command Ca##re"iated edD$ This action causes Oracle to #ring up the S1L statement in afiedt$#uf into the operating systemFs default text editor$ On

U/II systems, that text editor is usually JI or %8( S, while -indows en"ironments usually opt for the /otepad text editor$ To change the text editor used, issue the define>editor?FyoureditorF statement from the prompt$ Using a text editor rather than the line editor nati"e to S1L2!lus offers many #enefits$ =irst and foremost is the #enefit of using a text editor the user knows well, creating a familiarity with the application that is useful in adapting to S1L2!lus *uickly$ Second, it is helpful with large *ueries to ha"e the entire #lock of code in front of the user and immediately accessi#le$
Tip: W(en r#nning S'L statements from scripts4 do 2OT p#t a semicolon $%& at t(e end of t(e S'L statement* @nstead4 p#t a slas( $0& c(aracter on t(e line following t(e script*

One final word of note for using external editors to create S1L statements that will then #e executed with Oracle S1L2!lus$ It is possi#le to use the text editor of choice to write the entire *uery first and then load it into Oracle S1L2!lus$ Two commands are a"aila#le for this functionality$ The first is called get$ The get command opens the text file specified and places it in afiedt$#uf$ Once loaded, the user can execute the command using the slash C0D command$ (lternately, the user can simply load S1L statements from file into afiedt$#uf and execute in one step using the A command$ SQL*Plus: Release 3.2.3.0.0 - Production on Tue Feb 03 18:53:11 1998 Copyright (c) Oracle Corporation 1979, 1998. All rights reserved. Connected to Oracle7 Release 7.3.4.0.0 With the distributed and replication options PL/SQL Release 2.3.0.0.0 - Production SQL> GET select_emp SELECT * FROM emp SQL> / EMPID ----39334 49539 60403 02039 49392 LASTNAME -------SMITH QIAN HARPER WALLA SPANKY FIRSTNAME --------GINA LEE ROD RAJENDRA STACY SALARY -----75000 90000 45000 60000 100000

5 rows selected; SQL> @select_emp SELECT * FROM emp

/ EMPID ----39334 49539 60403 02039 49392 LASTNAME -------SMITH QIAN HARPER WALLA SPANKY FIRSTNAME --------GINA LEE ROD 4 RAJENDRA STACY SALARY -----75000 90000 45000 60000 100000

5 rows selected; In the first case illustrated #y the example a#o"e, the get command is used to pull in the contents of the selectKemp$s*l file into the afiedt$#uf #uffer$ /otice that the 6$s*l6 extension was left off$ Oracle S1L2!lus assumes that all scripts containing S1L statements will ha"e the $s*l extension, so the extension can #e omitted$ /otice also that after the file is #rought in using get, it can then #e executed using the slash C0D command$ In the second case, illustrated #y L4 a#o"e, the same file is read into afiedt$#uf and executed in one step, eliminating the need for the slash C0D command #y using the A command$ (gain, the $s*l extension is omitted$ 0emem#er that when using the get or A commands, if a full pathname is not specified as the filename, then Oracle S1L2!lus assumes the file is in the local directory$

E,ercises
+$ -hat two mechanisms are a"aila#le to enter and modify S1L statements within S1L2!lus5 4$ -hat is the edit command in the S1L2!lus command line5 .ow can S1L scripts #e loaded from files into S1L2!lus5 .ow are they run5 9$ -hat command is used to define a text editor for S1L2!lus to use5

Limiting Selected O#tp#t


In this section, you will co"er the following areas related to limiting selected output: The order by clause The w(ere clause O#taining all output from a ta#le is a great feature, #ut in the reality of data#ase applications, the user must #e more selecti"e in choosing output$ The reason is #ecause most data#ase applications contain a lot of data$ .ow much data can a data#ase contain5 Some applications contain ta#les with a million rows or more, and the most recent release of Oracle, OracleE, will store up to ?+4 peta#ytes of data$ /eedless to say, manipulating "ast amounts of data re*uires the user to #e careful to ask for exactly what he or she wants$

T(e ORDER BC Cla#se


In our running example of data from the %8! ta#le, a fundamental principle of relational data storage is illustrated$ &ata within a ta#le need not ha"e any order$ (nother *uick look at the output from the %8! ta#le will demonstrate: SQL> / EMPID LASTNAME FIRSTNAME SALARY ----- -------- --------- -----39334 SMITH GINA 75000 49539 QIAN LEE 90000 60403 HARPER ROD 45000 02039 WALLA RAJENDRA 60000 49392 SPANKY STACY 100000 /otice that the data returned is in no particular order on any column, either numeric or alpha#etical$ Oracle allows the user to place order on output from select statements #y issuing a special clause along with the statement already presented$ That special clause is called order by$ This clause can #e included in select statements at the end of the statement$ The general syntax for the order by clause is to include #oth the clause and the column or column aliasCesD on which Oracle will define order, optionally followed #y a special clause defining the direction of the order$ !ossi#le directions are asc for ascending and desc for descending, as shown #elow: SQL> SELECT * FROM emp ORDER BY empid DESC; EMPID LASTNAME FIRSTNAME SALARY ----- -------- --------- -----60403 HARPER ROD 45000 49539 QIAN LEE 90000 49392 SPANKY STACY 100000 39334 SMITH GINA 75000 02039 WALLA RAJENDRA 60000 In addition to pro"iding order on one column, Oracle can pro"ide order on many columns$ If the user desires, he or she can include multiple column specifications, as well as ascending or descending order in each of the columns specified$ The order by clause can #e useful in simple reporting$ It can #e applied to columns that are of /U8'%0, text CJ(0 .(04 and .(0D, and &(T% datatypes$ =inally, one can use num#ers to indicate the column on which Oracle should order the output from a statement$ The use of num#ers depends on the positioning of each column$ =or example, if the user issues a statement similar to the one in the following code #lock, the order for the output will #e as shown$ The num#er 4 indicates that the second column should #e used to define order in the output$ 'ut, since the second column is something different in each statement, the order of the output will #e different as well$ SELECT empid, lastname FROM emp ORDER BY 2;

EMPID ----02039 39334 49392 49539 60403

LASTNAME -------WALLA SMITH SPANKY QIAN HARPER

SELECT empid, lastnname FROM emp ORDER BY 2; LASTNAME -------60403 39334 49392 49539 02039 EMPID ----HARPER SMITH SPANKY QIAN WALLA

E,ercises
+$ .ow can a user put row data returned from a select statement in order5 -hat are the "arious orders that can #e used with this option5 4$ -hat are the two ways the column on which order should #e defined can #e identified5

T(e W5ERE Cla#se


The w(ere clause in Oracle select statements is where the really interesting things #egin$ This important clause in select statements allows the user to single out a few rows from hundreds, thousands, or e"en millions like it$ The w(ere clause operates on a #asic principle of comparison: SELECT * FROM emp WHERE empid = 43932; EMPID LASTNAME FIRSTNAME SALARY ----- -------- --------- -----49392 SPANKY STACY 100000 Instead of pulling all rows from %8!, Oracle pulls )ust one row for display$ To determine what row to display, the w(ere clause performs a comparison operation as specified #y the *uery<in this case, the comparison is an e*uality operation, w(ere empid ? ;9:94$ .owe"er, e*uality is not the only means #y which Oracle can o#tain data$ Some other examples of comparison are demonstrated in the following list: x?y omparison to see if x is e*ual to y$

xDy x D? y xEy x E? y x ED y x F? y x G? y liHe

omparison to see if x is greater than y$ omparison to see if x is greater than or e*ual to y$ omparison to see if x is less than y$ omparison to see if x is less than or e*ual to y$ omparison to see if x is not e*ual to y$

( special comparison used in con)unction with the character wildcard CID character to find su#strings in text "aria#les$ ( special function used to introduce 6fu33y logic6 into text string comparisons #y allowing e*uality #ased on similarly spelled words$ ( range comparison operation that allows for operations on dates that are similar to the following numeric comparison: Y 6is #etween6 X and Z$ ( special comparison that allows the user to specify multiple e*uality statements #y defining a set of "alues, any of which the "alue can #e e*ual to$ (n example of its usage may #e x I/ C+,4,9,;,?D$

so#nde,

between

in

These six operations are the cornerstone of comparison$ (ccording to 'oolean logic Cone of the cornerstones of computing in a data#ase or any other type of en"ironmentD, e"ery comparison #etween two "alues #oils down to one or more of these operations$ ( select statement need not ha"e only one comparison in it to determine what data should #e returned$ 8ultiple comparisons can #e placed together using the following list of operations$ The operator is listed along with the result that is re*uired to fulfill the criteria #ased on the presence of this operator$ x and y x or y not x 'oth comparisons in x and y must #e true$ One comparison in x or y must #e true$ The logical opposite of x$

E,ercises
+$ -hat is a w(ere clause5 On what principle does this clause operate to determine which data is selected5 4$ -hat are some operations a"aila#le to assist in the purpose of comparison5 -hat are some operations that allow the user to specify more than one comparison in the w(ere clause5

1sing Single/row F#nctions


In this section, you will co"er the following areas related to using single-row functions: Jarious single-row functions explained Using functions in select statements &ate functions In addition to simple comparison, Oracle allows more complex comparison operations with the use of special functions$ There are do3ens of functions a"aila#le in Oracle that can #e used for many purposes$ Some functions in Oracle are designed to alter the data returned #y a *uery, such as the n3l$ & function already presented$ The functions in this category are designed to work on columns of any datatype to return information in a different way$ =or example, the n3l$ & function can handle nulls appearing in any column, including dates, num#ers, text strings, and others$ One commonly used example of this type of function is decode$ &$ The decode$ & procedure works on the same principle as an if/t(en/else statement works in many common programming languages, including !LBS1L, which will #e discussed in hapter A$ SELECT DECODE(column, val1, return1, val2, return2, ,return_default) The decode$ & function allows for powerful transformation of data from one "alue to another$ Its scope encompasses the functionality pro"ided #y n3l$ &, yet decode$ & goes so much farther than n3l$ & in its a#ility to return highly speciali3ed data when gi"en the right criteria$ =urthermore, it allows for a default return "alue to #e specified if the user so desires$ Some examples of decode$ & in action will appear later in the chapter$

6ario#s Single/row F#nctions E,plained


=rom this point on, all functions descri#ed ha"e limitations on the datatype they can perform their operations on$ 0elated to the set of functions designed to con"ert data from one thing to another are se"eral functions that manipulate text strings$ These functions are similar in concept to n3l$ & and decode$ & in that they can perform a change on a piece of data, #ut the

functions in this family can perform data change on only one type of data< text$ (s such, the functions in this family are often referred to as text, or character functions$ In this family are se"eral functions in Oracle, for which some of the highlighted functions that are most used are listed following this paragraph$ lpad$,4yM4JN& rpad$,4yM4JN& 0eturns the column 6padded6 on the left or right side of the data in the column passed as x to a width passed as y$ The optional passed "alue z indicates the character that lpad or rpad will insert into the column$ 0eturns the column "alue passed as x into all lowercase or uppercase, or changes the initial letter in the string to a capital letter$ 0eturns a num#er indicating the num#er of characters in the column "alue passed as x$ 0eturns a su#string of string x, starting at character num#er y to the end, which is optionally defined #y the character appearing in position z of the string$

lower$,& #pper$,& initcap$,& lengt($,& s#bstr$,4yM4JN&

Others are designed to perform speciali3ed mathematical functions such as those used in scientific applications like sine and logarithm, which should already #e fairly well understood #y those with a #ackground in trigonometry$ These operations are commonly referred to as math or num#er operations$ The functions falling into this category are listed #elow$ These functions are not all the ones a"aila#le in Oracle, #ut rather are the most commonly used ones that will likely #e used on O ! %xam +$ abs$,& O#tains the a#solute "alue for a num#er$ =or example, the a#solute "alue of C-+D is +, while the a#solute "alue of A is A$ Similar to executing ro#nd Csee #elowD on an integer Ci$e$, ro#nd$,48&, except ceil always rounds up$ =or example, ceil$1*K& O 4$ /ote that rounding 6up6 on negati"e num#ers produces a "alue closer to 3ero Ce$g$, ceil$/1*K& O -+, not P4D$ Similar to ceil Csee a#o"eD, except floor always rounds down$ =or example, floor$1*K& O +$ /ote that rounding 6down6 on negati"e num#ers produces a "alue further away from 3ero Ce$g$, floor$/1*K& O -4, not P+$ The modulus of x, as defined #y long di"ision as the integer remainder left o"er when x is di"ided #y y until

ceil$,&

floor$,&

mod$,4y&

no further whole num#er can #e produced$ (n example is mod$184<& O +, or mod$184:& O @$ ro#nd$,4y& 0ound x to the decimal precision of y$ If y is negati"e, round to the precision of y places to the left of the decimal point$ =or example, ro#nd$1<;*<;L41& O +9;$9, ro#nd$1<;*<;L48& O +9;, ro#nd$1<;*<;L4/1& O +9@$ &isplays integer "alue corresponding to the sign of x, + if x is positi"e, -+ if x is negati"e$ The s*uare root of x$ Truncate "alue of x to decimal precision y$ If y is negati"e, then truncate to y num#er of places to the left of the decimal point$ The storage si3e in #ytes for "alue x$

sign$,& s-rt$,& tr#nc$,4y&

3siJe$,&

The final category of num#er functions that will #e discussed here is the set of list functions$ These functions are actually used for many different datatypes, including text, numeric, and date$ The list functions are listed #elow$ greatest$,4y4M& least$,4y4M& 0eturns the highest "alue from list of text strings, num#ers, or dates Cx,yQD$ 0eturns the lowest "alue from list of text strings, num#ers, or dates Cx,yQD$

(nother class of data functions a"aila#le in Oracle correspond to another commonly used datatype in the Oracle data#ase<the D !" datatype$ The functions that perform operations on dates are known as date functions$ 'efore di"ing into the functions, a useful item in Oracle related to dates will #e presented$ There is a special keyword that can #e specified to gi"e Oracle users the current date$ This keyword is called sysdate$ In the same way that the user calculated simple arithmetic in an earlier part of the chapter using the &U(L ta#le, so too can the user execute a select statement using sysdate to produce todayFs date: SELECT sysdate FROM DUAL; SYSDATE --------15-MAR-98 -ith usage of sysdate esta#lished, the functions that can #e used on &(T% columns are listed in the following definitions:

add>mont(s$,4y& last>day$,& mont(s>between$,4y& new>time$,4y4J&

0eturns a date corresponding to date x plus y months$ 0eturns the date of the last day of the month that contains date x$ 0eturns a num#er of months #etween y and x as produced #y y-x$ an return a decimal "alue$ 0eturns the current date and time for date x in time 3one y as it would #e in time 3one z$

-hy use functions at all5 The functions a"aila#le in Oracle are highly useful for executing well-defined operations on data in a ta#le or constant "alues in an easy way$ =or example, if the user were working with a scientific organi3ation to produce a report of data for that organi3ation, the user may want to use some of the math functions a"aila#le in Oracle$ 0ather than selecting data from a ta#le and performing standard mathematical calculations using a scientific calculator, the user may instead execute the functions on that data and produce the report cleanly, in one step$ The use of functions in Oracle often sa"es time and energy$

E,ercises
+$ Identify some of the character, num#er, and date functions a"aila#le in S1L$ -hat are two functions that allow the user to transform column "alues regardless of the datatype5 4$ -hat are other types of other functions that perform operations on columns of specific datatypes5

1sing F#nctions in SELECT Statements


The pre"ious section introduced the many functions a"aila#le in Oracle$ The definitions in that section should suffice for referenceG howe"er, there is no su#stitute for actual usage$ This section will show the functions listed in action$ The first example #elow details use of the decode$ & function$ (ssume that the user is selecting data from the %8! ta#le$ The data in the S%I column of %8! is populated with 8 for male and = for female$ Instead of displaying a letter, the user wants to write out the full word for each sex$ SELECT empid, lastname, firstname, DECODE(sex,M,MALE,F,FEMALE) sex FROM emp ORDER BY empid DESC; EMPID LASTNAME FIRSTNAME SEX ----- -------- --------- -----60403 HARPER ROD MALE

49539 QIAN LEE FEMALE 49392 SPANKY STACY FEMALE 39334 SMITH GINA FEMALE 02039 WALLA RAJENDRA MALE /otice that the decode$ & command has fi"e parameters, the first of which is the name of the column$ This column must always #e present$ The second parameter corresponds to the "alue that could #e found in the S%I column, followed #y the "alue that decode$ & should return if S%I in this row is e*ual to H8F$ The next set of parameters answers the *uestion of what decode$ & should return if the "alue in the column is H=F$ This matching of column "alues with appropriate return "alues can continue until the user has identified all cases he or she would like decode$ & to handle$ The last parameter according to the definition of decode$ & is used for the default return "alue$ /o default "alue was specified in this example, as the default return "alue is optional$ The next section will present examples of text or character function examples$ The first of these examples is for rpad$ & and lpad$ &$ These two functions can #e used to place additional filler characters on the right or left side of data in a column out to a specified column width$ SELECT empid, lastname, firstname, RPAD(DECODE(sex,M,MALE,F,FEMALE),10,-) sex FROM emp ORDER BY empid DESC; EMPID LASTNAME FIRSTNAME SEX ----- -------- --------- ---------60403 HARPER ROD MALE-----49539 QIAN LEE FEMALE---49392 SPANKY STACY FEMALE---39334 SMITH GINA FEMALE---02039 WALLA RAJENDRA MALE-----(n interesting property of Oracle S1L functions is displayed in this example$ The output from one S1L function can #e used as input for another$ In this case, the rpad$ & operation will pad the decoded S%I column out to ten characters with dashes$ If the lpad$ & operation had #een used instead, the result would ha"e #een as follows: SELECT empid, lastname, firstname, LPAD(DECODE(sex,M,MALE,F,FEMALE),10,-) sex FROM emp ORDER BY empid DESC; EMPID ----60403 49539 49392 39334 02039 LASTNAME FIRSTNAME SEX -------- --------- ---------HARPER ROD ------MALE QIAN LEE ----FEMALE SPANKY STACY ----FEMALE SMITH GINA ----FEMALE WALLA RAJENDRA ------MALE

Some of the simpler character functions are next$ Two straightforward examples of S1L *ueries are sometimes referred to as 6case translators,6 #ecause they perform a simple translation of case #ased on the text string passed$ SELECT LOWER(title) TITLE_NOQUOTE, UPPER(artist) ARTIST1, INITCAP(artist) ARTIST2 FROM SONGS; TITLE_NOQUOTE ARTIST1 ARTIST2 ------------------- --------- --------"happy birthday" ANONYMOUS Anonymous "diamonds and rust" ANONYMOUS Anonymous "amazing grace" ANONYMOUS Anonymous (nother straightforward and surprisingly useful character function is the lengt($ & function, which returns the length of a text string$ SELECT title, LENGTH(title) LENGTH FROM SONGS; TITLE LENGTH ------------------- -----"HAPPY BIRTHDAY" 16 "DIAMONDS AND RUST" 19 "AMAZING GRACE" 15 /ote one interesting thing happening in this *uery<spaces and special characters are all counted as part of the lengthR This is an important facet to remem#er when dealing with text strings in Oracle$ 'lank spaces count as part of the length of the column "alue$ (nother extraordinarily useful function related to character strings is the s#bstr$ & function$ This function is commonly used to extract data from a longer text string$ Its syntax, though slightly more difficult to understand than some of the other commands in Oracle, is definitely worth mastering$ s#bstr$ & takes as its first parameter the full text string to #e searched$ The second parameter contains an integer that designates the character num#er at which the su#string should #egin$ The third parameter is optional and specifies how many characters to the right of the start of the su#string will #e included in the su#string$ Optionally, the final parameter in the s#bstr$ & call could ha"e #een left off, producing the following output: SELECT title, SUBSTR(title,5,5) CHARS FROM SONGS; TITLE CHARS ------------------- ----"HAPPY BIRTHDAY" Y BIR "DIAMONDS AND RUST" ONDS "AMAZING GRACE" ING G SELECT title, SUBSTR(title,5) CHARACTERS FROM SONGS;

TITLE CHARACTERS ------------------- --------------"HAPPY BIRTHDAY" Y BIRTHDAY" "DIAMONDS AND RUST" ONDS AND RUST" "AMAZING GRACE" ING GRACE" The num#er or math functions are fre*uently used in scientific applications, and as such may not #e as familiar to de"elopers with less mathematical experience$ It is #eyond the scope of this chapter to discuss the meaning of the math functions, particularly the logarithmic functions$ .owe"er, use of those functions will #e demonstrated #y the S1L statements displayed in this section$ The first function detailed here is the abs$ & or a#solute "alue function$ SELECT ABS(25), ABS(-12) FROM DUAL; ABS(25) ABS(-12) ------- -------25 12 The next single-"alue function that will #e co"ered in this section is the ceil$ & function$ SELECT CEIL(123.323), CEIL(45), CEIL(-392), CEIL(-1.12) FROM DUAL; CEIL(123.323) CEIL(45) CEIL(-392) ------------- -------- ---------124 45 -392 The next single-"alue function is the floor$ & opposite of ceil$ &$ SELECT FLOOR(123.323), FLOOR(45), FROM DUAL; CEIL(-1.12) -----------1 function$ The floor$ & is the FLOOR(-392), FLOOR(-1.12)

FLOOR(123.323) FLOOR(45) FLOOR(-392) FLOOR(-1.12) ------------- -------- ---------- ----------123 45 -392 -2 The next function co"ered in this section is related to long di"ision$ The function is called mod$ &, and it returns the remainder amount for a num#er and its di"isor$ SELECT MOD(12,3), MOD(55,4) FROM DUAL; MOD(12,3) MOD(55,4) --------- --------0 3 (fter that, the user should look at ro#nd$ &$ This important function allows the user to round a num#er off to a specified "alue of precision$ SELECT ROUND(123.323,2), ROUND(45,1), ROUND(-392,-1), ROUND(-1.12,0) FROM DUAL;

ROUND(123.323,2) ROUND(45,1) ROUND(-392,1) ROUND(-1.12,0) ---------------- -----------------------------123.32 45 -390 -1 The next function is called sign$ &$ It assists in identifying a num#er to #e positi"e or negati"e$ If the num#er passed is positi"e, sign$ & returns +, if the num#er is negati"e, sign$ & returns P+$ SELECT SIGN(-1933), SIGN(55), SIGN(0) FROM DUAL; SIGN(-1933) SIGN(55) SIGN(0) ---------- ----------- -------1 1 0 The next example is the s-rt$ & function$ It is used to deri"e the s*uare root for a num#er$ SELECT SQRT(34), SQRT(9) FROM DUAL; SQRT(34) SQRT(9) --------- ---------5.8309519 3 The next single-"alue num#er function is called tr#nc$ &$ Similar to ro#nd$ &, tr#nc$ & truncates a "alue passed into it according to the precision that is passed in as well$ SELECT TRUNC(123.232,2), TRUNC(-45,1), TRUNC(392,-1), TRUNC(5,0) FROM DUAL; TRUNC(123.232,2) TRUNC(-45,1) TRUNC(392,-1) TRUNC(5,0) ---------------- ------------ ------------- ---------123.23 -45 390 5 The final single-row operation that will #e co"ered in this section is the 3siJe$ & function$ This function is not strictly for numeric datatypes, either$ The 3siJe$ & function gi"es the si3e in #ytes of any "alue for a text, num#er, date, or 0O-I&, and other columns$ SELECT VSIZE(384838), VSIZE('ORANGE_TABBY'), VSIZE(sysdate) FROM DUAL; VSIZE(384838) VSIZE('ORANGE_TABBY') VSIZE(SYSDATE) ------------- --------------------- -------------4 12 8

E,ercises
+$ -hat is the purpose of the n3l$ & function5 -hat datatypes does it accept5 -hat is the purpose of a decode$ & statement5 -hat datatypes does it accept5 4$ /ame some character functions5 an two functions #e com#ined5 -hy or why not5

9$ /ame some single-"alue num#er functions$ -hat types of applications are these functions typically used in5 ;$ -hat function is used to determine the si3e in #ytes of a gi"en "alue or column5

Date F#nctions
There are se"eral date functions in the Oracle data#ase$ The syntax of these functions has already #een presented$ This section will discuss each function is more detail and present examples of their usage$ 'ut first, the user should understand how dates are stored in Oracle$ The Oracle data#ase stores dates in an integer format, storing the date as the num#er of days from the #eginning of the Sulian calendar$ This method allows for easy format changes and inherent millennium compliance$ The first function is the add>mont(s$ & function$ This function takes as input a date and a num#er of months to #e added$ Oracle then returns the new date, which is the old date plus the num#er of months$ SELECT ADD_MONTHS(15-MAR-98,26) FROM DUAL;
ADD_MONTHS(15 -------------15-MAY-02

The next date function, last>day$ &, helps to determine the date for the last date in the month for the date gi"en$ SELECT LAST_DAY(15-MAR-99) FROM DUAL; LAST_DAY(15-M -------------31-MAR-99 The next date function determines the num#er of months #etween two different dates gi"en$ The name of the function is mont(s>between$ &$ The syntax of this command is tricky, so it will #e presented here$ The syntax of this command is mont(s>between$y4,&, and the return "alue for this function is y-x$ SELECT MONTHS_BETWEEN(15-MAR-98,26-JUN-97) FROM DUAL; MONTHS_BETWEEN -------------8.6451613 The next and last example of a date function is the new>time$ & function$ This procedure accepts three parameters, the first #eing a date and time, the second #eing the time 3one the first parameter #elongs in, and the last parameter #eing the time 3one the user would like to con"ert to$ %ach time 3one is a##re"iated in the following way: XST or X&T, where # or D stands for standard or daylight sa"ings time, and where X stands for the first letter of the

time 3one Csuch as tlantic, $ering, central, eastern, %awaii, &ountain, Newfoundland, 'acific, or YukonD$ There are two exceptions: >reenwich mean time is indicated #y >8T, while /ewfoundland standard time does not use daylight sa"ings$ (n example of the usage of new>time$ & is as follows in this example$ (nother useful fact to know when using new>time$ & is that the Oracle date format shown is not the only one a"aila#le$ &ates in Oracle are stored as num#ers from the #eginning of the Sulian calendar C&ecem#er 9+, ;,+9 '$ $%$D, down to the second$ So far, none of the *ueries used to demonstrate the date functions ha"e re*uired that much precision, #ut the following example will$ In order to demonstrate the full capa#ility of Oracle in the new>time$ & function, the /LS date format can #e changed to display the full date and time for the *uery$ The example #elow demonstrates #oth the use of nls>date>format$ & to change the date format and the new>time$ & function to con"ert a time stamp to a new time 3one: ALTER SESSION SET NLS_DATE_FORMAT = DD-MON-YYYY HH24:MI:SS; SELECT NEW_TIME(15-MAR-1998 14:35:00,AST,GMT) FROM DUAL;
NEW_TIME(15-MAR-199 -------------------15-MAR-1998 18:35:00

E,ercises
+$ -hat is nls>date>format5 .ow is it set5 .ow is it used5 4$ -hich date functions descri#ed in this section return information in the &(T% datatype5 -hich one returns information in a datatype other than &(T%5 9$ .ow are dates stored in Oracle5

Con3ersion F#nctions
Still other functions are designed to con"ert columns of one datatype to another type$ (s these functions are simply designed to change the datatype of the column "alue, not actually modify the data itself, the functions are called con"ersion functions$ There are se"eral different con"ersion functions a"aila#le in the Oracle data#ase$ The ones a"aila#le appear in the following list: to>c(ar$,& to>n#mber$,& to>date$,M4yN& on"erts noncharacter "alue x to character on"erts nonnumeric "alue x to num#er on"erts nondate "alue x to date, using format specified #y y

to>m#lti>byte$,& to>single>byte$,& c(artorowid$,& rowidtoc(ar$,& (e,toraw$,& rawto(e,$,& con3ert$,M4yM4JNN&

on"erts single-#yte character string x to multi#yte characters according to national language standards on"erts multi#yte character string x to single-#yte characters according to national language standards on"erts string of characters x into an Oracle 0O-I& on"erts string of characters x into an Oracle 0O-I& on"erts hexadecimal C#ase-+AD "alue x into raw C#inaryD format on"erts raw C#inaryD "alue x in to hexadecimal C#ase+AD format %xecutes a con"ersion of alphanumeric string x from the current character set optionally specified as z to the one specified #y y %xecutes a simple "alue con"ersion for character or numeric string x into something else #ased on the con"ersion factors y and z

translate$,4y4J&

The following text illustrates the most commonly used procedures for con"erting data in action$ These are the to>c(ar$ &, to>n#mber$ &, and to>date$ & functions$ The first one demonstrated is the to>c(ar$ & procedure$ In the example of new>time$ &, the date function descri#ed earlier, the alter session set nls>date>format$ & statement was used to demonstrate the full capa#ilities #oth of Oracle in storing date information and Oracle in con"erting dates and times from one time 3one to another$ That exercise could ha"e #een accomplished with the use of the to>c(ar$ & con"ersion function as well, howe"er$ Using to>c(ar$ & in this manner sa"es the user from con"erting nls>date>format, which, once executed, is in effect for the rest of the userFs session, or until the user executes another alter session set nls>date>format statement$ 0ather than using this method, the user may want to opt for a less permanent option offered #y the to>c(ar$ & function$ SELECT TO_CHAR(NEW_TIME(TO_DATE(15-MAR-1998 14:35:00, DD-MON-YYYY HH24:MI:SS),AST,GMT) FROM DUAL; NEXT_DAY(15-MAR-9 -----------------15-MAR-98 18:35:00 /ote that this example also uses the to>date$ & function, another con"ersion function in the list to #e discussed$ The to>date$ & function is "ery useful for

con"erting num#ers, and especially character strings, into properly formatted &(T% fields$ SELECT TO_NUMBER(49583) FROM DUAL; TO_NUMBER(49583) -----------------49583 (lthough there does not appear to #e much difference #etween the output of this *uery and the string that was passed, the main difference is the underlying datatype$ %"en so, Oracle is actually intelligent enough to con"ert a character string consisting of all num#ers #efore performing an arithmetic operation using two "alues of two different datatypes$ SELECT 49583 + 34 FROM DUAL;
49583+34 ---------49617

E,ercises
+$ Identify some con"ersion functions$ -hich con"ersion functions are commonly used5 4$ -hat is nls>date>format5 .ow is it used5

C(apter S#mmary
This chapter pro"ides an introduction to using Oracle #y demonstrating #asic techni*ues for use of select statements$ The areas discussed in this chapter are selecting row data from ta#les using the select from statement, limiting the rows selected with the w(ere clause of the select from statement, and using the single-row functions a"aila#le in Oracle to manipulate selected data into other "alues, formats, or meanings$ This chapter is the cornerstone for all other usage in Oracle, as well as for passing the O ! %xam +$ 8aterial co"ered in this chapter comprises +, percent of test content on O ! %xam +$ The first area co"ered in this chapter is information a#out selecting data from Oracle$ The most common manipulation of data in the Oracle data#ase is to select it, and the means #y which to select data from Oracle is the select statement$ The select statement has two #asic parts, the select clause and the from clause$ The select clause identifies the column of the ta#le that the user would like to "iew contents of$ The from clause identifies the ta#le in which the data selected is stored$ In this chapter, data from only one ta#le at a time was considered$ In the next chapter, the concept of pulling or 6)oining6 data from multiple ta#les will #e considered$ Often, users will want to perform calculations in"ol"ing the data selected from a ta#le$ Oracle allows for #asic, intermediate, and complex manipulation of data selected from a data#ase ta#le through the use of standard arithmetic

notation such as plus C.D, minusC/D, multiply C)D, and di"ide C0D$ These operators can #e used to perform math calculations on the data selected from a ta#le or as math operators on num#ers in calculator-like fashion$ In order to perform calculations on num#ers that are not selected from any ta#le, the user must utili3e the &U(L ta#le$ &U(L is simply an empty ta#le with one column that fulfills the syntactic re*uirements of S1L statements like select, which need a ta#le name in the from clause in order to work$ -hen manipulating data from a ta#le, the user must remem#er to handle cases when column data for a particular row is nonexistent$ /onexistent column data in a ta#le row is often referred to as #eing /ULL$ These /ULL "alues can #e "iewed either as #lank space, #y default, or the user can account for the appearance of null data #y using a special function that will su#stitute null fields with a data "alue$ The name of this special function is n3l$ &$ The n3l$ & function takes two parameters: the first is the column or "alue to #e in"estigated for #eing null, and the second is the default "alue n3l$ & will su#stitute if the column or "alue is null$ The n3l$ & function operates on all sorts of datatypes, including .(0, J(0 .(04, /U8'%0, and &(T%$ -hen performing special operations on columns in a select statement, Oracle often displays hard-to-read headings for the column name #ecause Oracle draws the column name directly from the select clause of the select statement$ The user can a"oid this pro#lem #y gi"ing a column alias for Oracle to use instead$ =or example, the following select may produce a cryptic column heading: select n3l$empid4N88888N& E !@D M, while a column alias would allow Oracle to pro"ide a more meaningful heading: select n3l$empid4N88888N& E !@D M* olumn aliases are specified as character strings following the function andBor column name the alias will su#stitute$ 'e sure to include white space #etween the function andBor column name and the alias$ oncluding the introduction to S1L select statements, the use of concatenation and entering the actual statements was discussed$ olumns can #e concatenated together using the dou#le-pipe C||D delimiter$ This operation is useful for placing information closer together, or to use special characters to separate the output, such as commas or others$ The S1L statement itself is entered using the S1L2!lus tool$ If a user makes an error while typing in the line of S1L, the user can use the #ackspace key to erase characters until he or she reaches the mistakeG howe"er, this approach only works if the user is still on the same line in the S1L entry #uffer$ If the user has already proceeded to another line, or if he or she has already tried to execute the command, then he or she can type in the num#er corresponding to the line to #e corrected to select that line for editing$ Then, the user can type in the change command, a##re"iated c0old0new, where old is the existing "ersion of the string containing the mistake, and new is the correction$ If this all sounds complicated, the user can simply type edit, or ed from the prompt in S1L2!lus, and Oracle will immediately #ring up the userFs fa"orite text editor$ The text editor used here can #e specified or changed with the define>editor?7youreditor7 command$

The num#er or order of selected rows from the data#ase can #e limited with "arious options$ The first option discussed is order by$ This is a clause that allows the user to specify two things<the first is a column on which to list the data in order, the second is whether Oracle should use ascending or descending order$ Usage of the order by clause can make output from an Oracle select statement more reada#le, since there is no guarantee that the data in Oracle will #e stored in any particular order$ The second means of limiting selected output is the w(ere clause$ !roper use of this clause is key to successful usage of Oracle and S1L$ In the w(ere clause, the user can specify one or more comparison criteria that must #e met #y the data in a ta#le in order for Oracle to select the row$ ( comparison consists of two elements that are compared using a comparison operator, which may consist of a logic operator such as e*uality C?D, ine*uality CED,F?, or G?D, less than CED or greater than CDD, or a com#ination of less or greater than and e*uality$ (lternately, the user can also utili3e special comparison operators that ena#le for pattern matches using liHe I, range scans using between x and y, or fu33y logic with the so#nde,$x& ? so#nde,$y& statement$ In addition, one or more comparison operations may #e specified in the w(ere clause, )oined together with and or the or operator, or preceded #y not$ &ata selected in Oracle can #e modified with the use of se"eral functions a"aila#le in Oracle$ These functions may work on many different types of data, as is the case with n3l$ & other functions called decode$ &, greatest$ &, or least$ &$ (lternately, their use may #e limited to a particular datatype$ These functions may #e di"ided into categories #ased on the types of data they can handle$ Typically, the functions are categori3ed into text or character functions, math or num#er functions, and date functions$ Usage of Oracle #uilt-in functions ena#les the user to perform many different operations$ In general, the use of a function comprises specifying the name of the function and the passing of parameters to the function$ =or example, to change the characters in a text string re*uires identifying the function that performs this task, followed #y passing the function a "alue$ To perform the task in this example, the following function call could #e made: #pper$lowercase&$ The chapter also detailed the usage of all the functions a"aila#le in Oracle, and pro"ided examples for most of them$ =or #re"ity sake, they will not reappear hereG howe"er, it should #e noted that many of the functions can #e used together and in con)unction with the multitype functions like decode$ &$ =or example, the usage of decode$s-rt$,&4 ;4 O5"R6ECN4L4NP@LLN4NBR"DN& is permitted$ In essence, this functionality allows the user to incorporate the output from one function as input for another$ (n entire set of con"ersion functions are also a"aila#le to change datatypes for "alues, or to create ciphers, or e"en to change the character sets used in order to mo"e data onto different machines$ (gain, for the sake of #re"ity, the functions themsel"es are not listed hereG howe"er, it should #e stated that the con"ersion functions can #e used in con)unction with many of the other functions already named$

Two/min#te Drill
&ata is retrie"ed from Oracle using select statements$ Syntax for a select statement consists of select MfromMG$ -hen entering a select statement from the prompt using S1L2!lus, a semicolonC%D must #e used to end the statement$ (rithmetic operations can #e used to perform math operations on data selected from a ta#le, or on num#ers using the &U(L ta#le$ The &U(L ta#le is an empty ta#le used to fulfill the syntactic re*uirements of S1L select statements$ Jalues in columns for particular rows may #e empty, or null$ If a column contains the /ULL "alue, the user can use the n3l$ & function to return meaningful information instead of an empty field$ (liases can #e used in place of the actual column name or to replace the appearance of the function name in the header$ Output from two columns can #e concatenated together using a dou#le-pipe C||D$ S1L commands can #e entered directly into S1L2!lus on the command line$ If a mistake is made, the change Cc0old0newD command is used$ (lternately, the edit CedD command can #e used to make changes in the userFs fa"orite text editor$ The user can specify a fa"orite text editor #y issuing the define>editor command at the prompt$ The order by clause in a select statement is a useful clause to incorporate sort order into the output of the file$ Sort orders that can #e used are ascending or descending$ Order is determined #y the column identified #y the order by clause$ The w(ere clause is used in S1L *ueries to limit the data returned #y the *uery$ The w(ere clauses contain comparison operations that determine whether a row will #e returned #y a *uery$ There are se"eral logical comparison operations, including ?4 D4 D?4 E4 E?4 ED4 F?4 G?* In addition to the logical operations, there is a comparison operation for pattern matching called liHe$ The I character is used to designate wildcards$ There is also a range operation called between$ There is also a fu33y logic operation called so#nde,$ =inally, the w(ere clause can contain one or more comparison operations linked together #y use of and, or, and preceded #y not$ Se"eral S1L functions exist in Oracle$ S1L functions are #roken down into character functions, num#er functions, and date functions$ ( few functions are usa#le on many different types of data$

There are also se"eral con"ersion functions a"aila#le for transforming data from text to numeric datatypes and #ack, num#ers to dates and #ack, text to 0O-I& and #ack, etc$

You might also like