You are on page 1of 6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

SAPBO,BI,Database&DatawarehouseFAQ| SubscribetoRSSFeed
WhyWeFollowtheWayifWecanLeadthe
SelectTopicsCategory
Way
SelectCategory

DearTechie!!
Welcometobobi.blog.comatechnoworldofBusinessIntelligence.
Throughthisblog,IhavetriedtoinitiateandsharemytechnialskillsinareaofSAPBusiness
Intelligence,SAPVisualIntelligence,BusinessAnalytics,Datawarehouse,Reportingand
databasesolutions.
Iwouldinviteandencourageyoutoreadthepostsandshareyourcommentandexpertiesonthe
topicsmentionedintheblogssothatthisblogcouldturnintotruehelpforthebeginnersandthe
advancelevelpractitionerofSAPBO/BI.
Thanksinadvanceforyourvaluablecontribution!!

~~*~~SQLFAQ~~*~~
FiledunderSAPBOWEBIFAQ,SybaseDatabasebyDeepakChaubeyon2008
2012
1WhatisSQLandwheredoesitcomefrom?
2WhatarethedifferencebetweenDDL,DMLandDCLcommands?
3DifferencebetweenTRUNCATE,DELETEandDROPcommands?
4HowdoesoneescapespecialcharacterswhenwritingSQLqueries?
5Canoneselectarandomcollectionofrowsfromatable?
6Howdoesoneeliminateduplicatesrowsfromatable?
7Howdoesonegetthetimedifferencebetweentwodatecolumns?
8Howdoesoneaddaday/hour/minute/secondtoadatevalue?

Authors
DeepakChaubey

AuthorIntroduction
Iamkeenenoughtolearntechnical
stuffasmuchpossible.Iusemy
leisuretimetosharemyknowledge
inareaofSAPbusinessobject,Business
Inteligence,DatawarehouseandDatabase
conceptswithcontexttodatabses(likeSql
server2005/2008/2012,Oracle
9i/10g/11i,SybaseASE,SybaseIQ,Mysql
5.5).Mypurposeistocreateasuper
BO/BI/Databaseblogwhichcontainsalmost
alltherespectivequestionsrelatedtoSAP
BOBI/BODS/HANAplatformInterviewsin
areaofadministration,developmentand
analysisfrombasictoadvancelevel.Idea
behindthisblogistosaveenoughtimefor
beginneraswellasexperiencedone.Ifyou
haveanyqueryregardinganyofthepostin
thisblog.youcanwritemeon:
sapbobiinfo@gmail.comIoffer&conducts
offline/OnlinetrainingcoursesforSAP
BO/BIandBODScourses.Checkbelowlink
toknowmoreaboutme:
http://about.me/deepakchaubey

Media

9Howdoesonecodeamatrix/crosstab/pivotreportinSQL?
10CanoneretrieveonlyrowsXtoYfromatable?
11CanoneretrieveonlytheNthrowfromatable?
12Howcanonedump/examinetheexactcontentofadatabasecolumn?
13Howdoesoneaddacolumntothemiddleofatable?

Subscribe

14Howdoesonecodeahierarchicaltreestructuredquery?

Getthelatestpostsonyouremail!

15Howdoesonecount/sumdatavaluesinacolumn?

Leaveyouremailaddress

OK

16Howdoesonedrop/renameacolumninatable?
17HowdoesoneimplementIFTHENELSElogicinaSELECTstatement?
18HowdoesonepreventOraclefromusinganIndex?
19HowdoesoneselectEVERYNthrowfromatable?
20HowdoesoneselecttheLASTNrowsfromatable?
21HowdoesoneselecttheTOPNrowsfromatable?
22Howtogenerateatextgraphs(histograms)usingSQL?
23Map/concatenateseveralrowstoacolumn

http://bobi.blog.com/2012/08/20/sqlfaq/

1/6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

24WhatisthedifferencebetweenVARCHAR,VARCHAR2andCHARdatatypes?
AnswerSection
~~~~~~~~~~~~~~~~~~~~~~~~~
WhatisSQLandwheredoesitcomefrom?
StructuredQueryLanguage(SQL)isalanguagethatprovidesaninterfacetorelationaldatabasesystems.Theproper
pronunciationofSQL,andthepreferredpronunciationwithinOracleCorp,issequelandnotesscueell.SQLwas
developedbyIBMinthe1970sforuseinSystemR,andisadefactostandard,aswellasanISOandANSIstandard.
IncommonusageSQLalsoencompassesDML(DataManipulationLanguage),forINSERTs,UPDATEs,DELETEs
andDDL(DataDefinitionLanguage),usedforcreatingandmodifyingtablesandotherdatabasestructures.The
developmentofSQLisgovernedbystandards.AmajorrevisiontotheSQLstandardwascompletedin1992,called
SQL2.SQL3supportobjectextensionsandare(partially?)implementedinOracle8and9i.ExampleSQLstatements:
CREATETABLEtable1(column1NUMBER,column2VARCHAR2(30))INSERTINTOtable1VALUES(1,XYZ)
SELECT*FROMtable1WHEREcolumn2=XYZ
WhatarethedifferencebetweenDDL,DMLandDCLcommands?

Meta
Register
Login
EntriesRSS
CommentsRSS
PoweredbyBlog.com

DDLDataDefinitionLanguage:statementsusedtodefinethedatabasestructureorschema.Someexamples:
CREATEtocreateobjectsinthedatabaseALTERaltersthestructureofthedatabaseDROPdeleteobjectsfrom
thedatabaseTRUNCATEremoveallrecordsfromatable,includingallspacesallocatedfortherecordsare
removedCOMMENTaddcommentstothedatadictionaryRENAMErenameanobject
DMLDataManipulationLanguage:statementsusedformanagingdatawithinschemaobjects.Someexamples:
SELECTretrievedatafromtheadatabaseINSERTinsertdataintoatableUPDATEupdatesexistingdata
withinatableDELETEdeletesallrecordsfromatable,thespacefortherecordsremainMERGEUPSERT
operation(insertorupdate)CALLcallaPL/SQLorJavasubprogramEXPLAINPLANexplainaccesspathtothe
dataLOCKTABLEcontrolsconcurrency

