Sei sulla pagina 1di 12

6.

ARITHMETIC AND DATE FUNCTIONS


What is a function? Types of functions Arithmetic functions Dual table Date arithmetic Date functions Summary Exercises

What is a function?
A function is similar to an operator in operation. A function is a name that performs a specific task. A function may or may not take values (arguments but it al!ays returns a value as the result. "f function takes values then these values are to be given !ithin parentheses after the function name. The follo!ing is the general format of a function.

function [(argument-1, argument-2,...) ]


"f the function #oesn$t take any value then function name can be use# alone an# even parentheses are not re%uire#.

Types of functions
&unctions are classifie# base# on the type of #ata on !hich they perform the operation. The follo!ing are the #ifferent types of functions available in 'racle.

Arithmetic &unctions. Date ( Time functions. String functions. )onversion functions. *iscellaneous functions. +roup functions.

Arithmetic functions perform take numeric #ata, #ate functions take #ate type #ata an# string functions take strings. )onversion functions are use# to convert the given value from one type to another. *iscellaneous functions perform operations on any type of #ata. +roup functions are use# to perform operations on the groups create# by +-'./ 01 clause.

Note: Group functions or aggregate functions perform their operation on a group (a collection of rows). All the remaining functions are called as s ingle2ro! functions as they return a result for each row.

Arithmetic Functions
Arithmetic functions take numbers an# perform arithmetic operations. Table 3 lists the arithmetic functions available in 'racle. Function ABS(value) CEIL(value) FLOOR(value) MOD(value,divisor) POWER(value,e ponent) RO!"D(value#,precision$) %R!"C(value#,precision$) S&R%(value) SI'"(value) Description Absolute value of the given value. Smallest integer larger than or e%ual to value 4argest integer smaller than or e%ual to value -emain#er of the #ivision bet!een the value an# #ivisor. 5alue is raise# to exponent. -oun#s value to precision. /recision can be negative if roun#ing is to be #one on the left of the #ecimal point. Truncates instea# of roun#ing. 'ther!ise same as -'.6D. S%uare root of value. -eturns 3 if value 7 89 23 if value :89 8 if value ; 8 %a(le)*+ Arithmetic &unctions.

The follo!ing are a fe! examples of arithmetic functions. select mod(10,4) from dual; The above comman# #isplays < as the result as the remain#er of the #ivision bet!een 38 an# = is <.

ROUND and TRUNC functions


-'.6D an# T-.6) functions are use# to roun# an# truncate the given number to the given number of #igits (either on the right or left of the #ecimal point . -'.6D takes the leftmost #igit that is being lost an# accor#ingly a##s one to the rightmost #igit. T-.6) #oesn$t take the leftmost #igit into account. "t >ust truncates the given number to the given precision. select round(1047.785,2), trunc(1047.785,2) from dual; The above comman# !ill #isplay 38=?.?@ an# 38=?.?A. take the #igits being lost into account. This is because T-.6) #oesn$t

The follo!ing examples illustrate the result of -'.6D an# T-.6) functions !ith positive an# negative precision.

Function -'.6D(3<@B.CBD9< T-.6)(3<@B.CBD9< -'.6D(3<@B.CBD98 -'.6D(3<AB.CBD9 23 T-.6)(3<AB.CBD9 23 -'.6D(3<@B92<

Result 3<@B.CD 3<@B.CB 3<@B 3<@8 3<A8 3C88

When precision in -'.6D is positive then roun#ing takes place to the specifie# number of #igits on the right of #ecimal point. &or example9 if precision is < it means roun# number to < #igits on the right of the #ecimal point. When precision is negative, it means number is to be roun#e# to the left of the #ecimal point. "n both the cases if the leftmost #igit of

the #igits being lost is 7; B then one is a##e# to the rightmost #igit of the #igits that are retaine#. "n the example given above9 -'.6D (3<AB.CBD9 23 !ill result in 3<@8. 0ecause one #igit on the left of #ecimal point is to be set to Eero9 means B is replace# !ith 8. As the #igit that is replace# !ith Eero (B in this case is 7; B one is a##e# to #igit on the left of it (A to make it @. So the result is 3<@8. -'.6D (3<@B92< results in 3C88. This is because in 3<@B t!o #igits on the left of #ecimal point are set to Eeroes( 3<88 an# as leftmost #igit out of #igits that are set to Eero is @ one is a##e# to <9 !hich is the rightmost #igit in the remaining portion. This makes it 3C88. Note: ROUND and RUN! functions can also "e used with date data type. #ore on this later in this chapter.

CEIL FLOOR functions CEIL produces the smallest integer that is greater than or equal to the given value. Whereas FLOOR is opposite of CEIL. The following ta le illustrates the usage of these two related functions.
Function )E"4(3.C )E"4(< )E"4(2<.C &4''-(3.C &4''-(< &4''-(2<.C Result < < 2< 3 < 2C

DUAL Table
This is a ta le that is made availa le to ever! account in Oracle data ase. This ta le contains one row and one column. This ta le can e used with "ELECT when result of the e#pression is to e displa!ed onl! for once.
!"# descri$e dual %ame %ull& '()e ------------------------- -------- ---*+,,./012/02(1)

For e#ample$ to displa! the current s!stem date the following "ELECT can e used%
!"# select s(sdate from dual; - */'3 -------24-/+4-01

&s '(&L ta le contains onl! one row$ the result is displa!ed onl! for once.
The follo!ing example #isplays the course fee by roun#ing it to thousan#s.

select ccode,name, round(fee,-5) 6fee7 from courses; 118*3 ----ora 9$net c as) =a9a ?ml %/,3 fee ------------------------------ --------8racle data$ase 5000 .:.%3' ;000 1 )rogramming 4000 / <.%3' 5000 >a9a "anguage 5000 @," <rogramming 4000

!cientific functions
The follo!ing are the other arithmetic functions that are rarely use# in business applications. They are mainly use# in scientific applications. Fo!ever as they are available in 'racle9 !e !ill get to kno! them.

Function ACOS(value) ASI"(value) A%A"(value) COS(value) COS,(value) E-P(value) L"(value) LO'((ase,value) SI"(value)) SI",(value) %A"(value) %A",(value)

