Professional Documents
Culture Documents
45UsefulOracleQueries
Aboutviralpatel.net JoinUs Search Advertise
PostFeed
Home>Database>Oracle
45UsefulOracleQueries
ByViralPatelonJanuary14,2014
Heresalistof40+UsefulOraclequeriesthateveryOracledevelopermustbookmark.Thesequeries
rangefromdatemanipulation,gettingserverinfo,getexecutionstatus,calculatedatabasesizeetc.
Subscribe
Date/Timerelatedqueries
1. Getthefirstdayofthemonth
Quicklyreturnsthefirstdayofcurrentmonth.Insteadofcurrentmonthyouwanttofindfirstdayof
monthwhereadatefalls,replaceSYSDATEwithanydatecolumn/value.
GetourArticlesviaEmail.Enteryouremail.
YourEMail
Viral Patel
SELECTTRUNC(SYSDATE,'MONTH')"Firstdayofcurrentmonth"
FROMDUAL;
Follow
3,470 followers
2. Getthelastdayofthemonth
Thisqueryissimilartoabovebutreturnslastdayofcurrentmonth.Onethingworthnotingisthatit
automaticallytakescareofleapyear.Soifyouhave29daysinFeb,itwillreturn29/2.Alsosimilarto
abovequeryreplaceSYSDATEwithanyotherdatecolumn/valuetofindlastdayofthatparticular
month.
FollowonTwitter@viralpatelnet
SELECTTRUNC(LAST_DAY(SYSDATE))"Lastdayofcurrentmonth"
FROMDUAL;
3. GetthefirstdayoftheYear
Firstdayofyearisalways1Jan.Thisquerycanbeuseinstoredprocedurewhereyouquicklywant
firstdayofyearforsomecalculation.
SELECTTRUNC(SYSDATE,'YEAR')"YearFirstDay"FROMDUAL;
4. Getthelastdayoftheyear
Similartoabovequery.Insteadoffirstdaythisqueryreturnslastdayofcurrentyear.
SELECTADD_MONTHS(TRUNC(SYSDATE,'YEAR'),12)1"YearLastDay"FROMDUAL
5. Getnumberofdaysincurrentmonth
Nowthisisuseful.Thisqueryreturnsnumberofdaysincurrentmonth.YoucanchangeSYSDATE
withanydate/valuetoknownumberofdaysinthatmonth.
SELECTCAST(TO_CHAR(LAST_DAY(SYSDATE),'dd')ASINT)number_of_days
FROMDUAL;
http://viralpatel.net/blogs/usefuloraclequeries/
LatestPosts
1. WordpressAllowContributorstoAdd/Upload
Media
2. ExcelMacro:EvaluatingFormulasDynamically
3. GettingStartedWithYeoman(Introductionto
Yeoman)
4. NavigatingSpringSecurityfromthickClientto
RESTWebservice
5. HTML5DataListExample
1/13
4/18/2015
45UsefulOracleQueries
6. Getnumberofdaysleftincurrentmonth
Belowquerycalculatesnumberofdaysleftincurrentmonth.
SELECTSYSDATE,
LAST_DAY(SYSDATE)"Last",
LAST_DAY(SYSDATE)SYSDATE"Daysleft"
FROMDUAL;
6. AuditingDMLchangesinOracle
7. Java8LambdaExpressionsTutorialwith
Examples
8. Java8DefaultMethodsTutorial
9. CompoundTriggersinOracle11gTutorial
withexample
10. HowtopassCLOBargumentinEXECUTE
IMMEDIATE
7. Getnumberofdaysbetweentwodates
Usethisquerytogetdifferencebetweentwodatesinnumberofdays.
Sponsors
SELECTROUND((MONTHS_BETWEEN('01Feb2014','01Mar2012')*30),0)
num_of_days
FROMDUAL;
OR
SELECTTRUNC(sysdate)TRUNC(e.hire_date)FROMemployees;
Usesecondqueryifyouneedtofindnumberofdayssincesomespecificdate.Inthisexample
numberofdayssinceanyemployeeishired.
8. Displayeachmonthsstartandenddateuptolastmonthoftheyear
Thiscleverquerydisplaysstartdateandenddateofeachmonthincurrentyear.Youmightwantto
usethisforcertaintypesofcalculations.
SELECTADD_MONTHS(TRUNC(SYSDATE,'MONTH'),i)start_date,
TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE,i)))end_date
FROMXMLTABLE(
'for$iin0toxs:int(D)return$i'
PASSINGXMLELEMENT(
d,
FLOOR(
MONTHS_BETWEEN(
ADD_MONTHS(TRUNC(SYSDATE,'YEAR')1,12),
SYSDATE)))
COLUMNSiINTEGERPATH'.');
9. Getnumberofsecondspassedsincetoday(since00:00hr)
SELECT(SYSDATETRUNC(SYSDATE))*24*60*60num_of_sec_since_morning
FROMDUAL;
10. Getnumberofsecondslefttoday(till23:59:59hr)
SELECT(TRUNC(SYSDATE+1)SYSDATE)*24*60*60num_of_sec_left
FROMDUAL;
Datadictionaryqueries
11. Checkifatableexistsinthecurrentdatabaseschema
Asimplequerythatcanbeusedtocheckifatableexistsbeforeyoucreateit.Thiswayyoucan
makeyourcreatetablescriptrerunnable.Justreplacetable_namewithactualtableyouwantto
check.Thisquerywillcheckiftableexistsforcurrentuser(fromwherethequeryisexecuted).
SELECTtable_name
FROMuser_tables
WHEREtable_name='TABLE_NAME';
12. Checkifacolumnexistsinatable
Simplequerytocheckifaparticularcolumnexistsintable.Usefulwhenyoutriestoaddnewcolumn
intableusingALTERTABLEstatement,youmightwannacheckifcolumnalreadyexistsbefore
addingone.
SELECTcolumn_nameASFOUND
FROMuser_tab_cols
WHEREtable_name='TABLE_NAME'ANDcolumn_name='COLUMN_NAME';
13. Showingthetablestructure
ThisquerygivesyoutheDDLstatementforanytable.NoticewehavepassTABLEasfirst
http://viralpatel.net/blogs/usefuloraclequeries/
2/13
4/18/2015
45UsefulOracleQueries
parameter.ThisquerycanbegeneralizedtogetDDLstatementofanydatabaseobject.For
exampletogetDDLforaviewjustreplacefirstargumentwithVIEWandsecondwithyourview
nameandso.
SELECTDBMS_METADATA.get_ddl('TABLE','TABLE_NAME','USER_NAME')FROMDUAL;
14. Gettingcurrentschema
Yetanotherquerytogetcurrentschemaname.
SELECTSYS_CONTEXT('userenv','current_schema')FROMDUAL;
15. Changingcurrentschema
Yetanotherquerytochangethecurrentschema.Usefulwhenyourscriptisexpectedtorununder
certainuserbutisactuallyexecutedbyotheruser.Itisalwayssafetosetthecurrentusertowhat
yourscriptexpects.
ALTERSESSIONSETCURRENT_SCHEMA=new_schema;
Databaseadministrationqueries
16. Databaseversioninformation
ReturnstheOracledatabaseversion.
SELECT*FROMv$version;
17. Databasedefaultinformation
Somesystemdefaultinformation.
SELECTusername,
profile,
default_tablespace,
temporary_tablespace
FROMdba_users;
18. DatabaseCharacterSetinformation
Displaythecharactersetinformationofdatabase.
SELECT*FROMnls_database_parameters;
19. GetOracleversion
SELECTVALUE
FROMv$system_parameter
WHEREname='compatible';
20. Storedatacasesensitivebuttoindexitcaseinsensitive
Nowthisonestricky.Sometimeyoumightqueryingdatabaseonsomevalueindependentofcase.In
yourqueryyoumightdoUPPER(..)=UPPER(..)onbothsidestomakeitcaseinsensitive.Nowin
suchcases,youmightwanttomakeyourindexcaseinsensitivesothattheydontoccupymore
space.Feelfreetoexperimentwiththisone.
CREATETABLEtab(col1VARCHAR2(10));
CREATEINDEXidx1
ONtab(UPPER(col1));
ANALYZETABLEaCOMPUTESTATISTICS;
21. ResizingTablespacewithoutaddingdatafile
YetanotherDDLquerytoresizetablespace.
ALTERDATABASEDATAFILE'/work/oradata/STARTST/STAR02D.dbf'resize2000M;
22. Checkingautoextendon/offforTablespaces
Querytocheckifautoextendisonoroffforagiventablespace.
SELECTSUBSTR(file_name,1,50),AUTOEXTENSIBLEFROMdba_data_files;
http://viralpatel.net/blogs/usefuloraclequeries/
3/13
4/18/2015
45UsefulOracleQueries
(OR)
SELECTtablespace_name,AUTOEXTENSIBLEFROMdba_data_files;
23. Addingdatafiletoatablespace
Querytoadddatafileinatablespace.
ALTERTABLESPACEdata01ADDDATAFILE'/work/oradata/STARTST/data01.dbf'
SIZE1000MAUTOEXTENDOFF;
24. Increasingdatafilesize
Yetanotherquerytoincreasethedatafilesizeofagivendatafile.
ALTERDATABASEDATAFILE'/u01/app/Test_data_01.dbf'RESIZE2G;
25. FindtheActualsizeofaDatabase
GivestheactualdatabasesizeinGB.
SELECTSUM(bytes)/1024/1024/1024ASGBFROMdba_data_files;
26. FindthesizeoccupiedbyDatainaDatabaseorDatabaseusagedetails
Givesthesizeoccupiedbydatainthisdatabase.
SELECTSUM(bytes)/1024/1024/1024ASGBFROMdba_segments;
27. FindthesizeoftheSCHEMA/USER
GivethesizeofuserinMBs.
SELECTSUM(bytes/1024/1024)"size"
FROMdba_segments
WHEREowner='&owner';
Home
Android
Java
Spring
Frameworks
Database
JavaScript
Web
More
28. LastSQLfiredbytheUseronDatabase
ThisquerywilldisplaylastSQLqueryfiredbyeachuserinthisdatabase.Noticehowthisquery
displaylastSQLpereachsession.
SELECTS.USERNAME||'('||s.sid||')'||s.osuserUNAME,
s.program||''||s.terminal||'('||s.machine||')'PROG,
s.sid||'/'||s.serial#sid,
s.status"Status",
p.spid,
sql_textsqltext
FROMv$sqltext_with_newlinest,V$SESSIONs,v$processp
WHEREt.address=s.sql_address
ANDp.addr=s.paddr(+)
ANDt.hash_value=s.sql_hash_value
ORDERBYs.sid,t.piece;
Performancerelatedqueries
29. CPUusageoftheUSER
DisplaysCPUusageforeachUser.Usefultounderstanddatabaseloadbyuser.
SELECTss.username,se.SID,VALUE/100cpu_usage_seconds
FROMv$sessionss,v$sesstatse,v$statnamesn
WHEREse.STATISTIC#=sn.STATISTIC#
ANDNAMELIKE'%CPUusedbythissession%'
ANDse.SID=ss.SID
ANDss.status='ACTIVE'
ANDss.usernameISNOTNULL
ORDERBYVALUEDESC;
30. LongQueryprogressindatabase
Showtheprogressoflongrunningqueries.
SELECTa.sid,
a.serial#,
b.username,
opnameOPERATION,
targetOBJECT,
http://viralpatel.net/blogs/usefuloraclequeries/
4/13
4/18/2015
45UsefulOracleQueries
TRUNC(elapsed_seconds,5)"ET(s)",
TO_CHAR(start_time,'HH24:MI:SS')start_time,
ROUND((sofar/totalwork)*100,2)"COMPLETE(%)"
FROMv$session_longopsa,v$sessionb
WHEREa.sid=b.sid
ANDb.usernameNOTIN('SYS','SYSTEM')
ANDtotalwork>0
ORDERBYelapsed_seconds;
31. Getcurrentsessionid,processid,clientprocessid?
Thisisforthosewhowantstodosomevoodoomagicusingprocessidsandsessionids.
SELECTb.sid,
b.serial#,
a.spidprocessid,
b.processclientpid
FROMv$processa,v$sessionb
WHEREa.addr=b.paddrANDb.audsid=USERENV('sessionid');
V$SESSION.SIDANDV$SESSION.SERIAL#isdatabaseprocessid
V$PROCESS.SPIDisshadowprocessidonthisdatabaseserver
V$SESSION.PROCESSisclientPROCESSID,ONwindowsitIS:separatedTHEFIRST#IS
THEPROCESSIDONTHEclientAND2ndoneISTHETHREADid.
32. LastSQLFiredfromparticularSchemaorTable:
SELECTCREATED,TIMESTAMP,last_ddl_time
FROMall_objects
WHEREOWNER='MYSCHEMA'
ANDOBJECT_TYPE='TABLE'
ANDOBJECT_NAME='EMPLOYEE_TABLE';
33. FindTop10SQLbyreadsperexecution
SELECT*
FROM(SELECTROWNUM,
SUBSTR(a.sql_text,1,200)sql_text,
TRUNC(
a.disk_reads/DECODE(a.executions,0,1,a.executions))
reads_per_execution,
a.buffer_gets,
a.disk_reads,
a.executions,
a.sorts,
a.address
FROMv$sqlareaa
ORDERBY3DESC)
WHEREROWNUM<10;
34. OracleSQLqueryovertheviewthatshowsactualOracleconnections.
SELECTosuser,
username,
machine,
program
FROMv$session
ORDERBYosuser;
35. OracleSQLquerythatshowtheopenedconnectionsgroupbytheprogramthatopensthe
connection.
SELECTprogramapplication,COUNT(program)Numero_Sesiones
FROMv$session
GROUPBYprogram
ORDERBYNumero_SesionesDESC;
36. OracleSQLquerythatshowsOracleusersconnectedandthesessionsnumberforuser
SELECTusernameUsuario_Oracle,COUNT(username)Numero_Sesiones
FROMv$session
GROUPBYusername
ORDERBYNumero_SesionesDESC;
37. Getnumberofobjectsperowner
http://viralpatel.net/blogs/usefuloraclequeries/
5/13
4/18/2015
45UsefulOracleQueries
SELECTowner,COUNT(owner)number_of_objects
FROMdba_objects
GROUPBYowner
ORDERBYnumber_of_objectsDESC;
Utility/Mathrelatedqueries
38. Convertnumbertowords
Moreinfo:ConvertingnumberintowordsinOracle
SELECTTO_CHAR(TO_DATE(1526,'j'),'jsp')FROMDUAL;
Output:
onethousandfivehundredtwentysix
39. Findstringinpackagesourcecode
BelowquerywillsearchforstringFOO_SOMETHINGinallpackagesource.Thisquerycomes
handywhenyouwanttofindaparticularprocedureorfunctioncallfromallthesourcecode.
searchastringfoo_somethinginpackagesourcecode
SELECT*
FROMdba_source
WHEREUPPER(text)LIKE'%FOO_SOMETHING%'
ANDowner='USER_NAME';
40. ConvertCommaSeparatedValuesintoTable
Thequerycancomequitehandywhenyouhavecommaseparateddatastringthatyouneedto
convertintotablesothatyoucanuseotherSQLquerieslikeINorNOTIN.Hereweareconverting
AA,BB,CC,DD,EE,FFstringtotablecontainingAA,BB,CCetc.aseachrow.Onceyouhavethis
tableyoucanjoinitwithothertabletoquicklydosomeusefulstuffs.
WITHcsv
AS(SELECT'AA,BB,CC,DD,EE,FF'
AScsvdata
FROMDUAL)
SELECTREGEXP_SUBSTR(csv.csvdata,'[^,]+',1,LEVEL)pivot_char
FROMDUAL,csv
CONNECTBYREGEXP_SUBSTR(csv.csvdata,'[^,]+',1,LEVEL)ISNOTNULL;
41. Findthelastrecordfromatable
Thisonesstraightforward.Usethiswhenyourtabledoesnothaveprimarykeyoryoucannotbe
sureifrecordhavingmaxprimarykeyisthelatestone.
SELECT*
FROMemployees
WHEREROWIDIN(SELECTMAX(ROWID)FROMemployees);
(OR)
SELECT*FROMemployees
MINUS
SELECT*
FROMemployees
WHEREROWNUM<(SELECTCOUNT(*)FROMemployees);
42. RowDataMultiplicationinOracle
Thisqueryusesometrickymathfunctionstomultiplyvaluesfromeachrow.Readbelowarticlefor
moredetails.
Moreinfo:RowDataMultiplicationInOracle
WITHtbl
AS(SELECT2numFROMDUAL
UNION
SELECT3numFROMDUAL
UNION
SELECT4numFROMDUAL),
sign_val
AS(SELECTCASEMOD(COUNT(*),2)WHEN0THEN1ELSE1ENDval
FROMtbl
WHEREnum<0)
SELECTEXP(SUM(LN(ABS(num))))*val
FROMtbl,sign_val
GROUPBYval;
http://viralpatel.net/blogs/usefuloraclequeries/
6/13
4/18/2015
45UsefulOracleQueries
43. GeneratingRandomDataInOracle
Youmightwanttogeneratesomerandomdatatoquicklyinsertintablefortesting.Belowqueryhelp
youdothat.Readthisarticleformoredetails.
Moreinfo:RandomDatainOracle
SELECTLEVELempl_id,
MOD(ROWNUM,50000)dept_id,
TRUNC(DBMS_RANDOM.VALUE(1000,500000),2)salary,
DECODE(ROUND(DBMS_RANDOM.VALUE(1,2)),1,'M',2,'F')gender,
TO_DATE(
ROUND(DBMS_RANDOM.VALUE(1,28))
||''
||ROUND(DBMS_RANDOM.VALUE(1,12))
||''
||ROUND(DBMS_RANDOM.VALUE(1900,2010)),
'DDMMYYYY')
dob,
DBMS_RANDOM.STRING('x',DBMS_RANDOM.VALUE(20,50))address
FROMDUAL
CONNECTBYLEVEL<10000;
44. RandomnumbergeneratorinOracle
PlainoldrandomnumbergeneratorinOracle.Thisonesgeneratearandomnumberbetween0and
100.Changethemultipliertonumberthatyouwanttosetlimitfor.
generaterandomnumberbetween0and100
SELECTROUND(DBMS_RANDOM.VALUE()*100)+1ASrandom_numFROMDUAL;
45. Checkiftablecontainsanydata
Thisonecanbewritteninmultipleways.Youcancreatecount(*)onatabletoknownumberofrows.
Butthisqueryismoreefficientgiventhefactthatweareonlyinterestedinknowingiftablehasany
data.
SELECT1
FROMTABLE_NAME
WHEREROWNUM=1;
IfyouhavesomecoolquerythatcanmakelifeofotherOracledeveloperseasy,doshareincomment
section.
RelatedArticles
1. HowToConvertNumberintoWordsusingOracleSQLQuery
2. GeneratingRandomDatainOracle
3. FetchRandomrowsfromDatabase(MySQL,Oracle,MSSQL,PostgreSQL)
4. RowDataMultiplicationinOracle
5. OracleSkipLocked
6. InvisibleIndexesinOracle11g
7. OracleXMLTableTutorialwithExample
GetourArticlesviaEmail.Enteryouremailaddress.
SendMeTutorials
Tags:ORACLE,PLSQL,SQL
28Comments
MadirajuKrishnaChaitanya
21January,2014,7:31
HiViralPatel,ThanksaLOTforprovidingtheseusefulOracleQueriesforus.Pleasekeepupthe
GoodWork.AlltheBest.
http://viralpatel.net/blogs/usefuloraclequeries/
7/13
4/18/2015
45UsefulOracleQueries
Reply
Praveen
21January,2014,14:38
veryusefulqueries,thanksforsharing:)
Reply
Tushar
21January,2014,18:05
ExcellentcompilationofqueriesViral!.
Yourockbhai:)
Reply
krunal
20February,2014,16:01
Thankyou
usingabovedatabasequeriesiwillsolvedbrelatedproblemsinmymanyproject.
Reply
Harshita
18March,2014,17:24
GoodJobViral,reallyusefularticle.Lookingforwardtomoresuchstuff.:)
Reply
Chandra
9April,2014,1:29
ReallySomeusefulqueries
Reply
junaidahmad
12April,2014,11:34
Canyoupleasegive50differentviewsofDataDictionaryinformofSQLQueries?
Reply
NishantMishra
16April,2014,16:34
UseUSER_Views
Reply
NishantMishra
16April,2014,16:34
YoucanuseUSER_VIEWStoseetheavailableviewswiththeSCHEMA.
Describetheviewandseethecolumns..
Usethecolumnnametogetthedetails
Reply
David
17April,2014,11:05
Ihavearequirement.
Ihave5attributecolumnscorresponding5daysoftheweekfromMondaytoFriday.
TheattributevaluescanbeYesorNo.
IfWednesdayandFridayaresettoYes,IneedaquerytoretrieveallthewednesdaysandFridays
fromagivendatetosysdate.
Similarly,IfMonday,WednesdayandThursdayaresettoYes,IneedalltheMondays,Wednesdays
andThursdayfromagivendate(passedasparameter)tosysdate.
Couldanyonepleasehelpmeinwritingthisquery?
Reply
Kevin
forDavidsquestiononApril17th..Imsurethiscouldprobablybecleanedupsomemore
http://viralpatel.net/blogs/usefuloraclequeries/
8/13
4/18/2015
45UsefulOracleQueries
andIseethattheFridayportionofthisreturnsafridaybefore
01/01/2012butthisisastart
15May,2014,18:57
createtableCVT_T1_DAYSas
(select'1'Mon,'0'Tue,'0'Wed,'1'Thu,'1'Frifromdual);
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'MON'ddfromCVT_T1_DAYSwheremon=1)
connectbyrownum<=round((sysdateto_date('01/01/2012','dd/mm/yyyy'))/7)
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'TUE'ddfromCVT_T1_DAYSwheretue=1)
connectbyrownum<=round((sysdateto_date('01/01/2012','dd/mm/yyyy'))/7)
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'WED'ddfromCVT_T1_DAYSwherewed=1)
connectbyrownum<=round((sysdateto_date('01/01/2012','dd/mm/yyyy'))/7)
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'THU'ddfromCVT_T1_DAYSwherethu=1)
connectbyrownum<=round((sysdateto_date('01/01/2012','dd/mm/yyyy'))/7)
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'FRI'ddfromCVT_T1_DAYSwhereFRI=1)
connectbyrownum<=round((sysdateto_date('01/01/2012','dd/mm/yyyy'))/7)
orderbydate_
;
Reply
Kevin
15May,2014,19:00
note,the<=shouldbe<=
or"lessthanorequalto"
itdidn'tformatcorrectlyinmycut/paste
Reply
FernandoTlatilolpa
6May,2014,3:59
HelloandthanksViral,Ithinkyoucanincludeaquerywhichreturnnumberofcolumnsresultofa
dynamicquery,theseusefullwhenyousendascriptinsideafunctionandyoudontknowexactly
howmanycolumnsyouobtain.
Onceagainthaksforyoureffort.
Reply
salim
7May,2014,12:55
Thankyoudearforsharingknowledge
Reply
Kevin
16May,2014,2:49
inresponsetoDavidsquery.cleanedupthedatesthatcomeoutpriortothedateenteredaswell
asifyouenteradateinthefuture.BothSQLandPL/SQLsolutionsarebelow.note,greaterthan,
equal,lessthanformattingmightbeaffectedbythetags
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'MON'ddfromCVT_T1_DAYSwheremon=1)
whereto_date('&indate','mm/dd/yyyy')<=sysdate
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
connectbyrownum<=round((sysdateto_date('&indate','mm/dd/yyyy'))/7)
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'TUE'ddfromCVT_T1_DAYSwheretue=1)
whereto_date('&indate','mm/dd/yyyy')<=sysdate
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
connectbyrownum<=round((sysdateto_date('&indate','mm/dd/yyyy'))/7)
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'WED'ddfromCVT_T1_DAYSwherewed=1)
whereto_date('&indate','mm/dd/yyyy')<=sysdate
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
connectbyrownum<=round((sysdateto_date('&indate','mm/dd/yyyy'))/7)
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'THU'ddfromCVT_T1_DAYSwherethu=1)
whereto_date('&indate','mm/dd/yyyy')<=sysdate
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
http://viralpatel.net/blogs/usefuloraclequeries/
9/13
4/18/2015
45UsefulOracleQueries
connectbyrownum<=round((sysdateto_date('&indate','mm/dd/yyyy'))/7)
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
union
selectdd,next_day(sysdate(rownum*7),dd)DATE_
from(SELECT'FRI'ddfromCVT_T1_DAYSwhereFRI=1)
whereto_date('&indate','mm/dd/yyyy')<=sysdate
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
connectbyrownum<=round((sysdateto_date('&indate','mm/dd/yyyy'))/7)
andnext_day(sysdate(rownum*7),dd)>=to_date('&indate','mm/dd/yyyy'
orderbydate_;
declare
v_datechosendate:=to_date('&indate','mm/dd/yyyy');
v_weeksdiffnumber:=round((sysdatev_datechosen)/7);
v_sysdatedate:=sysdate;
v_ddchar(5);
v_datedate;
cursordatesis
selectdd,next_day(v_sysdate(rownum*7),dd)DATE_
from(SELECT'MON'ddfromCVT_T1_DAYSwheremon=1)
wherev_datechosen<=v_sysdate
andnext_day(v_sysdate(rownum*7),dd)>=v_datechosen
connectbyrownum<=v_weeksdiffand
next_day(v_sysdate(rownum*7),dd)>=v_datechosen
union
selectdd,next_day(v_sysdate(rownum*7),dd)DATE_
from(SELECT'TUE'ddfromCVT_T1_DAYSwheretue=1)
wherev_datechosen<=v_sysdate
andnext_day(v_sysdate(rownum*7),dd)>=v_datechosen
connectbyrownum<=v_weeksdiffand
next_day(v_sysdate(rownum*7),dd)>=v_datechosen
union
selectdd,next_day(v_sysdate(rownum*7),dd)DATE_
from(SELECT'WED'ddfromCVT_T1_DAYSwherewed=1)
wherev_datechosen<=v_sysdate
andnext_day(v_sysdate(rownum*7),dd)>=v_datechosen
connectbyrownum<=v_weeksdiffand
next_day(v_sysdate(rownum*7),dd)>=v_datechosen
union
selectdd,next_day(v_sysdate(rownum*7),dd)DATE_
from(SELECT'THU'ddfromCVT_T1_DAYSwherethu=1)
wherev_datechosen<=v_sysdate
andnext_day(v_sysdate(rownum*7),dd)>=v_datechosen
connectbyrownum<=v_weeksdiffand
next_day(v_sysdate(rownum*7),dd)>=v_datechosen
union
selectdd,next_day(v_sysdate(rownum*7),dd)DATE_
from(SELECT'FRI'ddfromCVT_T1_DAYSwhereFRI=1)
wherev_datechosen<=v_sysdate
andnext_day(v_sysdate(rownum*7),dd)>=v_datechosen
connectbyrownum<=v_weeksdiffand
next_day(v_sysdate(rownum*7),dd)>=v_datechosen
orderbydate_;
begin
dbms_output.enable(1000000);
dbms_output.put_line(v_weeksdiff||''||to_date('&indate','mm/dd/yyyy'));
opendates;
LOOP
FETCHdatesintov_dd,v_date;
EXITWHENdates%NOTFOUND;
dbms_output.put_line(v_dd||''||v_date);
ENDLOOP;
closedates;
end;
Reply
Bharani
6June,2014,12:07
ansforq8
WITHcsvAS(
select(to_char(trunc(sysdate,MONTH),MM)level)asMntfromdualwhere
(to_char(trunc(sysdate,MONTH),MM)level)>1connectbylevel<20)
selectadd_months(trunc(sysdate,'MONTH'),csv.Mnt),add_months(trunc(sysdate,'MONTH'),
csv.Mnt)1fromdual,csv
Reply
MVVSSARMA
8July,2014,17:33
planswertomyquery,Ihaveatableemp(empno,login)inmytableanemployeecanlogin
manytimesinaday.Assumeeachemployee4timesloggedintothetablewithemployeeno
11,22,33,44sinceoneweek.NowIwantaquerytolistallemployees11,22,33,44onceperday.
(totalIneedtoget7recordsforeachemployee).
pleasesuggesttheansewr
http://viralpatel.net/blogs/usefuloraclequeries/
10/13
4/18/2015
45UsefulOracleQueries
Reply
Dayanandsm
10July,2014,19:40
pleasetrythis!
selectempno,loginfromempwhereto_Date(login)>=to_date(sysdate7)orderbylogin
desc
Reply
Daniel
11July,2014,15:12
veryusefull!
Ireallyappreciatethat!
Reply
Malshan
16July,2014,10:08
Hi,
Iwanttoselect1st,10thand20thofthemonthbygiving1,10,20astheparameters.istherethea
possibleway?
plzhelp
Reply
Makal
3September,2014,20:51
Thanksforsharingtheabovequeries.veryuseful.
Ineedonequerywhichwillgivemethelastmonthsalarydrawnofeachemployee.Allemployee
lastmonthsalaryisnotsame.Itriedthesame
thebelowqueryworksforuniquerecordbutnotforthelast
select*Fromdemo_ordersa
whereorder_idnotIN(
selectorder_idfromdemo_ordersb
whereb.customer_id=a.customer_idandrownum=1
)
logicallyIwantthe
select*Fromdemo_ordersa
whereorder_idIN(
selectb.order_idfromdemo_ordersb
wherea.customer_id=b.customer_idandrownum=1orderbya.customer_id)
Reply
rkgoud
6November,2014,18:47
veryusefulllookingforwardtoseemuchstufff
Reply
Pugazhendhi_r
17December,2014,7:09
Hicanuplssharemeanyqueriestofindthetablenameifiknowthetableheader.Asimbeginner
unabletofindit
Reply
Arun
24December,2014,10:18
Hi,
Howtofindavalueinapipedelimitervalue.
Forex:AssumethatwehaveacolumnAandB.InAcolumnihavevalueA1andinBcolumni
haveavaluelikeA1|B1|C1|D1.NowihavetosearchA1inBcolumn.Pleasenotethat:AandB
columnsareindifferenttable.
Reply
Jo
http://viralpatel.net/blogs/usefuloraclequeries/
11/13
4/18/2015
45UsefulOracleQueries
Pleasehelpmetooptimizefollowingcodeasitistakingalotoftimeto
11January,2015,23:27
execute
:selectdistinctCust_no_717from(selecta1.cust_no_717,a1.cust_cc_no_717,
a1.cust_long_name_717fromcustomera1wherea1.cust_client_717LIKE%UNIONselect
a2.cust_no_717,a2.cust_cc_no_717,a2.cust_long_name_717FromCustomera2,
alias_connectorwhere(connection_alias_778like%and(connection_status_778=BA)and
connection_cust_no_778=a2.cust_no_717))
Reply
pratikthakar
19January,2015,12:19
kindlyhelpmetofindlastonehourandpreviousdaydatabaseincreasedordecreasedsize
Reply
krishna
11February,2015,6:06
ihavetables
CREATETABLEClasses(
classNameVARCHAR2(20),
typeClassCHAR(2),
countryVARCHAR2(15),
numGunsINT,
boreINT,
displacementINT,
CONSTRAINTpkClassesPRIMARYKEY(className),
CHECK(typeClassIN(bb,bc))
)
CREATETABLEShips
(
shipNameVARCHAR2(20),
shipClassVARCHAR2(20),
launchYrINT,
CONSTRAINTpkShipsPRIMARYKEY(shipName),
CONSTRAINTfkClassesFOREIGNKEY(shipClass)REFERENCESClasses(className)
)
iwantFindforeachclass,theyearwhenthelatestshipofthatclasswaslaunched.Orderthe
resultsbythenameoftheclass.
Reply
Sathishkumar
27March,2015,21:28
Ihaveonedoubtinoracle.Isentonquery.Ineedlastonehourdataonthatquery.
SELECTaction_view.id,
action_view.string_valueASaction,
action_view.userid,
user_info.email,
to_char(to_date(19700101,YYYYMMDD)+(action_view.audittime/86400000),MMDDYYYY
HH24:MI:SS)asaudittime
,
SUBSTR(action_path.string_value,instr(action_path.string_value,cm:,1)+3)ASFileName,
action_path.string_valueASpath
FROMALFDBSPRFSCMA.cisco_audit_entry_action_viewaction_view,
ALFDBSPRFSCMA.cisco_audit_entry_path_viewaction_path,
ALFDBSPRFSCMA.cisco_audit_entry_type_viewtype_view,
ALFDBSPRFSCMA.cisco_view_user_infouser_info
WHEREaction_view.id=action_path.id
ANDaction_view.id=type_view.id
ANDaction_view.userid=user_info.user_id
ANDaction_path.string_valueLIKE(/app:company_home/st:sites/cm:nextgen
edcs/cm:documentLibrary/%)
ANDaction_view.userid!=admin
ANDtype_view.string_value=cs:ciscodoc
ANDaction_view.string_value!=READ
ANDaction_view.audittime
Weareshowingaudittimeformatlikementionedingreencolor.Theyellowcolorconditionshould
belastonehourfromsystime.
Eg:
action_view.audittime>((sysdateto_date(01JAN1970,DDMONYYYY))5)*
(86400000)+to_number(to_char(systimestamp,FF3))butthisisnotworkingproperly.
http://viralpatel.net/blogs/usefuloraclequeries/
12/13
4/18/2015
45UsefulOracleQueries
Reply
LeaveaReply
Youremailaddresswillnotbepublished.Requiredfieldsaremarked*
Name*
Email*
Website
Comment
Note
Topostsourcecodeincomment,use [codelanguage][/code] tag,forexample:
[codejava]Javasourcecodehere[/code]
[codehtml]HTMLhere[/code]
PostComment
Categories
SitePages
Homepage
Struts
Spring
AJAX
PHP
Java
JavaEE
JavaScript
CSS
Database
Web2.0
News
Fun
General
Featured
PlayFramework
Android
FreeMarkerTemplate
HTML5
Aboutviralpatel.net
CommentsFeed
Backtotop
JoinUs
Search
Advertise
PostsFeed
Copyright2015ViralPatel.net.Allrightsreserved:)
http://viralpatel.net/blogs/usefuloraclequeries/
13/13