You are on page 1of 10

lOMoARcPSD

Lecture notes, lectures 5 - Advanced SQL DML part 2

Data Management (Monash University)

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

Lecture5FIT1004:AdvancedSQL(DML2)
SQLFunctions
manipulatedatabydecomposingthedataelements
numerical/date/stringvalues
categorisedaccordingtooperandtypes(aquantityonwhichaoperationis
performed/input)

FunctionType

ApplicableTodatatype

Arithmetic

numerical

Text

alphanumeric

Date

date/timerelated

General

any

Conversion

datatypeconversion

Group

setofvalues

Examples:
Arithmetic
round(n,m)roundntomdecimalplaces
SELECTround(1.4212,2)FROMdual
SELECTROUND(column_name,decimals)FROMtable_name
Text
upper(char)makesstringuppercase
SELECTupper(empname)FROMemployee
SELECTUPPER(column_name)FROMtable_name
Date
last_daydateoflastdayofcurrentmonth(SYSDATE)
SELECTlast_day(SYSDATE)FROMdual
SELECTLAT_DAY(date)FROMtablename
TheOracle/PLSQLLAST_DAYfunctionreturnsthelastdayofthemonthbased
onadatevalue,LAST_DAY(date)

General
SELECTNVL(empcomm,0)FROMemployee
SELECTNVL(item,ifNull)FROMtablename
TheOracle/PLSQLNVLfunctionletsyousubstituteavaluewhenanullvalueis
encountered.NVL(x,replace_with)ifxisNULL,replacewithreplace_with,
otherwisex.Helpfulwhenperformingarithmeticonattributes

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

Conversion
SELECTTO_CHAR(empsal,$099.99)FROMemployee
to_charconcertsanydatatypetocharacterdata

NOTE:DualIt'sasortofdummytablewithasinglerecordusedforselectingwhenyou'renot
actuallyinterestedinthedata,butinsteadwanttheresultsofsomesystemfunctioninaselect
statement.

DatesinOracle
storeddifferentlytoSQLstandard(dateandtime),
Oracleusesonly
date
storedininternalformatcontainsdate&time
outputcontrolledviaformating
SELECTTO_CHAR(SYSDATE,ddMONyyyy)FROMDUAL
10Apr2015,note:MON(APR)/Mon(Apr)
SELECTTO_CHAR(SYSDATE,ddMONyyyyhh:mi:ssPM)fromdual
10Apr201510:56:50AM
Oracle10GintroducedTIMESTAMPdatatypefinergranularityonseci.e.10APR15
10.27.10.0000000000AM

DATAdatatypeshouldbeformattedwith:
TO_CHARwhenselectingfordisplay
TO_DATEwhencomparing,inserting,updating
Ifdontformat,systemhastodoitforus,itmayormaynotbesmartenoughtodoso

note:comparingto_charadate01feb1992
looksat0,then1thenfebetcsoifdate>01feb1992
02willpass
01nwillpass
01awillfail

Example:

SELECTempno,empname,TO_CHAR(empdate,ddMonyyyy)
FROMpayroll.employee
WHEREempdate>TO_DATE(01Feb1962,ddMonyyyy)

ORDERBYempdate

NOTE:FROMowner/database.table#specifieswhereitisfromfuther
#getsemployeesbornafter,thusyounger>andDOBlaterthan1Feb1962

AlphabeticallyFebcomesbeforeJan
ChronologicallyJancomesbeforeFeb
SowhencomparingweratheruseTO_DATEtocomparechronologically

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

ifWHERETO_CHAR(empbdate,ddMonyyyy)>01Feb1962
01Apr1962<01Feb1962<JuneviaTO_CHAR

OracleGroupFunctions:
usedtoperformmathematicalsummaries
allgroupfunctionsonlyapplytosetsofvaluesandreturnasinglevalue
ignoresNULLvalues,exceptCOUNT(*)

COUNT
SELECTCOUNT(*)
#returnsnumberofrowsintable
Fromtable

SELECTCOUNT(col)
#returnsnumberofnonnullrows
FROMtable

MAX&MINcanbeusedforanydatatype
SELECTMIN(col),MAX(col) #canuseMAX/MINbyitself
FROMtable
#returnsmaxvalue/minvalue

SUM&AVGonlyfornumericdata
SELECTSUM(col)/AVG(col)
#canuseSUM/AVGbyitself
FROMtable
#returnsmaxtotal/avgvalue