Description Arc cosine of the given $alue. The value is in the range G3 to 3 an# return value is in ra#ians. Arc sine of the $alue. Arc tangent of the $alue. )osine of the $alue. Fyperbolic cosine of the $alue. -eturn e (<.?3A<A3AC raise# to $alue po!er. 6atural logarithm of $alue. 4ogarithm !ith "ase of $alue. Sine of the $alue. Fyperbolic sine of the $alue. Tangent of the $alue. Fyperbolic tangent of the $alue. %a(le).+ Scientific &unctions.

The follo!ing are fe! examples of these scientific functions. select e?)(2) from dual; 3@<(2) --------7.58A05;1 select log(10,10) from dual "84(10,10) ---------1 3"31' 18 (180 B 5.1415A2;555AC180) from dual 18 (180B5.1415A2;555AC180) --------------------------1

Date Arithmetic
When arithmetic operators are use# !ith DATE #atatype it is calle# as Date Arithmetic. The follo!ing are the possible arithmetic operations on DATE type #ata.

A##ing a number to #ate to get the #ate after the given number of #ays. Subtracting a number from a #ate to get the #ate before the given number of Subtracting t!o #ates to get the number of #ays bet!een these t!o #ates.

#ays.

The follo!ing example #isplays the name of the stu#ent an# number of #ays bet!een system #ate an# #ate of >oining. select name, sysdate - dj from students; %/,3 -----------------------------4eorge ,icDeal ,icDeal *ouglas /nd( 0o$erts ,alcom ,arsDall .i9an 0icDards 1Dirs 39ert E9an "endal 4eorge ,icDeal 0icDard ,ar? 'ina 'urner >od( Foster %o *a(s --------22;.2A1A4 225.2A1A4 225.2A1A4 220.2A1A4 220.2A1A4 222.2A1A4 221.2A1A4 17;.2A1A4 140.2A1A4 140.2A1A4 15A.2A1A4

