Selecting Data From Oracle: $ Sqlplus Jason/athena
Selecting Data From Oracle: $ Sqlplus Jason/athena
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$
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
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
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
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
(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
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
This error indicates that the from keyword was not included or was misspelled$
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
/ 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
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
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
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$
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$
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:
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
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
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$