NVLforcesgroupfunctionstoincludenullvaluesusingassignedvalue(i.e.0)
SELECTFUNCTION(NVL(col,0))
FROMtable
NVL(x,y)ifxisNULL=y,otherwise=x(ycanbeanyvalue)
GroupBydoesntneedaWHERE
GroupByClause

aggregate(rows)recordsbythespecifiedcolumnsi.e.noduplicates
Usedtodividerowsintogroupsi.e.groupbydepartmenteachdepartmentis
consideredagroup
aggregate(grouping)functionsreturnsummaryinformationforeachgroupi.e.sum
employeegroupbydepartment
attributes(cols)inSELECTlist/statementnotingroupfuns(i.e.MAX)
must
beinthe
GROUPBYclause#orderdoesntmatter
canputotherattributes(cols)notinSELECTinGROUPBY
canputGROUPBYafterFROM

SELECTdeptno,COUNT,MAX(col)...
FROMtable
GROUPBYdeptno
#groupsallrowsintodepts,
orderdoesntmatter
ORDERBYdeptno
#sortsdept,
ordermatters

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

cantuseWHEREtorestrictgroupsi.e.WHEREempsal>avg(empsal)won'twork

SELECTcol,groupfun
#needsa
GROUPBYcol
#asthereisagroupbyfn,needsthegroupbyclause

HAVINGClause
appliedtooutputofGROUPBytorestrictrows
likeaWHEREclausehowever:
WHERE:colsandrowrestrictions
HAVING:outputofGROUPBYrestrictions

Evaluatedinthisorder:
WHERE
applyrestrictionsaspernormal
GROUPBY
HAVING(restrictsGROUPBY)applyrestrictionstogroupfunctions

usingHAVINGtorestrictgroups
rowsgroups
groupfunctionapplied
groupsmatchingHAVINGdisplayed

SELECTdeptno,max(empsal)
FROMemployee
GROUPBYdeptno
HAVINGmax(empsal)>2900
#getsusdeptswheremaxemployeesalary>2900

SELECTempjob,SUM(empsal)ASPAYROLL
#selects2cols
FROMemployee
#fromtable
WHEREempjobNOTLIKESALES%
#whereempjob!=SALES.
HAVINGSUM(empmsal)>5000
#whensumempsal>5000
ORDERBYSUM(empmsal)
#orderbyempmsal

NestingFunctions
cannestaggregate(group)functions

SELECTmax(avg(empmsal))
FROMemployee
GROUPBYdeptno

findsgreatestaveragesalaryofdepartments
i.e.ITsal5000onaverage,Marketingsal4000onaverage,displaysIT

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

Subqueries
canusethistorestrictgroupfns
queryinaqueryembedded/nested/inner
subqueryexecutedfirstresultreturnedtomainquery
1stqueryouterquery
queryinsideinnerqueryevaluatedfirstthenoutputusedinouterquery(use
brackets)

WhichemployeehasgreatermonthlysalarythanBlake?
SELECTempno,empname,empmsal
FROMemployee
WHEREempsal>(SELECTempsal
FROMemployee
Whereempname=BLAKE)
#assume1personcalledblakecanusethisintests

Subqueries:
enclosedin()parentheses
ontherightofcomparison(WHEREcondition(subquery))
dontuseORDERBYclauseonsubquery
singlerowoperatorswithsinglerowsubqueries(selectcol,from,wherecol=?)
multiplerowoperatorswithmultiplerowsubqueries(selectmax(col),from,groupby)

TypesofSubqueries
Singlerowsubquery(asinglevalue)
i.e.returnsCLERK(jobtype(attribute)foraparticularcondition)
usecomparisonoperators(=,>=,<>etc)
Multiplerowsubquery(alistofvalues,manyrows,onecolumn)
i.e.returnsCLEARK,MANAGER(>1rowforaattribute/col)
Multiplecolumnsubquery(virtualtablemanyrows,manycolumns)
CLEARK,MANAGER7900,7698(>1rowfor>1attributes)

Examples:

SingleRowSubqueries
Whichdepartmenthasthemostemployees?
SELECTd.deptno,d.deptname,count(*)
FROMdepartmentd,employeee
WHEREd.deptno=e.deptno
HAVINGcount(*)=(SELECTMAX(COUNT(*))
FROMemployee
GROUPBYdeptno)
GROUPBYd.depto,d.deptname

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

subqureyfindscountfindsmaxcountreturnsthatmeetshavingclausedisplays
thatmaxcountvalue

Whatiswrongwiththisstatement?

SELECTempno,empname
FROMemployee
WHEREempmsal=(SELECTMIN(empmsal)
FROMemployee
GROUPBYdeptno)