"n 'racle DATE #atatype stores #ate an# time. At the time of storing a #ate "f time is not given then it !ill be set to 8 hours9 8 minutes an# 8 secon#s (beginning of the #ay or 3<H88 a.m. . Default #ate format G DD2*'6211 G #oesn$t inclu#e time. Fo!ever time is al!ays store# along !ith #ate an# if you !ant to at any time you can extract the time portion a #ate using T'I)FA- function9 !hich !ill be #iscusse# in the next chapter. Note: All comparisons "etween two dates include time portion also. Note: he fraction portion in the result "etween two dates indicates the difference in time. The follo!ing example sho!s the #ue #ate for first installment (assuming first installment is to be pai# !ithin 38 #ays from the #ate of >oining . select name,d=, dj + 10 G*ue *ateG from students %/,3 -----------------------------4eorge ,icDeal ,icDeal *ouglas /nd( 0o$erts ,alcom ,arsDall .i9an 0icDards 1Dirs 39ert E9an "endal 4eorge ,icDeal 0icDard ,ar? 'ina 'urner >od( Foster *> --------10->/%-01 11->/%-01 11->/%-01 1;->/%-01 1;->/%-01 14->/%-01 15->/%-01 01-,/0-01 0;-/<0-01 0;-/<0-01 07-/<0-01 *ue *ate --------20->/%-01 21->/%-01 21->/%-01 2;->/%-01 2;->/%-01 24->/%-01 25->/%-01 11-,/0-01 1;-/<0-01 1;-/<0-01 17-/<0-01

The follo!ing %uery #isplays the #etails of the payment that !ere ma#e in the last C #aysH select B from )a(ments HDere sysdate dp <= 3;

Date Functions
Date functions operate on values of DATE #atatype. Except *'6TFSI0ETWEE6 all #ate functions return DATE #ata type. The follo!ing is the list of DATE functions.

Function ADDI*'6TFS(#ate9 count *'6TFSI0ETWEE6 (#ate39 #ate< 4ASTIDA1(#ate 6EJTIDA1(#ate9 $#ay$ 6EWIT"*E(#ate9 $this$9 $other$ -'.6D(#ate T-.6)(#ate

Description A##s count number of months to date. -eturns number of months bet!een date% an# date&. -eturns the last #ay of the month in !hich date is. +ives the #ate of next day after the #ate9 !here day name of the !eek like K*on#ay$. -eturns time in other time Eone for time of this time Eone. -oun#s the #ate #epen#ing upon the time. "f time is at or after 3< hours then #ate is incremente#. Time is al!ays set to beginning of the #ay (8H8H8 . Same as -'.6D (#ate but #oesn$t increment #ate.

%a(le)/H DATE &unctions.

Addin" and su#tractin" months )ou can add or su tract months from a date using &''*+O,T-" function. If the count is positive$ that man! months will e added. If count is negative that man! months will e su tracted. &dding months is the process where Oracle will give the date of ne#t specified num er of months. In the following e#ample$ Oracle will add two months to s!stem date%
!"# elect s(sdate, addImontDs(s(sdate,2) 2 From dual; - */'3 /**I,8%'2 --------- --------25-/+4-01 25-81'-01

If the target month doesn.t have the required da! then the last da! of the month will e ta/en. In the following e#ample$ 012"E324115 is returned$ as 052"E3 is not availa le. Oracle automaticall! ad6usts the date according to the requirement.
!"# select addImontDs(J51-aug-2001J,1) from dual;

/**I,8%'2 --------50- 3<-01

The following e#ample will show the date on which the students of completed atches will e issued certificates assuming it will ta/e 0 months time to issue certificates.
!"# select $code, ccode, enddate, addImontDs(enddate,5) G1ert. *ateG 2 from $atcDes 5 KDere enddate is not null;

:18*3 ----$1 $2 $5 $4 $5

118*3 ----ora as) c ?ml =a9a

3%**/'3 --------20-F3:-01 05-,/0-01 27-F3:-01 50-,/0-01 10-,/--01

