Sie sind auf Seite 1von 24

1SQLCONCEPTS

TABLEOFCONTENTS 1. IntroductiontoSQLDML,DDL,DCL,TCL>2 2. Clausesinoracle>5 3. Operatorsinoracle>8 4. Constraintsinoracle>11 5. Differenttypesoffunctionsinoracle(advanced)>14 6. JoinsinOracle>16 7. Views&indexesinoracle>17 8. Triggers>17 9. Cursors>19 10. Storedprocedures>22

2SQLCONCEPTS SQL(StructuredQueryLanguage):Isastandardforaccessingandmanipulatingdatabases. TABLE:Isacollectionofrelatedentriesanditconsistsofcolumnsandrows. SQLdividedinto: 1.DML:(DataManipulationLanguage)>TomanipulateOracledata,youusetheINSERT, UPDATE,DELETE,SELECT,andLOCKTABLEcommands.INSERTaddsnewrowsofdatato databasetables;UPDATEmodifiesrows;DELETEremovesunwantedrows;SELECTretrievesrows thatmeetyoursearchcriteria;andLOCKTABLEtemporarilylimitsaccesstoatable.MERGE UPSERToperation(insertorupdate) 2.DDL:(DataDefinitionLanguage)>statementsareusedtodefinethedatabasestructureor schema.Someexamples: CREATEtocreateobjectsinthedatabase ALTERaltersthestructureofthedatabase DROPdeleteobjectsfromthedatabase TRUNCATEremoveallrecordsfromatable,includingallspacesallocatedfortherecords areremoved COMMENTaddcommentstothedatadictionary RENAMErenameanobject 3.DCL DataControlLanguage(DCL)statements.Someexamples: GRANTgivesuser'saccessprivilegestodatabase REVOKEwithdrawaccessprivilegesgivenwiththeGRANTcommand

4.TCL
TransactionControl(TCL)statementsareusedtomanagethechangesmadebyDMLstatements. Itallowsstatementstobegroupedtogetherintologicaltransactions. COMMITsaveworkdone SAVEPOINTidentifyapointinatransactiontowhichyoucanlaterrollback ROLLBACKrestoredatabasetooriginalsincethelastCOMMIT SETTRANSACTIONChangetransactionoptionslikeisolationlevelandwhatrollback segmenttouse

3SQLCONCEPTS Syntaxfortheabove:DML 1. Deleterow: DELETEFROMtable_nameWHEREsome_column=some_value; 2. Insertvalue: INSERTINTOtable_nameVALUES(value1,value2,value3,...); 3. Update: UPDATE<table_name>SET<column_name>=<value>; 4. Select: SELECT*FROMTab_name; 5. LOCK: LOCKTABLE[schema.]table[options]INlockmodeMODE[NOWAIT] lockmodes:EXCLUSIVE,SHARE,ROWEXCLUSIVE,SHAREROWEXCLUSIVE, ROWSHARE*|SHAREUPDATE*e.g.LOCKTABLEtable1,table2,table3INROW EXCLUSIVEMODE; 6. MERGEORUPSERT: MERGE<hint>INTO<table_name> USING<table_view_or_query> ON(<condition>) WHENMATCHEDTHEN<update_clause> DELETE<where_clause> WHENNOTMATCHEDTHEN<insert_clause> [LOGERRORS<log_errors_clause><rejectlimit<integer|unlimited>]; exampleformergeorupsert: MERGEINTObonusesb USING(SELECTemployee_id,salary,dept_no FROMemployee WHEREdept_no=20)e ON(b.employee_id=e.employee_id) WHENMATCHEDTHEN UPDATESETb.bonus=e.salary*0.1 DELETEWHERE(e.salary<40000) WHENNOTMATCHEDTHEN INSERT(b.employee_id,b.bonus) VALUES(e.employee_id,e.salary*0.05) WHERE(e.salary>40000); DDL 1.Createtable:CREATETABLEtable_name(column_name1data_type,column_name2 data_type,olumn_name3data_type,....); 2.AlterTable:ALTERTABLEtable_nameADDcolumn_namedatatype; ALTERTABLEtable_nameDROPCOLUMNcolumn_name; ALTERTABLEtable_nameMODIFYCOLUMNcolumn_namedatatype;

4SQLCONCEPTS 3. Droptable: DROPTABLEtable_name; 4. Truncatetable: TRUNCATETABLEtable_name; 5. Rename: RENAMEtabl_nametotanb_name2; 6. Comment: COMMENT ON TABLE Employee IS 'This is a table for Employee.'; (-- and /* */ are used for commenting a line in oracle)

DCL 1. GRANT :2. REVOKE:TCL 1. Set Transaction :set transaction read only;
set transaction read write; set transaction isolation level serializable; set transaction isolation level read committed; set transaction use rollback segment some_rollback_segment; set transaction name some_name;