Mostvisited
SearchWithkeyword..LikeSQL
Search

DCLDataControlLanguage.Someexamples:GRANTgivesusersaccessprivilegestodatabaseREVOKE
withdrawaccessprivilegesgivenwiththeGRANTcommandTCLTransactionControl:statementsusedtomanage
thechangesmadebyDMLstatements.Itallowsstatementstobegroupedtogetherintologicaltransactions.COMMIT
saveworkdoneSAVEPOINTidentifyapointinatransactiontowhichyoucanlaterrollbackROLLBACK
restoredatabasetooriginalsincethelastCOMMITSETTRANSACTIONChangetransactionoptionslikeisolation
levelandwhatrollbacksegmenttouseDMLarenotautocommit.i.e.youcanrollbacktheoperations,butDDLare
autocommit

MostRecentPost
10Keyfactsyouneedtoknowbefore
planningaMigrationprojecttoSAP
BOBI4.0project
MasterConceptofSAPBOBI
versions,SupportpacksandFixpacks
&Patchlevel
MasterConceptofAuditDBinBOBI4.0
StepbyStepforestablishingRFC
ConnectionbetweenSAPBW&Data
Service
StepstoUpgradefrom11.7/3.X/4.Xto
SAPDataServices4.2
HowtoVersioncontrolinBODS

DifferencebetweenTRUNCATE,DELETEandDROPcommands?
TheDELETEcommandisusedtoremovesomeorallrowsfromatable.AWHEREclausecanbeusedtoonlyremove
somerows.IfnoWHEREconditionisspecified,allrowswillberemoved.AfterperformingaDELETEoperationyou
needtoCOMMITorROLLBACKthetransactiontomakethechangepermanentortoundoit.Notethatthisoperation
willcauseallDELETEtriggersonthetabletofire.SQL>SELECTCOUNT(*)FROMempCOUNT(*)14
SQL>DELETEFROMempWHEREjob=CLERK4rowsdeleted.SQL>COMMITCommitcomplete.SQL>
SELECTCOUNT(*)FROMempCOUNT(*)10TRUNCATEremovesallrowsfromatable.Theoperation
cannotberolledbackandnotriggerswillbefired.Assuch,TRUNCATEisfasteranddoesntuseasmuchundospace
asaDELETE.SQL>TRUNCATETABLEempTabletruncated.SQL>SELECTCOUNT(*)FROMempCOUNT(*)
0TheDROPcommandremovesatablefromthedatabase.Allthetablesrows,indexesandprivilegeswill
alsoberemoved.NoDMLtriggerswillbefired.Theoperationcannotberolledback.SQL>DROPTABLEempTable
dropped.SQL>SELECT*FROMempSELECT*FROMemp*ERRORatline1:ORA00942:tableorviewdoes
notexistDROPandTRUNCATEareDDLcommands,whereasDELETEisaDMLcommand.ThereforeDELETE
operationscanberolledback(undone),whileDROPandTRUNCATEoperationscannotberolledback.FromOracle
10gatablecanbeundropped.Example:SQL>FLASHBACKTABLEempTOBEFOREDROPFlashback
complete.PS:DELETEwillnotfreeupusedspacewithinatable.ThismeansthatrepeatedDELETEcommandswill
severelyfragmentthetableandquerieswillhavetonavigatethisfreespaceinordertoretrieverows.
HowdoesoneescapespecialcharacterswhenwritingSQLqueries?
EscapequotesUsetwoquotesforeveryonedisplayed.Examples:SQL>SELECTFranksOraclesiteAStextFROM
DUALTEXTFrankssOraclesiteSQL>SELECTAquotedword.AStextFROMDUALTEXT
Aquotedword.SQL>SELECTAdoublequotedword.AStextFROMDUALTEXT
Adoublequotedword.EscapewildcardcharactersTheLIKEkeywordallowsforstring
searches.The_wildcardcharacterisusedtomatchexactlyonecharacter,while%isusedtomatchzeroormore
occurrencesofanycharacters.ThesecharacterscanbeescapedinSQL.Examples:SELECTnameFROMemp
WHEREidLIKE%/_%ESCAPE/SELECTnameFROMempWHEREidLIKE%\%%ESCAPE\Escape
ampersand(&)charactersinSQL*PlusWhenusingSQL*Plus,theDEFINEsettingcanbechangedtoallow&s
(ampersands)tobeusedintext:SETDEFINE~SELECTLaurel&HardyFROMdualOthermethods:Definean
escapecharacter:SETESCAPE\SELECT\&abcFROMdualDontscanforsubstitutionvariables:SETSCAN
OFFSELECT&ABCxFROMdualAnotherwaytoescapethe&wouldbetouseconcatenation,whichwouldnot
requireanySETcommandsSELECTLaurel||&||HardyFROMdualUsethe10gQuotingmechanism:
Syntaxq[QUOTE_CHAR]Text[QUOTE_CHAR]MakesurethattheQUOTE_CHARdoesntexistinthetext.SELECT
q{ThisisOrafaqsquotedtextfield}FROMDUAL
Canoneselectarandomcollectionofrowsfromatable?
Thefollowingmethodscanbeusedtoselectarandomcollectionofrowsfromatable:TheSAMPLEClauseFrom
Oracle8i,theeasiestwaytorandomlyselectrowsfromatableistousetheSAMPLEclausewithaSELECTstatement.
Examples:SELECT*FROMempSAMPLE(10)Intheaboveexample,Oracleisinstructedtorandomlyreturn10%
oftherowsinthetable.SELECT*FROMempSAMPLE(5)BLOCKSThisexamplewillsample5%ofallformatted
databaseblocksinsteadofrows.Thisclauseonlyworksforsingletablequeriesonlocaltables.Ifyouincludethe
SAMPLEclausewithinamultitableorremotequery,youwillgetaparseerrororORA30561:SAMPLEoptionnot

http://bobi.blog.com/2012/08/20/sqlfaq/

MonthlyTopics
SelectMonth