groupedbydeptnoreturnsminemployeesalaryperdept(dept1minsal,dept2minsal.)
morethan1line..thisisasinglerowsubquerysoitwontwork

MultipleRowSubqueries
returnmorethanoneroworreturnsalist
samecol:
value1,
value2..etc
usemultiplerowcomparisonoperatorstocomparesinglevaluewithalistofvalues
IN,=toanymemberinthelist
ANY,<or>anyvalueinthelist
ALL,<or>allvaluesinthelist

WHEREempmsal>ALL(SELECTAVG(empsal)FROMemployeeGROUPBYdeptno)
returnsalistofavgsalariesforeachdepti.e.4depts=4avgsals
compareswhenempmsal>thanallvaluesorsameas>max(avg(sal))

MultipleColumnSubqueries
numbercolsinmainquery=numercolsreturnedininnerquery

SELECTempno,empname,deptno,empjob
FROMemployee

~WHEREempname<>Martin
AND~(deptno,empjob)=(SELECTdeptno,empjob
FROMemployee
WHEREempname=Martin)

RelationalSetOperators
DMLsetorientatedoperateoverentiresetsofrowsandcolumnsatonce

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

setoperatorscancombine2ormoresetstocreatenewsets(relations)
unionallrowsineitherquery(allincludesduplicates)
intersectalldistinctrowsinbothqueries
minusalldistinctrowsselectedbyfirstquerybutnotsecond
SAMENUMBEROFCOLS&SAMEDATATYPESunioncompatibility
=precedence,ifcontainsmultiple()thenLR
mustmatchdatatypes(useTO_CHAR,TO_DATE,TO_NUMBER)whendatatypesdontmatch

query
union(all)/intersetc(bioth)/minus(ab)
query

DisplaysemployeesthatworkinthesamedepandhavethesamejobasMartin,note:thisalso
includesMartin
modifytodiscludemartin~
note:WHEREconditionANDcondition

SELECT'Manager',empno,empname,empjob,mgrno
FROMemployee
WHEREempnoIN(SELECTmgrnoFROMemployee)
#tophalfgivemanagers
UNION
SELECT'Employee',empno,empname,empjob,mgrno #bottomhalfgivesemployee
FROMemployee
WHEREempnoNOTIN(SELECTdistinctnvl(mgrno,0)FROMemployee)ORDERBYmgrno

splitspeopleintoeithermanageroremployee

givesallemplyoeesmanagers
SELECTempno,empname,empjob,mgrno
FROMemployee
#allemployees
MINUS
#
SELECTempno,empname,empjob,mgrno
#mgrno=empnomanagers
FROMemployee
WHEREempnoIN(SELECTmgrnoFROMemployee)

Manipulatingdata
6basicSQLdmlcommands
INSERT
SELECT
COMMITpermanentlysavework
UPDATE
ROLLBACKgobacktolastcommit

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

DELETE

INSERT
INSERTINTOtable
VALUES(value,value,.)/subquery
ifnocolsspecifieditwillinsertintodefaultLRsetupofdatabase
caninsertNULL/defaultsifspecified
storeTO_DATE(01012001,ddMONyyyy)
OBrienquotationmarkissue
iftrytoinsertavaluethatdoesntexisti.e.dept60doesnotexistreferentialintegrity,
canrefersomethingthatdoesntexist

canusesubqueries
don'tusevaluesifusesubquereies
i.e.INSERTINTOtable
(subquery)

INSERTINTOtable(col1,col2)
(SELECTcol1,col2
FROMtable
WHEREcondition)subquery,colsneedto=

UPDATE
UPDATEtable
SETcol=value[addmorecol=valueifneeded]
WHEREcondition[ifnowhere,appliedtoallrows]

canusesubqueriestoupdaterowsinatablebasedonvaluesfromanothertable

UPDATEtable
SET col=(subquery)i.e.SELECTempjobFROMemployeeWHEREempname=j
#takejsjobtype
WHEREcondition#updatethisguy

DELETE
DELETEFROMtable
WHEREcondition#nowhereeverythingisdeleted
#cantdeletethingsthatarePK/FK
canuseSubqueries
DELETEFROMtable
WHEREcondition=subquery

DELETEFROMemployee

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

lOMoARcPSD

WHEREdeptno=(SELECTdeptno
FROMdepartment
WHEREdeptname='SALES')

note:cantdeletesomethingifitisusedasaforeignkeyneedtodealwithdependenciesfirst

Distributing prohibited | Downloaded by Richard Yang (city_rich@hotmail.com)

You might also like