You are on page 1of 49

Single-Row Functions

Copyright 1 Oracle Corporation. 1999 All rights reserved

CZ5F? AC.L.GE '

Two Types of SQL Functions

Functions

Single-row functions

Multiple-row functions

Copyright'" Oracle Corporation. 1999 Al rights reserved

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

Introduction to Oracle: SQL and PUSQL 3-4

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

Copyright ' Oracle Corporaiion. 1999. All rights reserved.

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

Copyright' Oracle Corporation. 1999 All nghts reservad

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

Introduction to Oracle: SQL and PL/SQL 3-6

Character Functions
Character functions

_L
Case conversin functions
LOWER UPPER INITCAP

_L Character manipulation functions


CONCAT SUBSTR LENGTH INSTR LPAD TRIM

3-7

Copyright : Oracle Corporation. 1999 All rights reserved

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 )

CONCATco/mm; /li'xpivssionl. Ct>himn2\exi>ressimi2) SUBSTR(c//mnii?.v/t/v,.von.;n/.//)

Note: The functions discussed in this lesson is a subset of the availabtc functions.

Introduction to Oracle: SQL and PL/SQL 3-7

Character Functions
Character functions

J_
Case conversin functions
LOWER UPPER INITCAP

1
Character manipulation functions
CONCAT SUBSTR LENGTH INSTR LPAD TRIM

Copyright

Oracle Corporation. 1999. All rights reserved.

Character Functions (continued)


| Functim LENGTHuW/ t'.v/i/wwu'M I NSTR(cY>////7m;e'Ayf/v.vs7 ni. ni ) LPAD(c)////?m t'.v/i/vv.v/)/;. n . ' s/nnfi' ) TRIM(/<?tfmg trailing\hoih. l/'ini cfttff'ad^f l-ROM It'ini vm//'cv)
i

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.

Introduction to Oracle: SQL and PL/SQL 3-8

Case Conversin Functions


Convert case for character strings Function Result LOWER( ' SQL Course ' ) sql course UPPER('SQLCourse-) SQL COURSE INITCAP(' SQL Course1) Sql Course

Copyright 1 Oracie Corporation. 1999 All rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-9

Using Case Conversin Functions


Display the employee number, ame, and department number for employee Blake.
SQL> SELECT empno , ename, deptno 2 FROM emp 3 WHERE ename = ' blake '; no rows selected SQL> SELECT 2 FROM 3 WHERE empno, ename, deptno emp ename = UPPER ( 'blake' ) ;

EMPNO ENAME 7698 BLAKE


3-10

DEPTNO 30
CDF^rf^KdL-CE

j 1

Copyright ' Oracle Corporation. 1999 All righs reserved

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');

Introduction to Oracle: SQL and PL/SQL 3-10

Character Manipulation Functions


Maniplate character strings
Function CONCAT( ' Good ' , 'String') SUBSTR('String',1,3) LENGTH(' String1) INSTR(-Strmg', T - ) LPAD(sal,10,'*') TRIM('S' FROM 'SSMITH') Result GoodString
Str

6 3

******5000 MITH

Copyright' Orade Corporation. 1999 All rights reserved

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.

Introductor) to Oracle: SQL and PL/SQL 3-11

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

CONCAT(ENAME,JOB) MARTINSALESMAN ALLENSALESMAN

Introduction to Oracle: SQL and PL/SQL 3-12

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

MOD: Returns remainder of divisin MOD(1600, 300) -> 100

Copyright ' Oracle Corporatran. 1999. All rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-13

Using the ROUND Function


SQL> SELECT ROUND(45.923,2), ROUND(45.923;, 2 ROUND(45.923,-1) 3 FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45,923,-1) 45.92 :*: 46 ; ; 50

Copyright

Oracle Corporaiion. 1999 A! rights reserved

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.

Introduction to Oracle: SQL and PUSQL 3-14

Using the TRUNC Function

SQL> SELECT TRUNC (45 . 923 ,2) , TRUNC (45. 923) , 2 TRUNC (45, 923, -1) 3 FROM DUAL;

TRUNC (45. 923, 2) 45.92

TRUNC (45 . 923) TRUNC (45. 923, -1} 45 40

}-15

Copyright Oracle Corporation. 1999 All rights reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-15

Using the MOD Function


Calclate the remainder of the ratio of salary to commission for all employees whose job title is salesman.
SQL> SELECT 2 FROM 3 WHERE ENAME MARTIN ALLEN TURNER WARD ename, sal, comm, MOD(sal, comm) emp ]ob = ' SALESMAN';
SAL