1ert. *at --------20-,/--01 05->+%-01 27-,/--01 50->+%-01 10-/+4-01

When the second parameter 7 count - is negative$ date is decremented ! that man! months.
'De folloKing e?am)le sDoKs tDe date on KDicD tDe admissions for running $atcDes Da9e started. For a $atcD admissions start e?actl( one montD $efore tDe starting date. select $code, ccode, stdate, addImontDs(stdate,-1) from $atcDes KDere enddate is null :18*3 ----$; $7 118*3 '*/'3 /**I,8%'2 ----- --------- --------9$net 12->+"-01 12->+%-01 ora 15-/+4-01 15->+"-01

$ettin" months #et%een t%o dates


1ou can obtain the number of months bet!een t!o #ates using *'6TFSI0ETWEE6 function. The follo!ing %uery returns the number of months bet!een starting #ate an# en#ing #ate of all complete# batches.

select $code, ccode, stdate, enddate, montDsI$etKeen(enddate, stdate) G%8. ,ontDsG from $atcDes KDere enddate is not null; :18*3 ----$1 $2 $5 $4 $5 118*3 ----ora as) c ?ml =a9a '*/'3 --------12->/%-01 15->/%-01 20->/%-01 02-,/0-01 05-/<0-01 3%**/'3 %8. ,ontDs --------- ---------20-F3:-01 1.2580;45 05-,/0-01 1.;7741A4 27-F3:-01 1.22580;5 50-,/0-01 .A0522581 10-,/--01 1.1;12A05

The fraction in the result is the number of #ays beyon# the number of months. &or example9 the #ifference bet!een 3<2LA6283 an# <82&E0283 is 3.<BA. "t means there is one month an# <DM of another month9 !hich comes to A #ays. Note: he fraction is calculated "ased on a '%(day month and also considers time portion. .se T-.6) function to ignore fraction in the result of *'6TFSI0ETWEE6 as follo!sH select $code, ccode, stdate, enddate, trunc(montDsI$etKeen( enddate, stdate)) G%8. ,ontDsG from $atcDes KDere enddate is not null; :18*3 ----$1 $2 $5 $4 118*3 ----ora as) c ?ml '*/'3 --------12->/%-01 15->/%-01 20->/%-01 02-,/0-01 3%**/'3 %8. ,ontDs --------- ---------20-F3:-01 1 05-,/0-01 1 27-F3:-01 1 50-,/0-01 0

$5

=a9a

05-/<0-01 10-,/--01

Note: )t is possi"le to send the return $alue of a function to another function. The follo!ing %uery #isplays the batches that !e complete# in the last D months an# #uration is more that 3 month. select $code, ccode from $atcDes KDere montDsI$etKeen(s(sdate,enddate) LM ; and montDsI$etKeen(enddate,stdate) # 1; :18*3 ----$2 $5 $5 118*3 ----as) c =a9a

LA!T&DA' function
4ASTIDA1 function returns the #ate of the last #ay of the month of the given #ate. The follo!ing statement #isplays the last #ay of the current monthH elect s(sdate, lastIda((s(sdate) From dual; - */'3 "/ 'I*/-( --------- --------25-/+4-01 51-/+4-01 The follo!ing %uery #isplays the #ue #ate by !hich first installment of each batch is to be pai#. 4ASTIDA1 function return the last #ay of the month in !hich batch has starte# an# if B is a##e# to that then it !ill be Bth of the next month G #ue #ate of first installment. select $code,ccode, stdate, lastIda((stdate) N 5 G*ue *ateG from $atcDes :18*3 ----$1 $2 $5 $4 $5 $; $7 118*3 ----ora as) c ?ml =a9a 9$net ora '*/'3 --------12->/%-01 15->/%-01 20->/%-01 02-,/0-01 05-/<0-01 12->+"-01 15-/+4-01 *ue *ate --------05-F3:-01 05-F3:-01 05-F3:-01 05-/<0-01 05-,/--01 05-/+4-01 05- 3<-01