grant privileges on object to user; revoke privileges on object from user;

2. Save point example using commit and rollback insert into emp (empno,ename,sal) values (109,Sami,3000); savepoint a; insert into dept values (10,Sales,Hyd); savepoint b; insert into salgrade values (III,9000,12000); Now if you give rollback to a;

5SQLCONCEPTS

Clausesinoracle 1.OverviewoftheClausesYouCanUseinanEPL(EventProcessiongLanguage)Statement SELECT FROM RETAIN MATCHING WHERE GROUPBY HAVING ORDERBY OUTPUT INSERTINTO WITH RETAIN: AtleastoneRETAINclauseisarequiredintheFROMclause.TheRETAINclause appliestoallstreamsourceslistedintheFROMclausethatprecedesit.Conceptuallyitdefinesa windowofeventdataforeachstreamsourceoverwhichthequerywillbeexecuted.TheRETAIN clausehasthefollowingsyntax:
RETAIN (ALL[EVENTS])| ([BATCHOF] (integer(EVENT|EVENTS))|(time_interval(BASEDONprop_name)*) (WITH[n](LARGEST|SMALLEST|UNIQUE)prop_name)* (PARTITIONBYprop_name)*)

EachaspectoftheRETAINclauseisdiscussedindetailbelow. EgSELECTAVG(price)
FROMStockTickRETAIN1MINUTE

Inthiscase,aseachnewStockTickeventcomesin,againtheaveragepricewouldbecomputed. However,eventsthatarrivedmorethanoneminuteagowouldberemovedfromthewindowwith theaveragepricebeingrecalculatedbasedontheremainingeventsinthewindow. MatchingClause:EitheraMATCHINGoraFROMclausemustappearinanEPLstatement.The MATCHINGclauseisanalternatemechanismfordeterminingwhicheventsareusedbytheEPL statement.Itallowsforthedetectionofaseriesofoneormoreeventsoccurringthatsatisfiesa specifiedpattern.Patternexpressionsconsistofreferencestostreamsseparatedbylogicaloperators suchasAND,OR,andFOLLOWED BYtodefinethesequenceofeventsthatcomposethepattern. YoumayincludeanoptionalRETAINclause,asspecifiedinRETAIN,todefinethecharacteristics

6SQLCONCEPTS ofthewindowcontainingthematchedevents.TheMATCHINGclauseexecutespriortotheWHERE orHAVINGclauses. TheMATCHINGclausesyntaxisasfollows:


MATCHINGpattern_expression[RETAINretain_clause]

withpattern_expressionhavingthefollowingsyntax:
[NOT|EVERY]stream_expression ((AND|OR|[NOT]FOLLOWEDBY)stream_expression)* [WITHINtime_interval]

YoucanusetheNOToperatortodetecttheabsenceofaneventandtheEVERYoperatortocontrol howpatternmatchingcontinuesafteramatch.Thestream_expressionisastreamsource nameoptionallyboundtoavariableandfilteredbyaparenthesizedexpression:


stream_expression:[var_name:=]stream_name[(filter_expression)]

Alternatively,astream_expressionmayitselfbeapattern_expressionallowingfor arbitrarilycomplexnestingofexpressions: Thevar_nameisboundtotheeventobjectoccurringthattriggersthematch.Itmaybereferenced asanyothereventpropertyinfilterexpressionsthatfollowaswellasinotherclausessuchasthe SELECTandWHEREclauses.Thestream_namemayoptionallybefollowedbyaparenthesized expressiontofilterthematchingeventsofthattype.Theexpressionactasapreconditionforevents toenterthecorrespondingwindowandhasthesamesyntaxasaWHEREclauseexpression. Previouslyboundvariablesmaybeusedwithintheexpressiontocorrelatewithalreadymatched events. Thetime_intervalisatimeintervalasspecifiedinSpecifyingTimeIntervalthatfollowsthe optionalWITHINkeywordtodeterminehowlongtowaitbeforegivinguponthepreceding expressiontobemet. IntheexamplebelowwelookforRFIDEventeventwithacategoryof"Perishable"followed byanRFIDErrorwithin10secondswhoseidmatchestheIDofthematchedRFIDEvent object.
SELECT* MATCHINGa:=RFIDEvent(category="Perishable") FOLLOWEDBYRFIDError(id=a.id)WITHIN10seconds RETAIN1MINUTE