COMM MOD (SAL, COMM)


1400
300 0 500

1250 1600 1500 1250

1250
100

1500
250

Copyright Oracle Corporation. 1999 Ali nghts reserved

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

Introduction to Oracle: SQL and PL/SQL 3-16

Working with Dates


Oracle stores dates in an interna! numeric format: century, year, month, day, hours, minutes, seconds. The default date format is DD-MON-YY. SYSDATE is a function returning date and time. DUAL s a dummy table used to view SYSDATE.

Copyright

Oracle Corporation 1999 All rights reserved

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

Arithmetic with Dates


Add or subtract a number to or from a date for a resultant dae valu. Subtract two dates to find the number of days between those dates. Add hours to a date by dividing the number of hours by 24.

Copyright Oracle Corporation. 1999. Ati rights reserved

{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

Introduction to Oracle: SQL and PL/SQL 3-18

Using Arithmetic Operators with Dates


SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS 2 FROM emp 3 WHERE deptno = 10;

ENAME KING CLARK MILLER

WEEKS 830.93709 853.93709 821.36566

Copynghl

Oracle Corporation. 1999 All rights reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-19

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

Copyright *; Oracle Corporation, 1999. All rights reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-20

Using Date Functions


MONTHS_BETWEEN ('01-SEP-95Y11-JAN-941) * ADD_MONTHS('11-JAN-94',6) 19.6774194 ->-'11-JUL-941

NEXT_DAY ('01-SEP-95YFRIDAY') -^ -08-SEP-95'

LAST_DAYC01-SEP-95')
i-21

-^ '30-SEP-95'

Copynght Oracle Corporation. 1999 All righis reserved C3RAXHL.CE *

Date Functions (continuad)


For al I employees employed for fe\ver tlinn 200 nionths. display the einployee inimber. liirc date, nuniber of nionths employed. six-inoiith re\-ie\\ dale, first Friday aer hire date, and last day of tlie niontli \vlicn hired

SQL> SELECT 2 3 4 5 FROM 6 WHERE

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

NEXT DAY( LAST DAY

Introduction to Oracle: SQL and PL/SQL 3-21

Using Date Functions


ROUND(f25-JUL-95','MONTH') ^ 01-AUG-95 ROUND('25-JUL-95','YEAR') TRUNC('25-JUL-95VMONTH') TRUNC('25-JUL-95YYEAR') +~ 01-JAN-96 +~ 01-JUL-95 *- 01-JAN-95

Copyright

Oracle Corporation. 1999 A rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-22

Conversin Functions
Datatype conversin

I
Implicit datatype conversin

1
Explicit datatype conversin

3-23

Copyright ' Oracle Corporation. 1999. All righls reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-23

Implicit Datatype Conversin


For assignments, the Oracle Server can automatically convert the following: From VARCHAR2 or CHAR VARCHAR2orCHAR NUMBER DATE
To

NUMBER DATE VARCHAR2 VARCHAR2

Copyright :": Oracle Corporation, 1999 All rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-24

Implicit Datatype Conversin


For expression evaluation, the Oracle Server can automatically convertthe following:
From VARCHAR2 or CHAR VARCHAR2orCHAR
To

NUMBER DATE

3-25

Copyright Oracle Corporation. 1999 All rights reserved

Implicit Datatype Conversin


In general, the Oracle Sener uses the rule for expression \vheii a datatvpe comersion is needed n places not covered by a nile for assignment conversin*. Note: CHAR to NUMBER conversions succeed orilv tf the character stnng represents a valid mmiber. CHAR to DATE conversions succeed only if the character string has the default format DDMON-YY

Introduction to Oracle: SQL and PL/SQL 3-25

Explicit Datatype Conversin


TO NUMBER TO DATE

NUMBER

DATE

TO CHAR

TO CHAR

Copyright' Oracle Corporation. 1999 All nghts reserved

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

Explicit Datatype Conversin


TO NUMBER TO DATE

NUMBER

DATE

TO CHAR

TO CHAR

3-27

Copyright S Oracle Corporation. 1999 All rights reserved

Explicit Datatype Conversin (continued) Function


_ \nf.ytiirtims |

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

Introduction to Oracle: SQL and PL/SQL 3-27

Expcit Datatype Conversin


TO NUMBER TO DATE

NUMBER

DATE

TO CHAR

TO CHAR

Copyright Oracle Corporation. 1999 All rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-28

TO CHAR Function with Dates


TO CHAR (cuate, ' fmt')

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';

SQL> SELECT 2 FROM 3 WHERE

Introduction to Oracle: SQL and PUSQL 3-29

Elements of Date Format Model


YYYY YEAR
MM

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

Sample Elements of Valid Date Formis


rit'im-nt
SCC o CC
i

Ycars ni dates Y Y Y Y or SYYYY

Verir v \ n h cormm m thi

SYFAR or Y F A R

BC orA.D

_MM_
MONTH
MON

Nanjc o'nionih paJJcd \\ith blank^ lo Icngtli oi'mne characlcrs

RM

m>O or DD o D

i ame ot'dav. tluve-lcrte. abbicualion

Introducton to Oracle: SQL and PL/SQL 3-30

Elements of Date Format Model


Time elements formal the lime portion of Ihe dale.
HH24:MI:SS AM fl5:45:32 PM

Add character slrings by enclosing Ihem in double quotation marks.


DD "of' MONTH 12ofOCTOBER

Number suffixes spell out numbers.


ddspth fourteenth

Copyright <: Oracle Corporation, 1999 All rights reservecf

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

Specifying Suffixes to Influence Number Display


TH

-rOrdinal number (for examnle. DDTH for 4TH) I


l Spefied-out ordinoj nujnhers (for xainpe. DDSPTH for | FOUKTH)

(S.P
: SPTH o THSP

Introduction to Oracle: SQL and PL/SQL 3-31

Using TO_CHAR Function with Dates


SQL> SELECT ename , 2 TO CHAR (hi reda te, 3 FROM emp;
' f mDD Mon th YYYY')

HIREDATE

ENAME KING BLAKE CLARK JONES MARTIN ALLEN

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

Copyright ' Oracle Corporalion. 1 999 All nghts reserved

C3 R A.CZ L.G '

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

Introctuction to Oracle: SQL and PL/SQL 3-32

TO CHAR Function with Numbers


TO CHAR (number, ' fmt')

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

TO_CHAR Function with Numbers


When working \vitli number values sucli as character strmgs. yon should con\crt tliose mimbers to the character datat\ pe usmg the TO_CHAR ftinction. which transales a \alue of NUMBER dalatype to VARCHAR2 datatype. This lechniqnc is especially iiseful \\ith concatenation.

Number Format Elements


If yon are coiiverting a nnniberto character datatype. yo can use the tbllouing elements: ' Elcment Dcscription Nuntenc position numher ot 9s determine dtspl;i\ v\'idtlf Displa\" leading zeros Fioahng dollar sign Floalmg loca] currenev s\'mho Decnnal point in >osit!on specii'itxi Comnia ni position specified Examplc 909999 Rcsult I234

! '1

0 $ I.

090999
5,999099 ] 999999

O )l 2.i 4
SI2.-1 FFI24 ] 234.(")0

999999 99
999,999

1.254 1254<1214> I.2.MH-HW 12540(1 1254.00

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

099999MT 999999PR OO.OOOF.EFF 9000V99 pj9999 99

Introduction to Oracle: SQL and PL/SQL 3-33

Using TO_CHAR Function with Numbers


SQL> SELECT 2 3 FROM WHERE TO CHAR(sal , ' $99 , 999 ' ) SALARY emp ename = ' SCOTT ;

SALARY $3,000

3-34

Copyright

Oracle Corporation. 1999 Al nghts reserved

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

Introduction to Oracle: SQL and PL/SQL 3-34

TO_NUMBER and TO_DATE Functions


Convert a character string to a number format using the TO_NUMBER function
TO NUMBER (char-[ , 'fint'])

Convert a character string to a date format using the TO_DATE function


TO DATE (char [ , ' fat' ])

Copyright '" Oracle Corporation, 1999 All rights reserved-

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

Introduction to Oracle: SQL and PL/SQL 3-35

RR Date Format .
Current Year
1995 1995 2001 2001

Specified Date
27-OCT-95 27-OCT-17 27-OCT-17 27-OCT-95

RR Format 1995 2017 2017 1995

YY Format 1995 1917 2017 2095

If the specified two-digit year is:

0-49

50-99

If two digits of the current year are:

0-49

The return date is in the current century

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

Copyright Oracle Corporation. 1999.Ali nghts reserved

CZD IFs X\CH I EE

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

27-OCT-95 27-OCT-I7 27-OCT-17

1 995
19 1 7
2017

Introduction to Oracle: SQL and PL/SQL 3-36

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')

Copyright Oracle Corporation. 1999 All nghts reserved

CDRACLCEE *

The NVL Function


To conven a nuil valu to an actual vale, use tlie NVL function. Syntax NVL where: (exprl, cxprl i'.v/wJ expr2) is the source valu or expression that may contain nuil is the target valu tbr converting nuil

Yon can use the NVL function to convert any datatype. but tlie return valu is ahvays the same as the datatype of exprl

NVL Conversions for Various Datatypes


Data type NUMBER DATE CHAR or VARCHAR2 Conversin Exainplc NVL7Uf>nbei'_colifniii.9) NVL(date_coIinn, 'O -JAN-95') NVUcharacter_cc>lumn, 'Unavailable')

Introduction to Oracle: SQL and PL/SQL 3-37

Using the NVL Function


SQL> SE LECT ename, sal, comm, 2 FROM emp ; (sal*12) +NVL (eomm, 0)

ENAME KING BLAKE CLARK JONES MARTIN ALLEN

SAL 5000 2850 2450 2975 1250 1600

COMM <SAL*12)+NVL<COMM,0) 60000 34200 29400 35700 16400 19500

1400 300

1 4 rows selected.

3-38

Copyright Oracle Corporation, 1999 A rignts reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-38

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])

Copyright' Oracle Corporation. 1999 Atl rights reserved

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

Introduction to Oracle: SQL and PL/SQL 3-39

Using the DECODE Function


SQL> SELECT Job, sal, 2 DECODE (Job , 'ANALYST', SAL*1.1, CLERK' , 3 SAL* 1.15, ' MANAGER ' , SAi*1.20, 4
5 6 7 JOB

SAL)

REVISED SALARY FROM emp ; SAL REVISED SAIARY 5000 2850 2450 5000 3420 2940

PRESIDENT MANAGER MANAGER

14 rows selected.

3-40

Copyright ' Ofacle Co poration, 1999 All rights reserved.

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

Introducton to Oracle: SQL and PL/SQL 3-40

Using the DECODE Function

[ Display the applicable tax rate for each


(jmployee in department 30.
SQL> SELECT ename , sal, 2 DECODE (TRUNC (sal/1000, 0 ) ,
3 4 5 6 7 8 9

0, 1, 2, 3, 4, 5, 6,

0.00, 0.09, 0.20, 0.30, 0.40, 0.42, 0.44,

10 1 1 FROM 12 WHERE

0 . 4 5 ) TAX RATE emp deptno = 30;

MI

Copyright

Oracle Corporation. 1999 All nghts reserved

OR? A.CTILE '

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%

1250 1600 1500

.09 .09 .09

Introduction to Oracle: SQL and PL/SQL 3-41

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

| Step 1 = Result 1 fi Step 2 = Result 2 Step 3 = Result 3


Copyright f Oracle Corporation. 1999. All rights reserved

;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

Introduccin to Oracle: SQL and PL/SQL 3-42

Nesting Functions

SQL> SELECT 2 3 FROM 4 WHERE

ename, NVL(TO_CHAR(mgr),'No Manager') emp mgr IS NULL;

ENAME KING

NVL(TO_CHAR(MGR),'NOMANAGER') No Manager

Copyright Oracle Corporation. 1999 All nghts reserved

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

Introduction to Oracle: SQL and PL/SQL 3-43

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

Copyright; Oracle Corporation, 1999. All ngtts reserved

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.

Introduction to Oracle: SQL and PL/SQL 3-44

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.

Introduction to Oracle: SQL and PL/SQL 3-45

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

750 428 368 446 138 240 225 143

Introduction to Oracle: SQL and PL/SQL 3-46

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

Introduction to Oracle: SQL and PL/SQL 3-47

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.

Introduction to Oracle: SQL and PL/SQL 3-48

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

Introduction to Oracle: SQL and PL/SQL 3-49

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.

Introduction to Oracle: SQL and PL/SQL 3-50

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

CLEPK SALESMAN SALESMAH MANAGER SALESMAN MANAGEP MAIIAGEP. ANALYST

E D D B D B B C

PRESIDENT A SALESMAN CLEPK CLERK ANALYST CLERK D E E C E

Introduction to Oracle: SQL and PL/SQL 3-51

You might also like