Calendar
August2012
M T W T F S S

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

Sep

Pages
BetheMasterofinterview
70factsofUniverseDesigner!!
CreatingCascadingPromptsina
Universe
Dashboards
Dashboards
Datamodelling(DM)
Datawarehousesvsoperational
systems
DataWarehousingConcepts
SybaseASEVsSybaseIQ
SystemProcedures
Dr.Codd's12Rulesfora
RelationalDatabaseModel
2/6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

allowedinstatementwithmultipletablereferences.Onewayaroundthisistocreateaninlineviewonthedriving
tableofthequerywiththeSAMPLEclause.Example:SELECTt1.dept,t2.empFROM(SELECT*FROMdept
SAMPLE(5))t1,empt2WHEREt1.dep_id=t2.dep_idIfyouexaminetheexecutionplanofaSampleTableScan,
youshouldseeasteplikethis:TABLEACCESS(SAMPLE)OFEMP(TABLE)ORDERBYdbms_random.value()
Thismethodordersthedatabyarandomcolumnnumber.Example:SQL>SELECT*FROM(SELECTename2
FROMemp3ORDERBYdbms_random.value())4WHERErownum<=3ENAMEWARDMILLER
TURNERTheORA_HASH()functionThefollowingexampleretrievesasubsetofthedataintheemptableby
specifying3buckets(0to2)andthenreturningthedatafrombucket1:SELECT*FROMempWHERE
ORA_HASH(empno,2)=1
Q:Howdoesoneeliminateduplicatesrowsfromatable?
Chooseoneofthefollowingqueriestoidentifyorremoveduplicaterowsfromatableleavingonlyuniquerecordsin
thetable:Method1:DeleteallrowidsthatisBIGGERthantheSMALLESTrowidvalue(foragivenkey):SQL>
DELETEFROMtable_nameA2WHEREROWID>(SELECTmin(rowid)3FROMtable_nameB4WHERE
A.key_values=B.key_values)Method2:Thismethodisusuallyfaster.However,remembertorecreateallindexes,
constraints,triggers,etc.onthetablewhendone.SQL>createtabletable_name2asselectdistinct*from
table_name1SQL>droptabletable_name1SQL>renametable_name2totable_name1Method3:SQL>DELETE
FROMmy_tablet12WHEREEXISTS(SELECTxFROMmy_tablet23WHEREt2.key_value1=t1.key_value14
ANDt2.key_value2=t1.key_value24ANDt2.rowid>t1.rowid)Note:OnecaneliminateN^2unnecessaryoperations
bycreatinganindexonthejoinedfieldsintheinnerloop(noneedtoloopthroughtheentiretableoneachpassbya
record).Thiswillspeedupthedeletionprocess.Note2:IfyouarecomparingNULLcolumns,usetheNVLfunction.
RememberthatNULLisnotequaltoNULL.ThisshouldnotbeaproblemasallkeycolumnsshouldbeNOTNULLby
definition.Method4:Thismethodcollectsthefirstrow(orderbyrowid)foreachkeyvaluesanddeletetherowsthat
arenotinthisset:SQL>DELETEFROMmy_tablet11WHERErowidNOTIN(SELECTmin(rowid)2FROM
my_tablet23GROUPBYkey_value1,key_value2)Note:IFkey_value1isnullorkey_value2isnull,thisstillworks
correctly.
Q:Howdoesonegetthetimedifferencebetweentwodatecolumns?
Oracleallowstwodatevaluestobesubtractedfromeachotherreturninganumericvalueindicatingthenumberof
daysbetweenthetwodates(maybeafraction).Thisexamplewillshowhowtorelateitbacktoatimevalue.Lets
investigatesomesolutions.Testdata:SQL>CREATETABLEdates(date1DATE,date2DATE)Tablecreated.SQL>
SQL>INSERTINTOdatesVALUES(SYSDATE,SYSDATE1)1rowcreated.SQL>INSERTINTOdatesVALUES
(SYSDATE,SYSDATE1/24)1rowcreated.SQL>INSERTINTOdatesVALUES(SYSDATE,SYSDATE1/60/24)1
rowcreated.SQL>SELECT(date1date2)FROMdatesDATE1DATE21.041666667.000694444
Solution1SQL>SELECTfloor(((date1date2)*24*60*60)/3600)2||HOURS||3floor((((date1date2)*24*60*60)
4floor(((date1date2)*24*60*60)/3600)*3600)/60)5||MINUTES||6round((((date1date2)*24*60*60)7
floor(((date1date2)*24*60*60)/3600)*36008(floor((((date1date2)*24*60*60)9floor(((date1
date2)*24*60*60)/3600)*3600)/60)*60)))10||SECStime_difference11FROMdatesTIME_DIFFERENCE
24HOURS0MINUTES0SECS1HOURS0
MINUTES0SECS0HOURS1MINUTES0SECSSolution2Ifyoudontwanttogothroughthefloorandceiling
maths,trythismethod:SQL>SELECTto_number(to_char(to_date(1,J')+2(date1date2),J)1)days,3
to_char(to_date(00:00:00,HH24:MI:SS)+4(date1date2),HH24:MI:SS)time5FROMdatesDAYSTIME
100:00:00001:00:00000:01:00Solution3Hereisasimplermethod:SQL>SELECTtrunc(date1
date2)days,2to_char(trunc(sysdate)+(date1date2),HH24HoursMIMinutesSSSeconds)time3FROM
datesDAYSTIME100Hours00Minutes00Seconds001Hours00Minutes00
Seconds000Hours01Minutes00Seconds
Q:Howdoesoneaddaday/hour/minute/secondtoadatevalue?
TheSYSDATEpseudocolumnshowsthecurrentsystemdateandtime.Adding1toSYSDATEwilladvancethedateby
1day.Usefractionstoaddhours,minutesorsecondstothedate.Lookattheseexamples:SQL>selectsysdate,
sysdate+1/24,sysdate+1/1440,sysdate+1/86400fromdualSYSDATESYSDATE+1/24SYSDATE+1/1440
SYSDATE+1/8640003Jul200208:32:1203Jul
200209:32:1203Jul200208:33:1203Jul200208:32:13ThefollowingformatisfrequentlyusedwithOracle
Replication:selectsysdateNOW,sysdate+30/(24*60*60)NOW_PLUS_30_SECSfromdualNOW
NOW_PLUS_30_SECS03JUL200516:47:2303JUL200516:47:53Herearea
coupleofexamples:DescriptionDateExpressionNowSYSDATETomorow/nextdaySYSDATE+1Sevendaysfrom
nowSYSDATE+7OnehourfromnowSYSDATE+1/24ThreehoursfromnowSYSDATE+3/24Ahalfhourfrom
nowSYSDATE+1/4810minutesfromnowSYSDATE+10/144030secondsfromnowSYSDATE+30/86400
Tomorrowat12midnightTRUNC(SYSDATE+1)Tomorrowat8AMTRUNC(SYSDATE+1)+8/24NextMondayat
12:00noonNEXT_DAY(TRUNC(SYSDATE),MONDAY)+12/24Firstdayofthemonthat12midnight
TRUNC(LAST_DAY(SYSDATE)+1)ThenextMonday,WednesdayorFridayat9a.m
TRUNC(LEAST(NEXT_DAY(sysdate,MONDAY),NEXT_DAY(sysdate,WEDNESDAY),NEXT_DAY(sysdate,
FRIDAY)))+9/24
Q:Howdoesonecodeamatrix/crosstab/pivotreportinSQL?
Newbiesfrequentlyaskhowonecandisplayrowsascolumnsorcolumnsasrows.Lookattheseexamplecrosstab
queries(alsosometimescalledtransposed,matrixorpivotqueries):SELECT*FROM(SELECTjob,
sum(decode(deptno,10,sal))DEPT10,sum(decode(deptno,20,sal))DEPT20,sum(decode(deptno,30,sal))DEPT30,
sum(decode(deptno,40,sal))DEPT40FROMscott.empGROUPBYjob)ORDERBY1JOBDEPT10DEPT20
DEPT30DEPT40ANALYST6000CLERK13001900950MANAGER2450
29752850PRESIDENT5000SALESMAN5600Hereisthesamequerywithsomefancyheadersandtotals:SQL>
ttitleCrosstabReportSQL>breakonreportSQL>computesumofdept10dept20dept30dept40totalonreport
SQL>SQL>SELECT*2FROM(SELECTjob,3sum(decode(deptno,10,sal))DEPT10,4sum(decode(deptno,20,sal))
DEPT20,5sum(decode(deptno,30,sal))DEPT30,6sum(decode(deptno,40,sal))DEPT40,7sum(sal)TOTAL8FROM
emp9GROUPBYjob)10ORDERBY1MonAug23page1CrosstabReportJOBDEPT10DEPT20DEPT30
DEPT40TOTALANALYST60006000CLERK130019009504150
MANAGER2450297528508275PRESIDENT50005000SALESMAN56005600
sum875010875940029025Heresanothervariationonthetheme:SQL>SELECT

http://bobi.blog.com/2012/08/20/sqlfaq/

ExplainindetailaboutSlowly
changingDimentionandits
type!!
ExtendMergedDimensions
FrequentInterviewQuestionof
BusinessObject
HowtoknowTimeoflastfull
backupofyourdatabase?
Howtoresetadministrator
passwordifyou
forgotten.???
MDA/Monitoringtablesin
SybaseASE
MultiCubefunctioninSAP
BusinessObject
PredefinedUserAccountsin
Oracle11g
Salarynegotiationisanartin
InterviewProcess!!!
SAPBOWikipedia
SQLInterviewQuestions
SQLInjection
SybaseRelatedLinks
TYPEOFSCHEMAIN
DATAWAREHOUSE
Whataredifferentnormalization
forms?
OfficialProductTutorialsSAPBO
BISuite

MyRecentPosts
10Keyfactsyouneedtoknowbefore
planningaMigrationprojecttoSAP
BOBI4.0project
MasterConceptofSAPBOBI
versions,SupportpacksandFixpacks
&Patchlevel
MasterConceptofAuditDBinBOBI
4.0
StepbyStepforestablishingRFC
ConnectionbetweenSAPBW&Data
Service
StepstoUpgradefrom11.7/3.X/4.Xto
SAPDataServices4.2
HowtoVersioncontrolinBODS
BODataServicesATLImport
Automation
HowtointegrateSAPBOwith
PeoplesoftERPdatalayer
CompleteOverviewofSAPBI4.x
IntegrationOptionforMicrosoft
SharePoint
HowtoPublishSAPBusinessObjects
reportstoSharePoint
HowtoPublishBusinessObjects
reportstoSharePoint
LearnBOwithSharepointintegration
HowtoSetupSAPSSOServicein
SAPBOBI4.0CMC
SetupofSSOagaintSAPBWforSAP
BOBI4.0BICSorJCOconnections
HowtoImportSAPBOBI4.0
certificateintoSAPBW
HowtosetupSSOagainstSAPBW
withSAPBOBI4.0Common
SemanticLayer(UNX)orBICS
OverviewofSAPBI4.xIntegration
OptionforMicrosoftSharePoint
ConceptofcompleteSSO
IntegratingSAPBusinessObjects4.1
withSAPHANAusingSAMLSSO
3/6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

DECODE(MOD(v.row#,3)2,1,Number:||deptno3,2,Name:||dname4,0,Location:||loc5)ASDATA6
FROMdept,7(SELECTrownumASrow#FROMuser_objectsWHERErownum<4)v8WHEREdeptno=309/
DATANumber:30Name:SALESLocation:CHICAGOFromOracle11g,we
canusepivotoption
Q:CanoneretrieveonlyrowsXtoYfromatable?SELECT*FROM(SELECTename,rownumrnFROMemp
WHERErownum<101)WHERERNbetween91and100Note:the101isjustonegreaterthanthemaximumrow
oftherequiredrows(meansx=90,y=100,sotheinnervaluesisy+1).SELECTrownum,f1FROMt1GROUPBY
rownum,f1HAVINGrownumBETWEEN2AND4AnothersolutionistousetheMINUSoperation.Forexample,to
displayrows5to7,constructaquerylikethis:SELECT*FROMtableXWHERErowidin(SELECTrowidFROM
tableXWHERErownum<=7MINUSSELECTrowidFROMtableXWHERErownum<5)thisonewasfasterfor
meandallowedforsortingbeforefilteringbyrownum.Theinnerquery(tableA)canbeaseriesoftablesjoined
togetherwithanyoperationbeforethefilteringbyrownumisapplied.SELECT*FROM(SELECTa.*,rownumRN
FROM(SELECT*FROMt1ORDERBYkey_column)aWHERErownum<=7)WHERErn>=5Pleasenote,thereis
noexplicitroworderinarelationaldatabase.However,thisqueryisquitefunandmayevenhelpintheoddsituation.
Thegenericsolutiontogetfullinformationofrowsbetweenxandy
________________________________________SELECT*FROMempWHEREempnoin(SELECTempno
FROMempGROUPBYrownum,empnoHAVINGrownumBETWEEN&xAND&y)
________________________________________selectparticularrowsfromatable:selectforrownum=4,15and
17.select*from(selectrownummyrownum,emp.*fromemployeesemp)mytablewheremyrownumin(4,15,17)
selectingrowbetweenrangeofrownum:selectforrownumbetween(12,20).select*from(selectrownum
myrownum,emp.*fromemployeesemp)mytablewheremyrownumbetween12and20Replace12and20with&x
and&yrespectivelytoassignrangedynamically.select*from(selectrownummyrownum,emp.*fromemployees
emp)mytablewheremyrownumbetween&xand&yCombinedquerytogivecompleteflexibilitytopickparticular
rowsandalsoagivenrange.select*from(selectrownummyrownum,emp.*fromemployeesemp)mytablewhere
myrownumbetween12and17ormyrownumin(3,18,25)
Q:CanoneretrieveonlytheNthrowfromatable?
SELECT*FROMt1aWHEREn=(SELECTCOUNT(rowid)FROMt1bWHEREa.rowid>=b.rowid)SELECT*
FROM(SELECTENAME,ROWNUMRNFROMEMPWHEREROWNUM<101)WHERERN=100Note:Inthis
firstqueryweselectonemorethantherequiredrownumber,thenweselecttherequiredone.Itsfarbetterthanusinga
MINUSoperation.SELECTf1FROMt1WHERErowid=(SELECTrowidFROMt1WHERErownum<=10MINUS
SELECTrowidFROMt1WHERErownum<10)SELECTrownum,empnoFROMscott.empaGROUPBY
rownum,empnoHAVINGrownum=4AlternativelySELECT*FROMempWHERErownum=1ANDrowidNOT
IN(SELECTrowidFROMempWHERErownum<10)Pleasenote,thereisnoexplicitroworderinarelational
database.However,thisqueryisquitefunandmayevenhelpintheoddsituation.
Q:Howcanonedump/examinetheexactcontentofadatabasecolumn?
Tabledatacanbeextractedfromthedatabaseasoctal,decimalorhexvalues:SELECTDUMP(col1,10)FROMtab1
WHEREcond1=val1DUMP(COL1)Typ=96Len=4:65,66,67,32Forthisexample,
type=96isindicatingaCHARcolumn.Thelastbyteinthecolumnis32,whichistheASCIIcodeforaspace.Thistells
usthatthiscolumnisblankpadded.
QHowdoesoneaddacolumntothemiddleofatable?
Oracleonlyallowscolumnstobeaddedtotheendofanexistingtable.Example:SQL>CREATETABLEtab1(col1
NUMBER)Tablecreated.SQL>ALTERTABLEtab1ADD(col2DATE)Tablealtered.SQL>DESCtab1Name
Null?TypeCOL1NUMBERCOL2DATENevertheless,
somedatabasesalsoallowcolumnstobeaddedtoanexistingtableafteraparticularcolumn(i.e.inthemiddleofthe
table).Forexample,inMySQLthefollowingsyntaxisvalid:ALTERTABLEtablenameADDcolumnnameAFTER
columnnameOracledoesnotsupportthissyntax.However,itdoesntmeanthatitcannotbedone.Workarounds:1.
Createanewtableandcopythedataacross.SQL>RENAMEtab1TOtab1_oldTablerenamed.SQL>CREATE
TABLEtab1ASSELECT0AScol1,col1AScol2FROMtab1_oldTablecreated.2.Usethe
DBMS_REDEFINITIONpackagetochangethestructureonlinewhileusersareworking.
Q:Howdoesonecodeahierarchicaltreestructuredquery?
TheSCOTT/TIGERdatabaseschemacontainsatableEMPwithaselfreferencingrelation(EMPNOandMGR
columns).ThistableisperfectfortestinganddemonstratingtreestructuredqueriesastheMGRcolumncontainsthe
employeenumberofthecurrentemployeesboss.TheLEVELpseudocolumnisanindicationofhowdeepinthe
treeoneis.Oraclecanhandlequerieswithadepthofupto255levels.Lookatthisexample:SQL>SELECTlevel,
empno,ename,mgr2FROMemp3CONNECTBYPRIORempno=mgr4STARTWITHmgrISNULL5/LEVEL
EMPNOENAMEMGR17839KING27566JONES783937788SCOTT7566
Onecanproduceanindentedreportbyusingthelevelnumbertosubstringorlpad()aseriesofspaces,and
concatenatethattothestring.Lookatthisexample:SQL>SELECTLPAD(,LEVEL*2)||ename2FROMemp3
CONNECTBYPRIORempno=mgr4STARTWITHmgrISNULLLPAD(,LEVEL*2)||ENAME
KINGJONESSCOTTUsethestartwithclausetospecifythestartof
thetree.Morethanonerecordcanmatchthestartingcondition.Onedisadvantageofhavingaconnectbyprior
clauseisthatyoucannotperformajointoothertables.Theconnectbypriorclauseisrarelyimplementedinthe
otherdatabaseofferings.Tryingtodothisprogrammaticallyisdifficultasonehastodothetoplevelqueryfirst,then,
foreachoftherecordsopenacursortolookforchildnodes.OnewayofworkingaroundthisistousePL/SQL,open
thedrivingcursorwiththeconnectbypriorstatement,andtheselectmatchingrecordsfromothertablesonarow
byrowbasis,insertingtheresultsintoatemporarytableforlaterretrieval.NOTE:Treestructuredqueriesare
definitelynonrelational(enoughtokillCoddandmakehimrollinhisgrave).Also,thisfeatureisnotoftenfoundin
otherdatabaseofferings.
Q:Howdoesonecount/sumdatavaluesinacolumn?
Count/sumFIXvalues:Usethissimplequerytocountthenumberofdatavaluesinacolumn:selectmy_table_column,
count(*)frommy_tablegroupbymy_table_columnAmoresophisticatedexampleselectdept,sum(

http://bobi.blog.com/2012/08/20/sqlfaq/

confuguration
BI4.0NewFeaturesandChanges
BI4.0PortalIntegration
MasteringinSAPBOConnection&
IntegrationwithotherBItool
Conceptofusingdelegatedmeasures
ConceptofDelegatedSearchforList
ofValues
BusinessObjectsBackupyourBI
system
HackingBOBI4.0administrator
accountresetAdminPassword
BusinessObjectsRepositoryScanand
RepairusingRepositoryDiagnostic
Tool(reposcan)
Top30tipsofBOXIR2Query
Builders
HowtoUpgradetoBI4.0
BusinessObjects4.0SingleSignOn
(SSO)withWINAD
SAPAdministration:HowtosetupSSO
againstSAPBWwithSAPBOBI4.0
CommonSemanticLayer(UNX)or
BICS
OptimizequerywithQueryStripping
inWebIntelligence
SAPBO:WebithinclientvsWebirich
client
MultitenancyManagementtoolsetup,
newfeaturesinBI4.1
ConfiguringtraceLogsin
BusinessObjects4.0
BusinessObjectsAdministration
AuditreportingvsMetadatareporting
ProcesstocreateBatchScriptto
START/STOPServerIntelligence
Agent(SIA)onWindows2008Server
StepbyStep
SAPBIPlattform4.1Performance
Tuning
IN,ForEach&ForAllContext
OperatorinBO
NewfeatureofBI4.1:Desktop
IntelligenceCompatibilityPack(DCP):
(FAQs)
InstallingSAPBI4.1SP01onRedHat
EnterpriseLinux6.xStepbystep
BIUpgradeQ&A
HowtoUpgradetoBI4.0
12factsyoushouldknowbefore
upgradingtoBI4.0
ConfiguringtheFileRepositoryServer
(FRS)inBI4
SettingupSAPBusinessObjects
Mobile
BIPlatform4.0Clusterconfiguration
HowtocountNumberof
reports/subreportsinaWebIdocument
VVIFactofOuterJoininUniverse
DesigninSAPBO
ClusteringandLoadBalancingin
Tomcat5,Part2
TomcatclusteringPart1
HowtocreateanSAPBusinessObjects
XI3.1cluster(onWindows)
DerivedtablesinSQLandinSAP
BusinessObject
Bigdata:Thenextfrontierfor
innovation,competition,and
productivity
ConfiguretheSAPBusinessObject/BI
4.0Servicesthroughcommandline
HowtoChangeLoginBanneror
4/6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

decode(sex,M',1,0))MALE,sum(decode(sex,F',1,0))FEMALE,count(decode(sex,M',1,F',1))TOTALfrom
my_emp_tablegroupbydeptCount/sumRANGESofdatavaluesinacolumn:Avaluexwillbebetweenvaluesyand
zifGREATEST(x,y)=LEAST(x,z).Lookatthisexample:selectf2,sum(decode(greatest(f1,59),least(f1,100),1,0))
Range60100,sum(decode(greatest(f1,30),least(f1,59),1,0))Range3059,sum(decode(greatest(f1,0),least(f1,
29),1,0))Range0029frommy_tablegroupbyf2Forequalsizerangesitmightbeeasiertocalculateitwith
DECODE(TRUNC(value/range),0,rate_0,1,rate_1,).Eg.selectenameName,salSalary,decode(
trunc(f2/1000,0),0,0.0,1,0.1,2,0.2,3,0.31)Taxratefrommy_tableQ:Howdoesonedrop/renameacolumnina
table?DropacolumnFromOracle8ionecanDROPacolumnfromatable.Lookatthissamplescript,demonstrating
theALTERTABLEtable_nameDROPCOLUMNcolumn_namecommand.Workaroundsforolderreleases:SQL>
updatet1setcolumn_to_drop=NULLSQL>renamet1tot1_baseSQL>createviewt1asselect>specificcolumns>
fromt1_baseSQL>createtablet2asselect>specificcolumns>fromt1SQL>droptablet1SQL>renamet2tot1
RenameacolumnFromOracle9ionecanRENAMEacolumnfromatable.Lookatthisexample:ALTERTABLE
tablenameRENAMECOLUMNoldcolumnTOnewcolumnWorkaroundsforolderreleases:Useaviewwithcorrect
columnnames:renamet1tot1_basecreateviewt1>columnlistwithnewname>asselect*fromt1_baseRecreate
thetablewithcorrectcolumnnames:createtablet2>columnlistwithnewname>asselect*fromt1droptablet1
renamet2tot1Addacolumnwithanewnameanddropanoldcolumn:altertablet1add(newcolamedatatype)
updatet1setnewcolname=oldcolnamealtertablet1dropcolumnoldcolnameQ:HowdoesoneimplementIF
THENELSElogicinaSELECTstatement?OnecanusetheCASEstatementorfunctionslikeDECODE,NVL,NVL2,
NULLIF,COALESCE,etc.HereisthesyntaxfortheCASEstatement:CASEexpWHENcomparison_exp1THEN
return_exp1[WHENcomparison_exp2THENreturn_exp2WHENcomparison_exp3THENreturn_exp3ELSE
else_exp]ENDAndforDECODE:DECODE(col|exprn,srch1,rslt1[,srch2,rslt2,...,][,default])
Q:HowdoesonepreventOraclefromusinganIndex?
Incertaincases,onemaywanttodisabletheuseofaspecific,orallindexesforagivenquery.Herearesome
examples:AddinganexpressiontotheindexedcolumnSQL>selectcount(*)fromtwhereempno+0=1000COUNT(*)
1ExecutionPlan0SELECTSTATEMENT
Optimizer=CHOOSE(Cost=2Card=1Bytes=3)10SORT(AGGREGATE)21TABLEACCESS(FULL)OFT
(Cost=2Card=1Bytes=3)SpecifyingtheFULLhinttoforcefulltablescanSQL>select/*+FULL(t)*/*fromtwhere
empno=1000EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNOGRADE
1000VictorDBA783920MAY0311000010JUNIORExecution
Plan0SELECTSTATEMENTOptimizer=CHOOSE(Cost=2Card=1
Bytes=41)10TABLEACCESS(FULL)OFT(Cost=2Card=1Bytes=41)SpecifyingNO_INDEXhintSQL>select/*+
NO_INDEX(T)*/count(*)fromtwhereempno=1000COUNT(*)1ExecutionPlan
0SELECTSTATEMENTOptimizer=CHOOSE(Cost=2Card=1
Bytes=3)10SORT(AGGREGATE)21TABLEACCESS(FULL)OFT(Cost=2Card=1Bytes=3)Usingafunction
overtheindexedcolumnSQL>selectcount(*)fromtwhereto_number(empno)=1000COUNT(*)1Execution
Plan0SELECTSTATEMENTOptimizer=CHOOSE(Cost=2Card=1
Bytes=3)10SORT(AGGREGATE)21TABLEACCESS(FULL)OFT(Cost=2Card=1Bytes=3)
Q:HowdoesoneselectEVERYNthrowfromatable?
Onecaneasilyselectalleven,odd,orNthrowsfromatableusingSQLquerieslikethis:Method1:Usingasubquery
SELECT*FROMempWHERE(ROWID,0)IN(SELECTROWID,MOD(ROWNUM,4)FROMemp)Method2:Use
dynamicviews(availablefromOracle7.2):SELECT*FROM(SELECTrownumrn,empno,enameFROMemp)temp
WHEREMOD(temp.ROWNUM,4)=0Method3:UsingGROUPBYandHAVINGSELECTrownum,f1FROMt1
GROUPBYrownum,f1HAVINGMOD(rownum,n)=0ORrownum=2nPleasenote,thereisnoexplicitroworderin
arelationaldatabase.However,thesequeriesarequitefunandmayevenhelpintheoddsituation.
Q:HowdoesoneselecttheLASTNrowsfromatable?
FromOracle9ionwards,theRANK()andDENSE_RANK()functionscanbeusedtodeterminetheLASTNor
BOTTOMNrows.Examples:Getthebottom10employeesbasedontheirsalarySELECTename,salFROM(
SELECTename,sal,RANK()OVER(ORDERBYsalASC)sal_rankFROMemp)WHEREsal_rank<=10Selectthe
employeesgettingthelowest10salariesSELECTename,salFROM(SELECTename,sal,DENSE_RANK()OVER
(ORDERBYsal)sal_dense_rankFROMemp)WHEREsal_dense_rank<=10ForOracle8iandabove,onecanget
thebottomNrowsusinganinnerquerywithanORDERBYclause:SELECT*FROM(SELECT*FROMmy_table
ORDERBYcol_name_1)WHEREROWNUM<10Usethisworkaroundforolder(8.0andprior)releases:SELECT*
FROMmy_tableaWHERE10>=(SELECTCOUNT(DISTINCTmaxcol)FROMmy_tablebWHEREb.maxcol<=
a.maxcol)ORDERBYmaxcol
Q:HowdoesoneselecttheTOPNrowsfromatable?
FromOracle9ionwards,theRANK()andDENSE_RANK()functionscanbeusedtodeterminetheTOPNrows.
Examples:
Getthetop10employeesbasedontheirsalarySELECTename,salFROM(SELECTename,sal,RANK()OVER
(ORDERBYsalDESC)sal_rankFROMemp)WHEREsal_rank<=10
Selecttheemployeesmakingthetop10salariesSELECTename,salFROM(SELECTename,sal,DENSE_RANK()
OVER(ORDERBYsalDESC)sal_dense_rankFROMemp)WHEREsal_dense_rank<=10ForOracle8iand
above,onecangettheTopNrowsusinganinnerquerywithanORDERBYclause:SELECT*FROM(SELECT*
FROMmy_tableORDERBYcol_name_1DESC)WHEREROWNUM<10Usethisworkaroundforolder(8.0and
prior)releases:SELECT*FROMmy_tableaWHERE10>=(SELECTCOUNT(DISTINCTmaxcol)FROMmy_table
bWHEREb.maxcol>=a.maxcol)ORDERBYmaxcolDESCQ:Howtogenerateatextgraphs(histograms)using
SQL?SELECTd.dnameASDepartment,LPAD(+,COUNT(*),+)asGraphFROMempe,deptdWHERE
e.deptno=d.deptnoGROUPBYd.dnameSampleoutput:DepartmentGraph
ACCOUNTING+++RESEARCH+++++SALES++++++Intheaboveexample,
thevaluereturnedbyCOUNT(*)isusedtocontrolthenumberof*characterstoreturnforeachdepartment.We
simplypassCOUNT(*)asanargumenttothestringfunctionLPAD(orRPAD)toreturnthedesirednumberof*s.

LOGOinBusinessObjectsInfoview
Trick:DisabletheDesktopIntelligence
optionundertheNewDocument
button.
TypeofConnection
DifferencebetweenBreakandSection
inWebireport
WhatisBI4HotBackup
Configureauditinglevelandauto
deleteinterval
SAPBusinessObjectArchitecture
Overviewandcomparativeanalysis
BusinessObjectsProgramObject
BusinessIntelligenceResourcesLink
BrowseCMSrepositoryanditsSecret
UsefulqueryusingSAPBOQuery
Builder
QuerywithQueryBuilder
DecodeFunctioninOracle
BOLinkedUniverse
DifferencesbetweenBOXIR2andR3
andBI4.0
TopnthSalary
Differencebetweenthehavingclause
andthegroupbystatement
Newmethodsofauthenticationoptions
intheCMCofSAPBOBI4.x
Webireport:Drilldown,Drillacross
functionality
HowtoResolveAmbiguous
Relationships
HandlingFanTrapandChasmTrapin
SAPBO
BusinessObjectsContentrecoveryand
DisasterrecoveryBOXI3.x
DatabaseDelegatedMeasuresorSmart
MeasuresinWebIntelligence
DynamicMeasuresinWebi
CascadingPromptsusingCustom
Hierarchies
BI4.0LCM:CreateBIARfile
using(Promotionalmanagementin
CMC)
ConceptofCalculationcontextinSAP
BOwebireports
ChangingthenameofaCMScluster
QaaWSvsLiveOfficeWhichoneis
theRightChoice
CheatBookofWebiReport
Multiplequeries,combinedqueriesand
synchronizedqueriescomparedin
WEBIreports
LiveOfficevsQaawsvsBIServices
StepByStepMethodtodoClustering
InBusinessObject
UsinghyperlinksinDesktop
Intelligencereports
Hack/ResetBOAdministrator
Password
CMSDBandAuditDBinSAPBO
DataModeling:BasicConcepts
DataMining:TheFundamental
Concept
ETL:MaintainingtheDataWarehouse
DesktopIntelligenceandconcept
DifferencesbetweenStoredProcedures
andFunctions
HandlingIndexes
DataProviderfunction
DataProviderSQLfunction
DaysBetweenfunction

Q:Map/concatenateseveralrowstoacolumnThisFAQwilldemonstratehowrowvaluescanbeconcatenatedintoa

http://bobi.blog.com/2012/08/20/sqlfaq/

5/6

12/23/2014

~~*~~SQLFAQ~~*~~|SAPBO,BI,Database&DatawarehouseFAQ

singlecolumnvalue(similartoMySQLs[i]GROUP_CONCAT[/i]function).
Startbycreatingthisfunction:
SQL>CREATEORREPLACEFUNCTIONrowconcat(qinVARCHAR2)RETURNVARCHAR2IS2ret
VARCHAR2(4000)3holdVARCHAR2(4000)4cursys_refcursor5BEGIN6OPENcurFORq7LOOP8FETCH
curINTOhold9EXITWHENcur%NOTFOUND10IFretISNULLTHEN11ret:=hold12ELSE13ret:=ret||,
||hold14ENDIF15ENDLOOP16RETURNret17END18/Functioncreated.Thisfunctionreturnsastring
resultwiththeconcatenatednonNULLvaluesfromaSQLstatement.ItreturnsNULLiftherearenononNULL
values.Hereisanexampleofhowtomapseveralrowstoasingleconcatenatedcolumn:SQL>SELECT
rowconcat(SELECTdnameFROMdept)ASdepartments2FROMdualDEPARTMENTS
ACCOUNTING,RESEARCH,SALES,OPERATIONS
Thisexampleismoreinterresting,itconcatenatesacolumnacrossseveralrowsbasedonanaggregation:SQL>col
employeesformata50SQL>SELECTdeptno,2rowconcat(SELECTenameFROMempaWHEREdeptno=||deptno)
ASEmployees3FROMemp4GROUPBYdeptno5/DEPTNOEMPLOYEES
30ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES20
SMITH,JONES,SCOTT,ADAMS,FORD10CLARK,KING,MILLER

Blogroll
Blog.com
Blog.comBlog
Help&Support
SapBOXIR3UniverseDesigner
Book:

Q:WhatisthedifferencebetweenVARCHAR,VARCHAR2andCHARdatatypes?
BothCHARandVARCHAR2typesareusedtostorecharacterstringvalues,however,theybehaveverydifferently.
TheVARCHARtypeshouldnotbeused:CHARCHARshouldbeusedforstoringfixedlengthcharacterstrings.
Stringvalueswillbespace/blankpaddedbeforestoredondisk.Ifthistypeisusedtostorevariablelengthstrings,it
willwastealotofdiskspace.
SQL>CREATETABLEchar_test(col1CHAR(10))
Tablecreated.
SQL>INSERTINTOchar_testVALUES(qwerty)
1rowcreated.
SQL>SELECTcol1,length(col1),dump(col1)ASCIIDumpFROMchar_test
COL1LENGTH(COL1)ASCIIDumpqwerty10
Typ=96Len=10:113,119,101,114,116,121,32,32,32,32Note:ASCIIcharacter32isablankspace.VARCHAR
CurrentlyVARCHARbehavesexactlythesameasVARCHAR2.However,thistypeshouldnotbeusedasitisreserved
forfutureusage.SQL>CREATETABLEvarchar_test(col1VARCHAR2(10))Tablecreated.SQL>INSERTINTO
varchar_testVALUES(qwerty)1rowcreated.SQL>SELECTcol1,length(col1),dump(col1)ASCIIDumpFROM
varchar_testCOL1LENGTH(COL1)ASCIIDump
qwerty6Typ=1Len=6:113,119,101,114,116,121VARCHAR2VARCHAR2isusedtostorevariablelengthcharacter
strings.Thestringvalueslengthwillbestoredondiskwiththevalueitself.SQL>CREATETABLEvarchar2_test
(col1VARCHAR2(10))Tablecreated.SQL>INSERTINTOvarchar2_testVALUES(qwerty)1rowcreated.SQL>
SELECTcol1,length(col1),dump(col1)ASCIIDumpFROMvarchar2_testCOL1LENGTH(COL1)ASCIIDump
qwerty6Typ=1Len=6:113,119,101,114,116,121

Like

Tweet

Share

CommentsOff
ReadMore
Commentsareclosed.

PoweredbyBlog.com

http://bobi.blog.com/2012/08/20/sqlfaq/

6/6

You might also like