Thefollowingsectionsdiscussthesyntax,semantics,andadditionaloperatorsavailableinthe MATCHINGclausetoexpresstemporalconstraintsforpatternmatching. WTHCLAUSE:WecanalsousetheSQL99WITHclauseinsteadoftemporarytables.The OracleSQLWITHclausewillcomputetheaggregationonce,giveitaname,andallowusto referenceit(maybemultipletimes),laterinthequery. TheSQL99WITHclauseisveryconfusingatfirstbecausetheSQLstatementdoesnotbegin withthewordSELECT.Instead,weusetheWITHclausetostartourSQLquery,definingthe aggregations,whichcanthenbenamedinthemainqueryasiftheywererealtables:

7SQLCONCEPTS

WITH subquery_name AS (the aggregation SQL statement) SELECT (query naming subquery_name); OUTPUT CLAUSE:- TheOUTPUTclauseisoptionalinEPLandisusedtocontrolorstabilizetherateatwhich eventsareoutput.Forexample,thefollowingstatementbatchesoldandneweventsandoutputsthemattheendofevery 90secondinterval. SELECT* FROMStockTickEventRETAIN5EVENTS OUTPUTEVERY90SECONDS

Hereisthesyntaxforoutputratelimiting:
OUTPUT[ALL|((FIRST|LAST)[number]]EVERYnumber[EVENTS|time_unit]

where
time_unit:MIN|MINUTE|MINUTES|SEC|SECOND|SECONDS|MILLISECONDS|MS INSERTINTOCLAUSE:TheINSERT INTOclauseisoptionalinEPL.Thisclausecanbespecifiedtomakethe resultsofastatementavailableasaneventstreamforuseinfurtherstatements.Theclausecanalsobeusedtomerge multipleeventstreamstoformasinglestreamofevents. INSERTINTOCombinedEvent SELECTA.customerIdAScustId,A.timestampB.timestampASlatency FROMEventAA,EventBBRETAIN30MIN WHEREA.txnId=B.txnId

TheINSERT INTOclauseintheabovestatementgenerateseventsoftypeCombinedEvent. EachgeneratedCombinedEventeventhastwoeventpropertiesnamedcustIdandlatency. Theeventsgeneratedbytheabovestatementcanbeusedinfurtherstatements.Forexample,the statementbelowusesthegeneratedevents.


SELECTcustId,SUM(latency) FROMCombinedEventRETAIN30MIN GROUPBYcustId

TheINSERT INTOclausecanconsistofjustaneventtypealias,orofaneventtypealiasandone ormoreeventpropertynames.ThesyntaxfortheINSERT INTOclauseisasfollows:


INSERT[ISTREAM|RSTREAM]INTOevent_type_alias[(prop_name[,prop_name,[,]])]

TheISTREAM(default)andRSTREAMkeywordsareoptional.Ifneitherkeywordisspecified,the enginesuppliestheinsertstreameventsgeneratedbythestatementtoattachedupdatelisteners.The insertstreamconsistsoftheeventsenteringtherespectivewindow(s)orstream(s).IftheRSTREAM keywordisspecified,theenginesuppliestheremovestreameventsgeneratedbythestatement.The removestreamconsistsoftheeventsleavingtherespectivewindow(s).

8SQLCONCEPTS

Operators in Oracle FOLLOWEDBYOperator

TheFOLLOWED BYtemporaloperatormatchesontheoccurrenceofseveraleventconditionsina particularorder.Itspecifiesthatfirstthelefthandexpressionmustturntrueandonlythenwillthe righthandexpressionbeevaluatedformatchingevents. Forexample,thefollowingpatternlooksforeventAandifencountered,looksforeventB:


AFOLLOWEDBYB

ThisdoesnotmeanthateventAmustimmediatelybefollowedbyeventB.Othereventsmayoccur betweentheeventAandtheeventBandthisexpressionwouldstillevaluatetotrue.Ifthisisnot thedesiredbehavior,usedtheNOToperatorasdescribedinNOTOperator.

ANDOperator
TheANDlogicaloperatorrequiresbothnestedpatternexpressionstoturntruebeforethewhole expressionreturnstrue.InthecontextoftheMATCHINGclause,theoperatormatchesonthe occurrenceofseveraleventconditionsbutnotnecessarilyinaparticularorder. Forexample,thefollowingpatternmatcheswhenbotheventAandeventBarefound:
AANDB

ThepatternmatchesonanysequenceofAfollowedbyBineitherorder.Inaddition,itisnot requiredthataBeventimmediatelyfollowanAeventothereventsmayappearinbetweenthe occurrenceofanAeventandaBeventforthisexpressiontoreturntrue.

OROperator
TheORlogicaloperatorrequireseitheroneoftheexpressionstoturntruebeforethewhole expressionreturnstrue.InthecontextoftheMATCHINGclause,theoperatormatchesonthe occurrenceofeitherofseveraleventconditionsbutnotnecessarilyinaparticularorder. Forexample,thefollowingpatternmatchesforeithereventAoreventB:
AORB

Thefollowingwoulddetectallstockticksthatareeitheraboveacertainpriceoraboveacertain volume.
StockTick(price>1.0)ORStockTick(volume>1000)

NOTOperator
TheNOToperatornegatesthetruthvalueofanexpression.InthecontextoftheMATCHINGclause, theoperatorallowstheabsenceofaneventconditiontobedetected.

9SQLCONCEPTS ThefollowingpatternmatchesonlywhenaneventAisencounteredfollowedbyeventBbutonlyif noeventCwasencounteredbeforeeventB.


(AFOLLOWEDBYB)ANDNOTC

EVERYOperator
TheEVERYoperatorindicatesthatthepatternsubexpressionshouldrestartwhenthesub expressionqualifiedbytheEVERYkeywordevaluatestotrueorfalse.IntheabsenceoftheEVERY operator,animplicitEVERYoperatorisinsertedasaqualifiertothefirsteventstreamsourcefound inthepatternnotoccurringwithinaNOTexpression. TheEVERYoperatorworkslikeafactoryforthepatternsubexpressioncontainedwithin.Whenthe patternsubexpressionwithinitfiresandthusquitscheckingforevents,theEVERYcausesthestart ofanewpatternsubexpressionlisteningformoreoccurrencesofthesameeventorsetofevents. EverytimeapatternsubexpressionwithinanEVERYoperatorturnstruetheenginestartsanew activesubexpressionlookingformoreevent(s)ortimingconditionsthatmatchthepatternsub expression. Let'sconsideranexampleeventsequenceasfollows: A1B1C1B2A2D1A3B3E1A4F1B4 Example EVERY(A FOLLOWEDBYB) Description DetecteventAfollowedbyeventB.AtthetimewhenBoccursthe patternmatches,thenthepatternmatcherrestartsandlooksforeventA again. 1. MatchesonB1forcombination{A1, B1}. 2. MatchesonB3forcombination{A2, B3}. 3. MatchesonB4forcombination{A4, B4} EVERY A FOLLOWED BY B ThepatternfiresforeveryeventAfollowedbyaneventB. 1. MatchesonB1forcombination{A1, B1} 2. MatchesonB3forcombination{A2, B3}and{A3, B3}. 3. MatchesonB4forcombination{A4, B4} EVERY A FOLLOWED BY EVERY B ThepatternfiresforeveryeventAfollowedbyeveryeventB,inother words,allcombinationsofAfollowedbyB. 1. MatchesonB1forcombination{A1, 2. MatchesonB2forcombination{A1, 3. MatchesonB3forcombination{A1, {A3, B3}. 4. MatchesonB4forcombination{A1, B4},and{A4, B4} B1}. B2}. B3},{A2, B3}and B4},{A2, B4},{A3,

Theexamplesshowthatitispossiblethatapatternfiresformultiplecombinationsofeventsthat

10SQLCONCEPTS matchapatternexpression. Let'sconsidertheEVERYoperatorinconjunctionwithasubexpressionthatmatchesthreeevents thatfolloweachother:


EVERY(AFOLLOWEDBYBFOLLOWEDBYC)

ThepatternfirstlooksforeventA.WheneventAarrives,itlooksforeventB.AftereventBarrives, thepatternlooksforeventC.Finally,wheneventCarrivesthepatternmatches.Theenginethen startslookingforeventAagain. AssumethatbetweeneventBandeventCasecondeventA2arrives.Thepatternwouldignorethe A2entirelysinceit'sthenlookingforeventC.Asobservedinthepriorexample,theEVERY operatorrestartsthesubexpressionA FOLLOWED BY B FOLLOWED BY Conlywhenthesub expressionfires. InthenextstatementtheeveryoperatorappliesonlytotheAevent,notthewholesubexpression:
EVERYAFOLLOWEDBYBFOLLOWEDBYC

ThispatternnowmatchesforanyeventAthatisfollowedbyaneventBandtheneventC, regardlessofwhentheeventAarrives.Thiscanoftenbeimpracticalunlessusedincombination withtheAND NOTsyntaxortheRETAINsyntaxtoconstrainhowlonganeventremainsinthe window.

WITHINOperator
TheWITHINqualifieractslikeastopwatch.Iftheassociatedpatternexpressiondoesnotbecome truewithinthespecifiedtimeperioditisevaluatedbytheengineasfalse.TheWITHINqualifier takesatimeperiodasaparameterasspecifiedinSpecifyingTimeInterval. ThispatternfiresifanAeventarriveswithin5secondsafterstatementcreation.
AWITHIN5SECONDS

ThispatternfiresforallAeventsthatarrivewithin5secondintervals. ThispatternmatchesforanyoneAorBeventinthenext5seconds.
(AorB)WITHIN5SECONDS

Thispatternmatchesforanytwoerrorsthathappen10secondswithineachother.
A(status='ERROR')FOLLOWEDBYB(status='ERROR')WITHIN10SECONDS

ThispatternmatcheswhenaStatuseventdoesnotoccurwithin10seconds:
NOTStatusWITHIN10SECONDS LIKEOPERATOR INOPERATOR BETWEENOPERATOR

11SQLCONCEPTS
CONSTRAINTSINORACLE 1.NOTNULL:TheNOTNULLconstraintensuresthatacolumndoesnothaveNULLvalues. createtableeditor (editor_keyvarchar2(9)notnull); 2.UNIQUE:auniqueconstraintdoesn'tallowduplicatevaluesinacolumn. createtableeditor (editor_keyvarchar2(9)unique); 3.DEFAULT:createtablet1 ( id$integernotnull, charcolchardefault'Y', datecoldatedefaultsysdate, strcolvarchar2(30)defaultuser, intcolintegerdefault12 ); insertintot1(id$)values(1); select* fromt1;

4. CHECK:createtabletab_name(pidintnotnull,namevarchar(255)check(pid>0));

5.PRIMARYKEY:Aprimarykeyisasinglefieldorcombinationoffieldsthatuniquely definesarecord.Noneofthefieldsthatarepartoftheprimarykeycancontainanullvalue.Atable canhaveonlyoneprimarykey. Note: InOracle,aprimarykeycannotcontainmorethan32columns. AprimarykeycanbedefinedineitheraCREATETABLEstatementoranALTER TABLEstatement.

UsingaCREATETABLEstatement
ThesyntaxforcreatingaprimarykeyusingaCREATETABLEstatementis: CREATETABLEtable_name (column1datatypenull/notnull, column2datatypenull/notnull, ... CONSTRAINTconstraint_namePRIMARYKEY(column1,column2,.column_n) );

12SQLCONCEPTS Forexample: CREATETABLEsupplier ( supplier_id numeric(10) notnull, supplier_nam varchar2(50) notnull, e contact_name varchar2(50), CONSTRAINTsupplier_pkPRIMARYKEY (supplier_id) );
Using an ALTER TABLE statement

ThesyntaxforcreatingaprimarykeyinanALTERTABLEstatementis: ALTERTABLEtable_name addCONSTRAINTconstraint_namePRIMARYKEY(column1,column2,...column_n);

Forexample: ALTERTABLEsupplier addCONSTRAINTsupplier_pkPRIMARYKEY(supplier_id);

6.FOREIGNKEY:Aforeignkeymeansthatvaluesinonetablemustalsoappearinanother table. Thereferencedtableiscalledtheparenttablewhilethetablewiththeforeignkeyiscalledthe childtable.Theforeignkeyinthechildtablewillgenerallyreferenceaprimarykeyintheparent table. AforeignkeycanbedefinedineitheraCREATETABLEstatementoranALTERTABLE statement.

UsingaCREATETABLEstatement
ThesyntaxforcreatingaforeignkeyusingaCREATETABLEstatementis: CREATETABLEtable_name (column1datatypenull/notnull, column2datatypenull/notnull,

13SQLCONCEPTS ... CONSTRAINTfk_column FOREIGNKEY(column1,column2,...column_n) REFERENCESparent_table(column1,column2,...column_n) );

Forexample: CREATETABLEsupplier ( supplier_id numeric(10) notnull, supplier_nam varchar2(50) notnull, e contact_name varchar2(50), CONSTRAINTsupplier_pkPRIMARYKEY (supplier_id) ); CREATETABLEproducts ( product_id numeric(10) notnull, supplier_id numeric(10) notnull, CONSTRAINTfk_supplier FOREIGNKEY(supplier_id) REFERENCESsupplier(supplier_id) ); Inthisexample,we'vecreatedaprimarykeyonthesuppliertablecalledsupplier_pk.Itconsistsof onlyonefieldthesupplier_idfield.Thenwe'vecreatedaforeignkeycalledfk_supplieronthe productstablethatreferencesthesuppliertablebasedonthesupplier_idfield. Wecouldalsocreateaforeignkeywithmorethanonefieldasintheexamplebelow: CREATETABLEsupplier ( supplier_id numeric(10) notnull, supplier_nam varchar2(50) notnull, e contact_name varchar2(50), CONSTRAINTsupplier_pkPRIMARYKEY(supplier_id, supplier_name) ); CREATETABLEproducts ( product_id numeric(10) notnull, supplier_id numeric(10) notnull,

14SQLCONCEPTS supplier_nam varchar2(50) notnull, e CONSTRAINTfk_supplier_comp FOREIGNKEY(supplier_id,supplier_name) REFERENCESsupplier(supplier_id,supplier_name) ); ORACLENULLVALUES 1. ISNULL:checksforthefieldfornullvalues 2. ISNOTNULL:displaysthefieldwhicharenotnull eg:select*fromtabwherecolISNULL/ISNOTNULL ORACLE AGGREGATE FUNCTIONS 1. avg : - returns average 2. corr:- returns the coefficient of correlation of a set of number pairs. 3. Count:- returns count of rows 4. covar_pop:- calculates the population covariance 5. covar_sample:- calculates the sample covariance 6. rank():- returns the rank of a specified column 7. max():- returns maximum value 8. min() :- returns minuimum value 9. group_id():- assigns number for groups resulted from group by clause 10. variance():- returns variance of a specified field 11. sum():- returns sum of aspecified field. ORACLE STRING FUNCTIONS 1. ASCII :-returns the NUMBER code that represents the specified character. Syntax:- select ascii('specified character') from table_name; 2. Upper Case :- SELECT UPPER('Dan Morgan') FROM dual; 3. Lower Case:- SELECT LOWER('Dan Morgan') FROM dual; 4. initcap:- initial letter capital:- SELECT INITCAP('DAN MORGAN') FROM 5. 6. chr():-The CHR function converts an integer value (or any value that can be implicitly converted to an integer value) into a character. Syntax:- SELECT(CHR(68) || CHR(65) || CHR(78)) FROM dual; 7. COALESCE():returnsthefirstnonnulloccurence 8. Convert:Converts From One Character Set To Another
dual; NLS_UPPER (national or native language support)

15SQLCONCEPTS
syntax:selectconvert('Ank)fromdual; 9.concat():selectcol1||col2concatenationfromtab; 10. dump:Returns a VARCHAR2 value containing the datatype code, length in bytes, and internal representation of a value suntax:SELECT table_name, DUMP(table_name) DMP FROM user_tables;

11. INSTR():nstrfunctionreturnsthelocationofasubstringinastring. Syntax:SELECTinstr('Techonthenet','e')fromTAB;wouldreturn2;thefirstoccurrenceof 'e' SELECTinstr('Techonthenet','e',1,1)fromTAB;wouldreturn2;thefirstoccurrenceof'e' SELECTinstr('Techonthenet','e',1,2)fromTABwouldreturn11;thesecondoccurrenceof'e' SELECTinstr('Techonthenet','e',1,3)fromTABwouldreturn14;thethirdoccurrenceof'e' 12. SUBSTR():SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR
FROM dual;

syntax:SELECT name, TREAT(VALUE(p) AS employee_t).salary SALARY FROM persons p;

13. LENGTH():selectlength('vineet')fromdual; 14. LPAD():selectLPAD('VINEET,25,'V')fromdual; 15. LTRIM():SELECT'>'||LTRIM('DanMorgan')||'<'FROMdual; 16. reverse():selectreverse('vineet')fromdual; 17. TREAT():Changes The Declared Type Of An Expression

18. vsize():returnsbitesizesyntax:selectvsize('vineet')fromdual; 19. translate():SELECT TRANSLATE('So What', 'ah', 'e') 20. 21.
ORACLEDATEFUNCTIONS: FROM dual; replace():SELECT REPLACE('So What', 'o', 'ay') FROM dual; concat():- select concat('vin','eet') from dual;

1. sysdate:selectsysdatefromdual;displayscurrentdate 2. +AND:selectsysdate+/1fromdual;addsorsubsadayfromcurrentday. 3. ADD_MONTHS:SELECT add_months(SYSDATE, 2) FROM dual;


SELECT add_months(TO_DATE('27-JAN-2007'), 1) FROM dual;

4. LAST_DAY: Returns The Last Date Of A Month:- select last_day(datecol1) from 5. 6. 7. 8. 9.


tab_name; least:- returns earliest day SELECT LEAST(datecol1, datecol2, datecol3) FROM t; interval: SELECT TO_CHAR(SYSDATE + INTERVAL '10' MINUTE, 'HH:MI:SS') FROM dual;toadjustortoaddtieminterval Greatest :tofindgreatestofdates:SELECT GREATEST(datecol1, datecol2, datecol3) FROM t; Months_between:SELECT MONTHS_BETWEEN(SYSDATE-365, SYSDATE+365) FROM dual; next_day():SELECT NEXT_DAY(SYSDATE, 'FRI') FROM dual;

16SQLCONCEPTS 10. TRUNC:- INSERT INTO t (datecol) VALUES (TRUNC(SYSDATE)); convert date
at midnight 11. to_date() the to_date function converts a string to a date. to_date('2003/07/09', 'yyyy/mm/dd') 12. to_char():- converts to characters to_char(sysdate, 'yyyy/mm/dd'); would return '2003/07/09' to_char(sysdate, 'Month DD, YYYY'); would return 'July 09, 2003'

JOINS IN ORACLE

Thisjoinreturnsrowswhenthereisatleastonematchinboththetables. Select*fromtablet1innerjointablet2ont1.col1=t2.col1
1. INNER JOIN 2. LEFT OUTER JOIN This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values. Select * from table t1 LEFT outer join table t2 ON t1.col1=t2.col1 3.RIGHT OUTER JOIN This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

Select * from table t1 RIGHT outer join table t2 ON t1.col1=t2.col1; 4.FULLOUTERJOINThis join combines left outer join and right after join. It returns row from either table when the conditions are met and returns null value when there is no match.

Select * from table t1 Full outer join table t2 on t1.col1=t2.col1; 5. Cross Join:-ThisjoinisaCartesianjointhatdoesnotnecessitateanycondition tojoin.Theresultsetcontainsrecordsthataremultiplicationofrecordnumberfrom boththetables. Select * from table1,table2; SOME other functions and commands of oracle 1. select * from v$version; --> displays the version of the database we are using 2. cast():- the cast function converts one datatype to another. eg. select cast( '22-Aug-2003' AS varchar2(30) ) from dual; 3. from_tz():-the from_tz function converts a TIMESTAMP value (given a TIME ZONE) to a TIMESTAMP WITH TIME ZONE value. Eg:- select from_tz(TIMESTAMP '2005-09-11 01:50:42', '5:00') from

17SQLCONCEPTS dual; out put :- 11-Sep-05 01.50.42.000000 AM +05:00 4. NULLIF():- the NULLIF function compares expr1 and expr2. If expr1 and expr2 are equal, the NULLIF function returns NULL. Otherwise, it returns expr1. ThesyntaxfortheNULLIFfunctionis: NULLIF(expr1,expr2) EG- NULLIF(12, 12) would return NULL NULLIF(12, 13) would return 12 NULLIF('apples', 'apples') would return NULL 5. user():- user function returns the user_id from the current Oracle session. Eg:- select user into parm_user_ID from dual; 6. cardinality():-the cardinality function returns the number of elements in a nested table. EG: select supplier_id, cardinality(location) from suppliers; 7. UID():- he uid function returns the id number for a user's session (the user who is currently logged in). EG:-select uidinto parm_uid from dual; 8. ceil(): - ceil(32.65) would return 33. 9. floor():- floor(5.9) would return 5 10. extract():- extract(YEAR FROM DATE '2003-08-22') would return 2003 VIEWS & INDEXES IN ORACLE VIEW:- A view is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. Syntax:- CREATE VIEW view_emp AS SELECT empid FROM emp; INDEXES:- An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. syntax:-CREATE INDEX supplier_idx ON supplier (supplier_name);

TRIGGERS Triggerisablockofcodethatfiresorexecutesinresponsetoaspecificevent. Generalusesoftriggers

18SQLCONCEPTS

1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

Automaticallygeneratedesiredcolumnvalues preventinvalidtransactions enforcecomplexsecurityauthorization enforcereferentialintegrityacrossnodesindistributeddatabase enforcecomplexbusinessrules maintainsyncronoustablereplicates provideauditing gatherstaticsontableaccess modifytabledatawhenDMLstatementsareissuedagainstviews publishinformationaboutdatabaseevents

PARTSOFTRIGGERS 1. Atriggeringeventorstatement 2. Atriggerrestriction 3. Atriggeraction Syntaxoftrigger


CREATE[ORREPLACE]TRIGGER<trigger_name> {BEFORE|AFTER}{INSERT|DELETE|UPDATE}ON<table_name> [REFERENCING[NEWAS<new_row_name>][OLDAS<old_row_name>]] [FOREACHROW[WHEN(<trigger_condition>)]] BEGIN <trigger_body> END; Exampleoftrigger:CREATETRIGGERtrig1 AFTERINSERTONT4 REFERENCINGNEWASnewRow FOREACHROW WHEN(newRow.a<=10) BEGIN INSERTINTOT5VALUES(:newRow.b,:newRow.a); ENDtrig1; Example2: CREATE TRIGGER PersonCheckAge AFTER INSERT OR UPDATE OF age ON Person FOR EACH ROW BEGIN IF (:new.age < 0) THEN

19SQLCONCEPTS
RAISE_APPLICATION_ERROR(-20000, 'no negative age allowed'); END IF; END; DisablingTriggers Todisableorenableatrigger: alter trigger <trigger_name> {disable|enable}; DroppingTriggers Todropatrigger: droptrigger<trigger_name>; ViewingDefinedTriggers Toviewalistofalldefinedtriggers,use: select trigger_name from user_triggers; Formoredetailsonaparticulartrigger: selecttrigger_type,triggering_event,table_name,referencing_names,trigger_body fromuser_triggers wheretrigger_name='<trigger_name>'; youcanseetheerrormessagesbytyping showerrorstrigger<trigger_name>;

CURSORSINORACLE Acursorisamechanismbywhichyoucanassignanametoa"selectstatement"andmanipulatethe informationwithinthatSQLstatement.

Cursorsarecategorizedintothefollowingtopics:

DeclareaCursor OPENStatement FETCHStatement CLOSEStatement 1.Declarecursor:Thebasicsyntaxforacursorwithoutparametersis:


CURSORcursor_name IS

20SQLCONCEPTS
SELECT_statement; Example:CURSORc1 IS SELECTcourse_number fromcourses_tbl wherecourse_name=name_in; Belowisafunctionthatusesthiscursor. CREATEORREPLACEFunctionFindCourse (name_inINvarchar2) RETURNnumber IS cnumbernumber; CURSORc1 IS SELECTcourse_number fromcourses_tbl wherecourse_name=name_in; BEGIN openc1; fetchc1intocnumber; ifc1%notfoundthen cnumber:=9999; endif; closec1; RETURNcnumber;END;

2.Openstatement:ThebasicsyntaxtoOPENthecursoris:
OPENcursor_name; Forexample,youcouldopenacursorcalledc1withthefollowingcommand: OPENc1; BelowisafunctionthatdemonstrateshowtousetheOPENstatement: CREATEORREPLACEFunctionFindCourse (name_inINvarchar2) RETURNnumber IS cnumbernumber;

21SQLCONCEPTS
CURSORc1 IS SELECTcourse_number fromcourses_tbl wherecourse_name=name_in; BEGIN openc1; fetchc1intocnumber; ifc1%notfoundthen cnumber:=9999; endif; closec1; RETURNcnumber; END;

3.Fetchcursor:ThebasicsyntaxforaFETCHstatementis: FETCHcursor_nameINTO<listofvariables>;

Forexample,youcouldhaveacursordefinedas: CURSORc1 IS SELECTcourse_number fromcourses_tbl wherecourse_name=name_in; Thecommandthatwouldbeusedtofetchthedatafromthiscursoris: FETCHc1intocnumber; Thiswouldfetchthefirstcourse_numberintothevariablecalledcnumber; BelowisafunctionthatdemonstrateshowtousetheFETCHstatement. CREATEORREPLACEFunctionFindCourse (name_inINvarchar2) RETURNnumber IS cnumbernumber; CURSORc1 IS SELECTcourse_number

22SQLCONCEPTS fromcourses_tbl wherecourse_name=name_in; BEGIN openc1; fetchc1intocnumber; ifc1%notfoundthen cnumber:=9999; endif; closec1; RETURNcnumber; END; 4.Closecursor:ThebasicsyntaxtoCLOSEthecursoris: CLOSEcursor_name; Forexample,youcouldcloseacursorcalledc1withthefollowingcommand: CLOSEc1; BelowisafunctionthatdemonstrateshowtousetheCLOSEstatement: CREATEORREPLACEFunctionFindCourse (name_inINvarchar2) RETURNnumber IS cnumbernumber; CURSORc1 IS SELECTcourse_number fromcourses_tbl wherecourse_name=name_in; BEGIN openc1; fetchc1intocnumber; ifc1%notfoundthen cnumber:=9999;

23SQLCONCEPTS endif; closec1; RETURNcnumber; END;

STOREDPROCEDURESINORACLE

Procedureisasubprogramusedtoperformaspecificaction.Aprocedurecontainstwoparts specificationandthebody.ProcedurespecificationbeginswithCREATEandendswithprocedure nameorparameterslist.Proceduresthatdonottakeparametersarewrittenwithoutaparenthesis. ThebodyoftheprocedurestartsafterthekeywordISorASandendswithkeywordEND. Syntax:CREATE[ORERPLACE]PROCEDURE <procedurename>[(parameter1,parameter2..)] [AUTHID(DEFINER|CURRENT_USER]IS|AS [localdeclarations] BEGIN Statements [Exception exceptionhandlers] END; AUTHIDclauseisusedtodecidewhethertheprocedureshouldexecutewithinvoker (currentuserorpersonwhoexecutesit)orwithdefiner(ownerorpersoncreated)rights Example CREATEPROCEDUREMyProc(ENONUMBER) AUTHIDDEFINERAS BEGIN

24SQLCONCEPTS DELETEFROMEMP WHEREEMPNO=ENO; EXCEPTION WHENNO_DATA_FOUNDTHEN DBMS_OUTPUT.PUT_LINE(Noemployeewiththisnumber); END;

Das könnte Ihnen auch gefallen