"imilarl! assuming the atches are scheduled in the last wee/ of previous month for each atch$ the following quer! displa!s the date of last wee/%
select $code, ccode, stdate, lastIda((addImontDs(stdate,-1)) - 7 OO J to J OO lastIda((addImontDs(stdate), -1) from $atcDes :18*3 ----$1 $2 $5 $4 $5 $; 118*3 ----ora as) c ?ml =a9a 9$net '*/'3 --------12->/%-01 15->/%-01 20->/%-01 02-,/0-01 05-/<0-01 12->+"-01 cDd. HeeP ---------------------24-*31-00 to 51-*31-00 24-*31-00 to 51-*31-00 24-*31-00 to 51-*31-00 21-F3:-01 to 28-F3:-01 24-,/0-01 to 51-,/0-01 25->+%-01 to 50->+%-01

$7

ora

15-/+4-01 24->+"-01 to 51->+"-01

NEXT_DAY function
This function returns the date of given wee/da! that is greater than the given date. It ta/es wee/da! 7 "unda!$ +onda! etc. 7 and returns the date on which the coming wee/da! is falling. The return value is alwa!s grater than the given date. The following e#ample shows when is the ne#t Frida!.
select s(sdate, ne?tIda((s(sdate,JFriJ) from dual;

- */'3 %3@'I*/-( --------- --------25-/+4-01 51-/+4-01

If wee/da! of the given date and the given wee/da! happen to e the same then the date of coming wee/da! is returned. This is ecause the result of this function is alwa!s greater than the given date. "ee the following e#ample where though the given date 2 482&(9 2 is "aturda! ,E:T*'&) returns the ne#t "aturda! and not the same date.
select s(sdate, ne?tIda((s(sdate,J atJ) from dual

- */'3 %3@'I*/-( --------- --------25-/+4-01 01- 3<-01

;ut what if !ou want to get the same date$ when da! of the wee/ of the given date is same as the one as/ed for< The following quer! will return the same date if date happens to fall on the required wee/da!.
select s(sdate, ne?tIda((s(sdate - 1,J atJ) from dual

- */'3 %3@'I*/-( --------- --------25-/+4-01 25-/+4-01 When one is subtracte# from the system #ate9 though the #ate happens to be on Satur#ay it become &ri#ay (<=2A.+ because of the subtraction. Then 6EJTIDA1 returns the <B2 A.+ as it is grater than the given #ate G <=2A.+.

ROUND

TRUNC functions %ith dates

DATE #ata type contains both #ate an# time. -'.6D an# T-.6) function can be use# to roun# or truncate the #ate base# on the time portion. The follo!ing %uery #isplays the #ate an# time portion of system #ate using T'I)FA- function. "t is suffice to kno! that T'I)FA- can be use# to convert given #ate to character type using the given format.

elect toIcDar(s(sdate,Jdd-mm-(((( DD24QmiQssJ) from dual '8I12/0( - */'3,J** ------------------25-08-2001 18Q42Q08

Note: O*!+AR con$erts a DA , type data to character type. -lease see ne.t chapter for more information on O*!+AR.

-'.6D function a##s one #ay to the #ate if time portion of the #ate is greater than or e%ual to 3< noon. select s(sdate, toIcDar(round(s(sdate),Jdd-mm-(((( DD24QmiQssJ) 60ound *ateG from dual - */'3 0ound *ate --------- ------------------25-/+4-01 2;-08-2001 00Q00Q00 "n the above %uery first -'.6D function is use# to roun# S1SDATE. As !e have seen the time in S1SDATE is 3A hours9 the #ate is incremente# by one G <D2A.+. -'.6D al!ays sets the time portion to 8H8H8 (as seen in the output of the %uery .

TR(,C function doesn.t increment the date ased on the time$ ut it sets time portion to 1 hours$ 1 minutes and 1 seconds. The following quer! shows the result of TR(,C function.
select toIcDar(s(sdate,Jdd-mm-(((( DD24QmiQssJ) G'oda(G, toIcDar( trunc(s(sdate),Jdd-mm-(((( DD24QmiQssJ) G'runcated *ateG from dual 'oda( 'runcated *ate ------------------- ------------------25-08-2001 18Q5;Q55 25-08-2001 00Q00Q00

Note: /oth ROUND and RUN! set the time portion in the DA , data type to %& A.#. (00:00:00). The follo!ing %uery is use# to #isplays the #etails of the payments ma#e to#ay. select B from )a(ments KDere d) M s(sdate; The above %uery al!ays returns no rows selected. This is because !hen 'racle compares t!o #ates it takes #ate an# time portions into account. "n the above %uery9 though /A1*E6TS table contains ro!s !here D/ is containing the same #ate as S1SDATE9 the time portions !ill not match. The reme#y is to ignore time portions an# compare only #ate portions of the #ates. The follo!ing is revise# %uery !here !e truncate the #ates to set both the times to 8H8H8 so that only #ates are compare# as times are e%ual. select B from )a(ments KDere trunc(d)) M trunc(s(sdate); The follo!ing is another example !here T-.6) is use# to ignore time portion of D/ an# compare #ate !ith 382apr2<883. select B from )a(ments KDere trunc(d)) M J10-a)r-2001J 08""%8 --------10 11 *< /,8+%' --------- --------10-/<0-01 4500 10-/<0-01 5500

10

$ettin" time in different time (one ,EW*TI+E is used to return the time of the specified time =one for the time of the given time =one. The following quer! displa!s what will e the time in 3"T for the time in 9+T.
select toIcDar(s(sdate,Jdd-mm-(((( DD24QmiQssJ) 4,' , toIcDar( neKItime(s(sdate,J4,'J,J/ 'J),Jdd-mm-(((( DD24QmiQssJ) / ' from dual '8I12/0( - */'3,J** '8I12/0(%3HI'E,3( ------------------- ------------------25-08-2001 1AQ55Q5; 25-08-2001 15Q55Q5; The follo!ing are a fe! of the available time Eones. &or complete lit9 please see 'racle online #ocumentation.

%i0e)1one ES%),)ED%)) 'M%)) ,S%),),D%)) PS%),)PD%)) AS%),)AD%))

Meanin2 Eastern Stan#ar# or Daylight Time +reen!ich *ean Time Alaska2Fa!aii Stan#ar# Time or Daylight Time. /acific Stan#ar# or Daylight Time Atlantic Stan#ar# or Daylight Time

Summary
A function is to perform a single operation an# return a value. &unctions are of #ifferent types. Arithmetic functions are use# to perform arithmetic operations. Date functions perform operations on #ate type #ata. /erforming arithmetic operations on #ates is calle# as date arithmetic. D.A4 table is !ith SE4E)T comman# to #isplay the result of expression that #o not relate to any table.

E)ercises
3. <. C. =. B. D. ?. A. IIIIII function can be use# to subtract months from a #ate. The return value of -'.6D (<C<C.C=C9< is IIIIIIIII. To get the remain#er of a #ivisionIIIII function is use#. "n Date Arithmetic IIIIIIIIII9 IIIIIIIIIIIIIII an# IIIIIIIIIII operations are allo!e#. IIIIIIIIIIII is the result of 4ASTIDA1(S1SDATE assuming S1SDATE is <= th August. Which function can be use# to set time portion of the DATE #ata type to !ithout affecting #ate portion.? IIIIIIIII Display #etails of stu#ents !ho have >oine# in the last = months. Display -'446'9 6A*E9 DL an# number of #ays bet!een current #ate an# DL for each stu#ent. 88H88H889

11

@.

Display the first Sun#ay since batch !ith co#e < starte#.

38. Display #etails of batches that starte# three or more months back. 33. Display the #etails of payments of last *on#ay. 3<. IIIIIIIIII is the function to get number of years bet!een t!o #ates.

12

Potrebbero piacerti anche