Functions
Single-row functions
Multiple-row functions
SQL Functions (continued) Ttere are t\vo distinct typesof ftmcttons: Smgle-rov. tunctions Multiple-row fimctions Sing!e-Ro\v Functions "Flese ftiiictions oprate on single roxvs only and reUini one result per ro\v. Ttere are ditTerent tvpes of single-ro\v finctions. This lesson coversthe follo\vmg ones: Character Number Date Conversin
Mltiple-Row Functions Tliese finctions nianipulate groups of roxvs to give one result per group of roxvs. For more Information, see Oracle Scnvr SOI. Kefcrcncc. Relase S_ for the complete list of available functions and svntax
Single-Row Functions
Maniplate data tems Accept arguments and return one valu Act on each row returned Return one result per row May modify the datatype Can be nested
unction_name (columnexpression, [argl, arg2,. . . ]) I
OR* A.CLCE"
Single-Row Functions Sinale-ro\v finctions are used to maniplate data tems. TTiey accept one or more arguments and reum one \alue for each row returned bv the querv. An argument can be one of the fo!lo\ving: User-supplied constan! Variable valu Column ame Expression Features of single-rcnv finctions: Act on each row returned in the query Return one result per row May return a data valu of a dfferent type than that referenced May expect one or more arguments Can be used in SELECT. WHERE. and ORDER BY clauses: can be nested fiinction_name coliinm expression argl. arg2 is the ame of the function is any named datbase column is any character string orcalculated expression is an)' argument to be used by the function Introduction to Oracle: SQL and PL/SQL 3-5
In the syntax:
Single-Row Functions
Single-row functons
OF?/\CIL,E
Single-Row Functions (continued) 71ns Icsson co\ers llie folloxving single-ro\v functions: fharacter ftinctions: Accept character input and can retum both character and number vales Number functons: Acccpt mimcric input and return numenc vales Date functions: Oprate on vales of the date datatype (All date functons return a valu of date datan pe except the MONTHS_BETWEEN function. \\hich returns a number.) Conversin finctions: C'onvert a valu from one datat>pe to another General finctions:
NVL ftinction
DECODE function
Character Functions
Character functions
_L
Case conversin functions
LOWER UPPER INITCAP
3-7
Character Functions
Single-ro\v character functions accept character data as input and can retum both character and iHimber vales Character finctions can be divided mto the following. Case conversin ftinctions Character manipulation functions
r runction
LOWER(eo///;|eA7>n.'Wn) UPPER(co/ttmn expreaxian)
lNITCAP(c>//m;<.'.\7>/v.v.</oy;)
Purpose Convcrts alpha charactcr vales lo \cm crease Convcrls alpha charactcr \alucs to uppcrcase Convcrts alpha characlcr \alucs lo uppcrcase for (he firsl Icitcr ofcpcli \\ord- all olhcr Ictlcrs in lowcrcasc Concalcnatcs thc first characlcr vale lo ihc sccond characlcr \aluc: cqunalcnt to concatcnation opcralor (|) Rclurns spccificd characlcrs froni charactcr \alc slarting at charactcr posiion m. n characlcrs longdr/?? is ncgahvc. ihc counl slarts froni ihc cnd of thc charactcr \aluc- II /? is omicd. all charactcrs to thc cnd of Ihc string are rcturncd )
Note: The functions discussed in this lesson is a subset of the availabtc functions.
Character Functions
Character functions
J_
Case conversin functions
LOWER UPPER INITCAP
1
Character manipulation functions
CONCAT SUBSTR LENGTH INSTR LPAD TRIM
Copyright
Purposc Rclums tlic nunibcr of charactcrs in \a!uc Rclums Ihc niimcric posilion ofa namcd charactcr Pads Ihc charactcr valu nghl-juslincd lo a lolal \\idlh ofn cliaracicr posilions Enabics \ou lo tnm hcadnig or iraihng characlcrs (or both) froni a charactcr slrmg. lf tnm characlcr or tnm sourcc is a charada- literal, yon mus cnclosc u n single quolcs This is a fcalurc a\iilablc lYom Oraclc8/ on\\ard.
Case Conversin Functions LOWER- UPPER. and INITCAP are the three case conversin functions. LOWER: Oonverts mixed case or llppercase character string to loxvercase UPPER: Oonverts mixed case or loxvercase character string to uppercase INITCAP: Converts first letter of cach \\ord to uppercase and remaming letters to lowercase
SQL> SELECT 'The Job title for '||INITCAP(ename)||' is ' 2 ||LOWER(job) AS "EMPLOYEE DETAILS" 3 FROM emp; EMPLOYEE DETAILS The Job title for King is president The Job title for Blake is manager The Job title for Clark is manager
DEPTNO 30
CDF^rf^KdL-CE
j 1
Case Conversin Functions (continued) llie shde example displays the employee number ame, and department number of employee BLAKE Tlie W H E R E clause of the first SQL statement specifies the employee ame as ' blake ' Since all the data m the EMP table is stored in uppercase. the ame ' blake' does not fmd a match in the EMP table ajid as a re su 11 no rows are selected The WHERE clause of the second SQL statement specifies that the employee ame in the EMP table is compared to ' blake' , converted to upper case Since both the names are in uppercase no\v. a match is found and one row is selected, The W H E R E clause can be rewntten in the follo\vmg manner to produce the same result: ... WHERE ename = 'BLAKE'
Tlie ame in the output appears as it \vas stored in the datbase To display the ame \\\th the first letter capitalized. use the INITCAP function in the SELECT statement. SQL> SELECT 2 FROM 3 WHERE empno, INITCAP(ename), deptno emp ename = UPPER('blake');
6 3
******5000 MITH
Character Manipulation Functions CONCAT. SIJBSTR. LENGTH. INSTR. LPAD. and TRIM are tlie si\ character manipulado ftinctions covered in this lesson. CONCAT: Joins vales together (Yon are limitcd to using t\\o parameters \\ith CONCAT) SIJBSTR: Extrais a String of detemuned length LENGTH: Shows the length of a string as a numeric valu INSTR: Finds numeric position of a named character LPAD: Pads the character valu right-justified Note: RPAD character manipulation function pads the character valu left-justified TRIM: Trims heading or trailing characters (or both) from a character string. If tnm_character or trim_source is a character literal, yon must endose it in single qnotes.
JRNER
VRD
TURNERSAISMMJ WARDSALESMAN
';
.6: -: 4 -
- -<"
;0 1 21
Copyright v Oracle Corporation, 1999. All nghts reserved. CDR AdLjEE '
anipulation Functions (continued) ampie dfsplays employee ame and job |omed together. length of tile emplo\ee ame, eric position of the letter A in the employee ame, tbrall employees \vlio are in sales SQL statement on tlie sude to displav the data for those employees \vhose ames end \\ ith LECT ename, CONCAT(ename, Job), LENGTH(ename), INSTR(ename, 'A') emp SUBSTR(ename, -1, 1) = 'N' ; LENGTH(ENAME) INSTR(ENAME,'A')
:OM :ERE
Number Functions
ROUND: Rounds valu to specified decimal ROUND(45.926, 2) -+ 45.93 TRUNC: Truncates valu to specified decimal TRUNC(45.926, 2) - 45.92
Number Functions Number funcions accept numenc mput and retum numenc vales Thts section descubes some of the inimber finctions.
Function Purposc
ROUND(or.>/!//?w|i'.v/?/''xs/f>/7. n}
j Rounds llic column. cxprcssion. or \aluc to'? dccimol places or ifn K omiltcd- no decimal places (ll'/j is ncgalnc. nnmbcrs to IcTl oi thc decimal point are roundcd ) Trncales (lie column. cxprcssion. or \aluc lo;7 decimal ! places or t f / 7 is omillcd. no decimal places l l f / is ncgali\c. numbers Icft of thc decimal poml are truncalcd to /ero ) i Rctums ihc remainder ol'm dividcd b\ n
TRUNC(fo//H;;|(.'.Kyjrt'.w;on.;)
Note: Tliis list is a siibset of the a\ailable nuniber fiuictions. For more infonnation. see rnele Serv1 r SOI. KiHrcncc. Relase X. "Number Functions
Copyright
ROUND Function The R O U N D function rounds the column. expression. or valu to n decimal places If the second argumeiu is O or K missing. the valu is rounded to zero decimal places. If the second argument is 2. the valu is rounded to two decimal plaees. Conversely. if the second argument is -2. the v a l u is rounded to two decimal places to the left. Tlie ROUND function can also be used \\ith date tunctions Yon will see examples later m this lesson. The DUAL is a duinmv table. More about this \vill be covered later.
SQL> SELECT TRUNC (45 . 923 ,2) , TRUNC (45. 923) , 2 TRUNC (45, 923, -1) 3 FROM DUAL;
}-15
OR/\CIL,E
TRUNC Function The TRUNC function tnincates the coluinn. expression. or valu to u decimal places The TRUNC function works with arguments similar to those of the RO ND function If the second argunient is O or is missing. the valu is tmncated to zero decimal places. If the second argument is 2 the valu is tmncated to two decimal places Converselv. if the second argument is -2. the valu is tmncated to hvo decimal places to the left. Like the ROUND function, the TRUNC fimction can be used \\ ith date functions.
1250
100
1500
250
MOD Function The MOD function fmds the remainder of valu I divided by va!ue2. The shde example calclales llie remainder of the ratio of salan, to commission for all employees whose |ob tille is salesman
Copyright
Oracle Date Format Oracle stores dates in an interna] numeric format. representing the century. year. month. day. hours. minutes, and seconds. The default displny and mput formal for an\ date is DD-MON-YY Valid Oracle dates are het\veen Jannary I. 4 7 I 2 B C - and D e c e m b e r l . W99 A D SYSDATE SYSDATE is a date function that rehinis the current date and time. Yon can use SYSDATE ust as you \\ould use any other coiuinn name For example. yon can displav tile current date by seeciim SYSDATE from a table. It is customary to select S"v'SDATE from a d u m m y table called D U A L DUAL Tlie DUAL table is o\\ned by the user SYS and can be accessed by all nsers. It coutams one cohimn. DUMMY. and one ro\v \\ith the \aliie X Tlie DUAL table is usefnl when yon \vant to retum a valu once onlyfor instance. the valu of a constant. pseudocohimn. or e\pression tliat is not derived from a table \vith user data. Tile D U A L table is generalh used for SELECT clanse syntas completeness. because both SELEC'Tand FROM clauses are mandatory. and severa! calculations do not need to select from actual tables Example Display the current date usmg the D U A L table SQL> SELECT 2 FROM SYSDATE DUAL ; Introducton to Oracle: SQL and PL/SQL 3-17
{ZDf^^AXZL-EE'
Arithmetic with Dates Slice the datbase stores dates as numbers. yon can perfonn calculations using arithinetic operators such as addition aiid subtraction. Yon can add and subtract number constants as \vell as dates Yon can perfonn the tbllowing operations:
Opcration dale + number dale - number date - date date + iiumbcr/24 RcMilt Date Daic Number ofdays Date Dcscription Adds a number ol"da\ s to a date Sublracls a number of days from a date Subtracts onc date from anothcr Adds a number of hours to a date
Copynghl
Arithmetic with Dates (continuad) The example on the slide displays the ame and the nnmber of weeks employed for all employees in department l(). It subtracts the current date (SYSDATE) from the date on wlucli the emplovee u as hired and divides the rcsult by 7 to calculate the nuniber of weeks that a worker has been emplo\ed Note: SYSDATE is a SQL function that returns the current date and time Your results may difTer from the example.
Date Functions
Function MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC Description Number of months between two dates Add calendar months to date Next day of the date specified Last day of the month Round date Trncate date
3-20
OR/VCILCEE '
Date Functions Date ftinctions oprate on Oracle dates. All date ftinctions rettim a valu of DATE datatvpe except MONTHS BETWEEN, \vhich retums a inimeric valu MONTHS_BETWEEN(c///.'/. dcite2): Fmds the number of months between cate! and cate?. Tlie result can be positive or negative. If date! is later than dale2. the result is positive. f i / a i c l is earherthan cate 2. the resuit is negative. The nonintegerpart ot the result represents a portion of tlie month. ADD_MONTHS(/~fiV. /?): Adds ;; number of calendar months to dale. The valu of n must be an integer and can be negative. NEXT_DAY(/7/c, ' char'): Finds the date of the next specified day of the week ( ' cliar' ) following dale. The valu of char may be a number representing a day or a character string. LAST_DA Y(or<?): Finds the date of the last day of the month that contains date. ROUND(date[, ' f n n ' ] ) : Retums date rounded to the unit specified by the fomiat model/wi/. If the forrnat model/mf is omitted, date is rounded to the nearest day. TRUNC(rfaf<?[. 'fmr' ]): Retums date with the time portion of the day truncated to the unit specified by the formal model/mr. If the formal model/;;if is omitted. date is truncated to the nearest day.
This list is a subset of the a\ ailable date functions. The formal models are covered later in this lesson. Examples of fonnat models are month and year.
LAST_DAYC01-SEP-95')
i-21
-^ '30-SEP-95'
empno, hiredate, MONTHS_BETWEEN(SYSDATE, hiredate) TENURE, ADD_MONTHS(hiredate, 6) REVIEW, NEXT_DAY(hiredate, 'FRIDAY'), LAST_DAY(hiredate) errp MONTHS BETWEEN (SYSDATE, hiredate)<200;
EMPNO HIREDATE
TENURE REVIEW
Copyright
Date Functions (continued) Tlie ROUND and TRUNC functions can be nsed tbr mimber and date valnes. When used \vith dates, (hese functions round or tmncate to the specified forma! model rherefore. vou can ronnd dates to thc nearest yearor month Example Compare tlie hire dates tbr all emplovees \\ ho staned in 1982. Dispiay the employee inimbcr. hire date, and month started using the ROUND and TRUNC ftinctions SQL> SELECT empno, hirdate, 2 ROUND(hirdate, 'MONTH'), TRUNC(hirdate, 'MONTH1) 3 FROM errtp 4 WHERE hiredate like '%1982'; EMPNO HIREDATE ROUND(HIR TRUNC(HIR
Conversin Functions
Datatype conversin
I
Implicit datatype conversin
1
Explicit datatype conversin
3-23
Conversin Functions
In addition to Oracle datatypes. columns of tables in an OracleX datbase can be defined using ANS. DB2. and SQL/DS datatypes However. the Oracle Sener intemally converts snch datatypes to OracleS datatypes. In some cases. Oracle Sener allo\vs data of one datatype \vhere it expects data of a different datatype. This is allowed \vlien Oracle Sener can automtica!!} convert the data to the expected datatype Tliis datatype conversin can be done imp/icir/y by Oracle Sener or explicitly by the user. Implicit datatype conversions \vork according to the mies explained in next t\vo slides. Explicit dataty pe conversions are done by using the conversin ftinctions. Con\ ersion ftinctions convert a valu from one datatype to another. Generally. the fonn of the function ames follows the convention datan'pe TO datafypc. The first datatype is the mput datat\ pe; the last datatype is the output. Note: Although implicit datatype conversin is available. it is recommended that yon do explicit datatype conversin to ensiire reliability of your SQL statements.
Implicit datatype Conversin Tlie assignment succeeds if the Oracle Servercan convert the datatype of (he \alue uscd in the assignment to that of the assignment target
NUMBER DATE
3-25
NUMBER
DATE
TO CHAR
TO CHAR
Explicit Datatype Conversin SQL provides tliree functions to con\ert a valu from one dalatype to another: Fumtion Purposc Comcris a numbcr or dale \alnc lo a VARCHAR2 characlcr slring \\ilh Ibmial modcl fin. Numbcr Conversin nlsparams paramclcr si^ccifics Ihc Ibllouing characicrs. \\lncli are rctiirncd b\ iuimlx;r fonnal elcmcms: Decimal characlcr Group scparalor Local currcnc) symbol Inlcmalional currcncy Symbol
lf nlsparams or any oilicr paramclcr is omitted. llns lunclion uses Ihc dcfaull paramclcr \alucs Por ihc scssion
NUMBER
DATE
TO CHAR
TO CHAR
3-27
Purposc Date Conversin Thc njsparams paranielcr spcciiics fhc languagc in \x hich monlh and da\ ames and abbrcviations are rcliinicd. If lilis paramctcr is omillcd. lilis l'unclion uses tlic dcfatill dale languagcs ibr llic scssion /nlxparamxf) Convcrts a characlcr slrmg conlaming digit.s lo a mimbcr in llic formal spcciTicd bx thc oplional termal niodc! fhn Tlie nfsparams parameicr lias tlic same purposc in ibis lunclion as in llic TO_CHAR function Ibr numbcr con\crsion.
i TO_NUMBERU-/JW.//wrf/.
TO_DATE(C/K/r[/m|.|/7/.v/M/YH!.<r|)
Conx cris a characcr slnng rcprcscnling a dale lo a dale xaluc according lo ihc fml spcciTicd. \(fml is omillcd. thc formal is DD-MON-YY Thc nlsparams paramelcr has thc same purpose in tlus lunclion as in llic TO_CHAR fuiclion Ibr dale convcrsioiv
NUMBER
DATE
TO CHAR
TO CHAR
Explicit Datatype Conversin (contlnued) Note: The list of functions mentioned in this lesson are a subset of the available conversin fimctions. For more intormatioii- see Oriiclct S'n'cr SOI. /-tejcrcfice. Itefeas' 8-0. "Comersion Functions
The format model: Must be enclosed in single quotation marks and is case sensitive Can include any valid date format element Has an fm element to remove padded blanks or suppress leading zeros Is separated from the date valu by a comma
Copyright ' Oracle Corporation. 1999 AN rights reserved
Displaying a Date n a Specific Format Previously. all Oracle date vales ere displayed in the DD-MON-YY fomiat. Tlie TO CHAR ftmction allo\vs yon to comert a date from tliis default fomiat to one specified by yon. Guidelines The format model inust be enclosed in single quotation marks and is case sensitive. The fomiat model can include any valid date fonnat element. Be stire to seprate the date valu from the fonnat model by a comma. Tlie ames of days and months in the output are automatically padded \vith blanks. To remove padded blanks orto suppress leading zeros, use the fill mode fm element. Yon can resize the display idth of the resulting cliaracter field with the SQL*Plus COLUMN command. Tlie resultan! column uidth is 80 characters by default empno, TO_CHAR(hirdate, 'MM/YY') Month Hired emp ename = 'BLAKE';
Full year in numbers Year spelled out Two-digit valu for month Full ame of the month Three-letter abbreviation of the day of the week Full ame of the day
Copyright: Oracle Corporation. 1999 A nghts reserved
MONTH
DY
DAY
SYFAR or Y F A R
BC orA.D
_MM_
MONTH
MON
RM
m>O or DD o D
C3F? AGLE *
Time Formis Use the fomiats fsted in the folloxving tables to dispJay time infonmation and (iteris and to change numeris to spelled numbers.
Elfmene DescripMm Meridan ndicator Meridi.ln indicator with periods Hour of day or hour ( J - \ 2 ) or hour (0- 23 ) Minute (0-59) Second (0-59) Secondsjjasi mdnjh( 10-86399) Oescripiio PunclwlKJii is tepr<xuccj t i (he resufl Quocd slnny sregroiictt in [he rcsull
AM or PM
A.M. or P.M.
HHorHH12o. HH24
MI SS
SSS.SS
Other Formis
\ EJemtnt
i .j
| -oflhe"
1 I
(S.P
: SPTH o THSP
HIREDATE
H I RDATE 17 November 1981 1 May 1981 9 June 1981 : 2 April 1981 28 September 1981 20 February 1981
14 rows selected.
3-32
TO_CHAR Function with Dates llio SQL stntenient on the slide displays the ame and hire dates for all tlie emplosees Tlie hire date appears as 17 November 1 9 X 1 Example Modity Ihe slide e\ample to displas the dates in a formal that appears as Seventh of Febnian 19X1 OX ( ) ( ) ( ) ( ) AM SQL> SELECT 2 3 4 FROM ENAME KING BLAKE ename, TO_CHAR(hiredate, ' fmDdspth "of" Month YYYY fmHH:MI: SS AM') HIREDATE emp ; HIREDATE Seventeenth of November 1981 12:00:00 AM First of May 1981 12:00:00 AM
Notice that the inonth follows tlie fomiat model specifed. in other words. the tirst letter is capitalized and the rcst in lowercase
Use these formis with the TO_CHAR function to display a number valu as a chara ter:
9 0 $ L
j
Represents a number Forces a zero to be displayed Places a floating dollarsign Uses the floating local currency symbol Prints a decimal point Prints a thousand indicator
Copyright'" Oracle Corporation. 1999 All rights reserved
! '1
0 $ I.
090999
5,999099 ] 999999
O )l 2.i 4
SI2.-1 FFI24 ] 234.(")0
999999 99
999,999
MI
PR
ERKE
V
Minus sipns to right 1 negative \'alucs Parenthes7e negan'e nun>!iers Scienlific notolion (tbnnat inust specity follr Es) MtillipK hv ! () u lunes (n - iiiunber ot' 9s after V ) Oisp!a\ zero values os blank. nol f
SALARY $3,000
3-34
Copyright
CDR^AdLGE*
Guidelines
Tlie Oracle Serverdisplays a stnng ofpound signs (#) in place of a \\hole number \\hose digits exceed the niimhcr of digits provided ni the format model Tlie Oracle Sen er roiinds the stored decimal \ alue to the number of decimal spaces provided m the fonnat model
TO_NUMBER and TO_DATE Functions You may \vaiit to convert a character string to ethera number or a date. To accoinplish tlus task. \ou use the TOJMUMBER or TO_DATE fimctions. Tlie format model yon choose \vill be based on ie previously demonstrated formal elemcnts. Example Display the ames ajid hire dates of all the employees \vho joincd 011 Febniary 22. 19XI. SQL> SELECT ename, hiredate 2 FROM emp 3 WHERE hiredate = TO_DATE ( ' February 22, 1981',
'Month dd,
YYYY ' ) ;
ENAME WARD
HIPEDATE 22-FEB-S1
RR Date Format .
Current Year
1995 1995 2001 2001
Specified Date
27-OCT-95 27-OCT-17 27-OCT-17 27-OCT-95
0-49
50-99
0-49
The return date is in 50-99 the century after the current one
The return date is in the century before the current one The return date is in the current century
5-36
The RR Date Format Element The RR date formal is similar lo the V Y element. hu it allows yon to specify difieren! cenlnnes. Yon can use the RR date formal element instead of YY. so tliat the century of the retum valu vanes according to the specified fuo-digit year and the last two digits of the current year. The table on the shde summarizes the behavior of the RR element.
Currtnt Year Ghcn Dato
Intcrprctrtl (RR)
1 995 20 1 7
20I7
Intcrprctcd (Y Y)
1 994 1 994
20DI
1 995
19 1 7
2017
NVL Function
Converts nuil to an actual valu Datatypes that can be used are date, character, and number. Datatypes must match - NVL(comm,0) - NVL(hiredate,'01-JAN-97') - NVL(job,'No Job Yet')
CDRACLCEE *
Yon can use the NVL function to convert any datatype. but tlie return valu is ahvays the same as the datatype of exprl
1400 300
1 4 rows selected.
3-38
ORACILE '
NVL Function To calclate the annual compensation of all employees, yon need to multiply the nionthly salan h\ 12 and then add the conimission to U SQL> SELECT ename, sal, comm, (sal*12)-t-comm 2 FROM emp ; ENAME
1400
16400
Notice that the annual compensation is calculated only for those employees who ean a commission. If any colunin \alue in an expression is n u i l , the result is nuil. To calclate vales tbr all emptoyees. \ou nmst convert tlie nuil \alue to a number before applying the anthnietic operator. In the example on the shde. the NVL ftinction to is used to comet nuil vales to zero.
DECODE Function
Facilitates conditional inquines by doing the work of a CASE or IF-THEN-ELSE statement
DECODE(col/expression, searchl, resultl [, search2, result2,..., [, default])
The DECODE Function The DECODE ftinction decodes an expression in a way similar to the IF-THEN-ELSE logic used m \ arious languages- Tlie DECODE function decodes c'\prcxsi<i after comparmg it to each search valu. If the expression is the same as seiirch. repul is retunied. If the default valu is omitted. a nuil valu is retumed \\here a search valu does not match am of the result vales
SAL)
REVISED SALARY FROM emp ; SAL REVISED SAIARY 5000 2850 2450 5000 3420 2940
14 rows selected.
3-40
C3R A^CL-CE
Using the DECODE Function In the SQL statement aho\c. tlie valu of JOB is decoded If JOB is ANALYST, the salan, ulerease is IOV if JOB is C L E R K . the salan mercase is 15%. if JOB is MANAGER, the salan menease is 20",, Forall other |oh roles, there is no inciea.se in salan The same statement can be untten as a IF-THEN-ELSE statement: THEN THEN THEN sal = sal*1.1 sal = sal*1.15 sal = sal*1.20
0, 1, 2, 3, 4, 5, 6,
10 1 1 FROM 12 WHERE
MI
Copyright
Example Tile slide shows another e\ample usiny tile DECODE fimctioii- In this example. \ve delennine the tn\ rate for each employee in department 50 based on the monthly salan,. Tlie ta\ rates are as per the vales meiitioned in the follo\\ing table Monthlv Salan' Rftnge $0.00-999.99 $1.00000- 1.999.99 $2,000 (X)- 2. 999 99 3.000 (X) - 3.999.99 4.000.00 - -1.999.99 $5 (100 i)- 2.999.99 $6.000 M>- 6.999 99 $7.000 00 or greatei ENAME BLAKE MARTIN ALLEN TURNEP. 2850
9
Rule
0%
9%
20% 30% 40%
42% 44% 45%
Nesting Functions
Single-row functions can be nested to any level. Nested functions are evaluated from deepest level to the least-deep level. F3 (F2(F1 (col,argl) ,arg2) ,arg3)
ti
i1
;k
Nesting Functons
Singe-ro\\ ftinctions can be nestcd to an\ deph Nesed fimctions are evaluaed ron thc innermost !c\ el to the outermost levei. Somc e\amples follow to sho\\ yon lie flxbitity of thesc functions
Nesting Functions
ENAME KING
NVL(TO_CHAR(MGR),'NOMANAGER') No Manager
Nesting Functions (continued) The sude example displays the head of the company. who has no nianager. The evaluation of the SQL statement involves two steps: 1. Evalate the inner function to conven a nuniber valu to a charnctci strmg. Example Display the date of the ne\t Fnda\ that is six montlis from the hire date. The resulting date sliould appearas Friday. March 12th. 1982. Orderthe results b\ hire date SQL> SELECT 2 3 4 5 FROM 6 ORDER BY TO_CHAR (NEXT_DAY (ADD_MONTHS (hiredate, 6), 'FRIDAY'), 'fmDay, Month ddth, YYYY') "Next 6 Month Review" emp hiredate; Resultl =TO_CHAR(msr) N V U R e s u l t l . 'No Manager 1 ) 2. Evaluate the outer ftinction to replace the nuil valu \vith a text stnng Tlie entire expression becomes the column heading because no cohrnin alias \vas gi\en
Summary
Use functions to do the following: Perform calculations on data Modify individual data tems Maniplate output for groups of rows Alter date formats for display Convert column datatypes
OR.ACIL.C~E/
Single-Row Functions Single-row functlons can be nested to any level. Single-rov. functions can maniplate the following: Character data: LOWER UPPER. INITCAP. CONCAT. SUBSTR. INSTR. LENGTH Number data: ROUND. TRUNC. MOD Date data: MONTHS BETWEEN, ADD MONTHS. N EXT DA Y, LAST DAY. ROUND. TRUNC Date vales can also use anthmetic operators. Conversin ftinctions can conven character. date, and numenc vales: TO CHAR. TO DATE. TO N U M B E R
SYSDATE and DUAL SYSDATE is a date tunction that retunis the current date and time. It is customary to select SYSDATE from a dninmv Uible called DUAL.
Practce Overview
Creating queries that require the use of numeric, character, and date functions Using concatenation with functions Writing case-insensitive queries to test the usefulness of character functions Performing calcuiations of years and months of service for an employee Determming the review date for an employee
3-45 Copyright i- Oracle Corporation, 1999 Al! rights reserved C3R/\CIL,E *
Practice Overview
Tliis practice is desjgncd to gi\e vou a varielv of exercises using differcnt ftinctions availablc for character. iiumber. and date datatypes. Remember that for nested functions. the results are evaluated from the nnermost ftmction to the otitemiost function.
Practice 3 I Write a quen to display thc curren! date. Labcl thc column Dale Date 28-OCT-97 2 Display the employee number ame, salan, and salary mercase by 15% expressed as a \vhole number Label (lie colnmn Ne\v Salan Save your SQL statement to a file named p3q2.sql. Run yourquery m the file p>3q2 . sql . EMPNO EN AME 7339 KING 5000 7698 BLAKE 2850 2450 77S2 CLARK 7566 JONES 2975 765^1 MARTIN 1250 7495 ALLEN 1600 7344 TURNER 1500 950 7900 JAMES 1250 7521 WARD 7 902 FORD 3000 7369 SMITH 300 7793 SCOTT 3000 7876 ADAMS 1100 793-3 MILLER 1300 14 rows selected. 4 5750 3278 2818 3421 1438 1840 1725 1093 1438 3450 920 3450 1265 1495
Modify vour querv p3q2 . sql to add a colnmn tliat will subtract tlie od salan from the new salan. Label the colnmn Increase Renm yourquery. EMPNO ENAME 7839 KING 7698 BLAKE CLARK JONES 7654 MARTIN 7499 ALLEN 7844 TURNER 7900 JAMES SAL New Salary Increase
Practice 3 (continued) 5. Display the employee s ame, hire date, and salan revie\v date, \vliich s tlie first Monday after six montlis of serv-ice. Lahel the column REVIEW Fomiat the dates to appear in thc fonnat similar to "Sunday. the Seventh of September. 1981."
ENAME KING BLAKE CLARK JONES MARTIN ALLEN TURNEE JAMES WAPD FORD SMITH SCOTT ADAMS MILLER HI RDATE REVIEW Monday, the Twenty-Fourth of May, 19 Monday, the Second of Novembe r, 1981 C Monday, the Fourteenth of Dec embe r , 1 981 Monday, the Fifth of 0c t obe r , 198 1 Monday, the Twenty-Nnth of M arch , 1 9E Monday, the Twenty-Fourth of Augu st , 1 1981 Monday, the Fifteenth of Marc h, 1 982 Monday, the Seventh of June , 1982 Monday, the Twenty-Fourth of August, J Monday, the Seventh of June, 1982 Monday, the Twenty-Sec ond of June , 1 QC Monday, the Thirteenth of June, 1983 Monday, the Eighteenth of Jul y, i 983 Monday, the Twenty-Six th of Jul y. 19
17 -NOV- S 01 -MAY- 81 OS -JON- 81 02 -APR- 81 9 -SEP- 81 20 -FEB- 81 08 -SEP- 81 03 -DEC- 81 O O -FEB- 81 03 -DEC- 81 17 -DEC- 80 09 -DEC- 09 12 -JAN- 83 23 -J AN- 82
s:
14 rows selected.
For each employee displa> tlie emploxee name and calclate (lie nuniber of montlis behvcen todax and the date the empknee xvas hired Labe I the column MONTUS WORKED Order your results b\ the number o months employed Round the luimber of mouths up to the closest \\hole number.
EN AME
MONTHS WORKED
ADAMS SCOTT MILLER JAMES FORD KING MARTIN TURNER CLARK BLAKE JONES WARD ALLEN SMITH
177 178 188 190 190 191 192 193 196 197 198 1 99 199 202
14 rows selected
Practice 3 (continued) 7. Write a query tliat produces the folloumg for each employee: <employee name> eams <salan > monthly but \vants <3 times salan > Label the column Dream Salanes. Dream Salaries KING earns $5,000.00 monthly but wants $15,000.00. BLAKE earns $2,350.00 monthly but wants $3,550.00. CLARK earns $2,450.00 monthly but wants $7,350.00. JONES earns $2,975.00 monthly but wants $3,925.00. MARTIN earns $1,250.00 monthly but wants $3,750.00. ALLEN earns $1,600.00 monthly but wants $4,800.00 TURNER earns $1,500.00 monthly but wants $4,500.00. JAMES earns $950.00 monthly but wants $2,850.00. WARD earns $1,250.00 monthly but wants $3,750.00. FORD earns $3,000.00 monthly but wants $9,000.00. SMITH earns $800.00 monthly but wants $2,400.00. SCOTT earns $3,000.00 monthly but wants $9,000.00. ADAMS earns $1,100.00 monthly but wants $3,300.00 HILLER earns $1,300.00 monthly but wants $3,900.00. 14 rows selected. If yon have time, complete the fbllo\vmg e\ercises: X. Crate a querv to display ame and salan, furall employees Formal the salan to be l characters long. left-padded \\ith $. Label tlie column SALARY. ENAME SALARY
SMITH $$$$$$$$$$$$800 ALLEN $$$$$$$$$$$1600 WARD $$$$$$$$$$$1250 JONES $$$$$$$$$$$2975 MARTIN $$$$$$$$$$$1250 BLAKE $$$$$$$$$$$2850 CLARK $$$$$$$$$$$2450 SCOTT $$$$$$$$$$$3000 KING $$$$$$$$$$$5000 TURNER $$$$$$$$$$$1500 ADAMS $$$$$$$$$$$1100 JAMES $$.$$$$$$$$$950 FORD $$$$$$$$$$$3000 MILLER $$$$$$$$$S$1300 14 rows selected.
Practice 3 (continued) 9 Write a query that \vill displav the employec's ame \\ith the first letter capitalized and all other letters lowercase and tlie length of their ame, for all employees wiiose ame starts \vith J. A. or M. Give each cohimn an appropriate label ame Length
Jones 5 Martin 6 Alien 5 James 5 Adams 5 Miller 6 6 rows selected. 10 Displav the ame, hire date, and dav of the \\eek on \vhich the employee started. Label the colnnin DA Y. Order the resiilts bv the dav of the ueek starting \\ith Mondar
MARTIN2S-SEP-81 CLARK 09-JUN-31 KING 17-NOV-S1 TURMER O 8-SEP-81 SMITH 17-DEC-SO 12-JAH-83 02-APR-81 03-DEC-Sl 09-DEC-82 03-DEC-81 20-FEB-81 Ol-MAY-81 MILLER23-JAN-82 VJARD 22-FEB-81 14 rows selected.
MOMDAY TUESDAY TUESDAY TUESDAY WEDNESDAY WEDNESDAY THURSDAY THUPSDAY THURSDAY THURSDAY FRIDAY FRIDAY SATURDAY SUHDAY
Practice 3 (continued) If \ou want extra challenge, complete the followmg exerctses 1 1 . Crate a querv iat \\ill display the employee ame and commission aniount If the employee does not eam commission. put "No Commission Label tlie colnmn COMM ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER COMM No Commission 300 500 No Commission
1400
No No No No 0 No No No No Commission Coimmission Commission Commission C -"'irirni ss i c>n Cc-mmission Cc>mmission Commission
14 rows selected .
12 Crate a qnery that displays the emplovees ames and indcales the amounts of their salaries through astensks. Each astensk signifies a hundred dollars Sort the data m descendmg order of salar> Label the colnmn EMPLOYEE AND THEIR SALARIES EMPLOYEE AND THEIR SALARIES KING FORD SCOTT JONES BLAKE CLARK ALLEN TURNER MILLER MARTIN WARD ADAMS JAMES SMITH 14 rows ********, **** + + **, ********, +*******, *** + ****, +********+******, * + + *****. ********, ********, ***,****, ********, ********, ******** selected.
Practice 3 (continueci)
If yon \vant an extra challenge, complete the follcnving exercise: 13. Wnte a query that displa\ s the grade of all emplovees hased 011 the valu of the colunin JOB. as per the table shown belcm
.ion
PRESIDENT MANAGER ANALYST SALESMAN CLERK Nonc oflhc abovc
(;R41)E
A B C D E O
JOB
GRADE
E D D B D B B C