Charan SQL

Embed Size (px)

Citation preview

  • 8/12/2019 Charan SQL

    1/31

    O R A C LE S Q L- A N INTR O D U CT IO N

    TABLE OF CONTENTS

    1. D ATAMO D EL S .. 22. ORACL E ARCH ITECT U RE . 33. SQ L . 7

    3.1 SQL D at a types...73.2 D at a De fin itio n Lan!ae..."3.3 D at a Ma n ip! #atio n Lan!ae..1$3.% Co n st & ain ts . ..1 23.' ( !n ) tio n s . ..1 %3.* + oin s .. .2 33.7 ,& itin S!-!e&ies..273." D ata - as e O-/e)ts...20

    %. AE DE 4 A .. .3'

    * All SQL statements marked in blue

    * All SQL keywrds marked in CA!S blue

    * T"e #i and $%& 'eatures marked in red

    * Su&&estins( )mments and ueries )an be +sted t s "a rad , ba lle + u y a " .) .in

    1

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 8/12/2019 Charan SQL

    2/31

    $. DATA /ODELS0

    What is a database:Collection of information in a structural and systematic manner.

    Why to use a database:In order to store and retrieve information in a fast and efficient manner.

    Understand your database model:There are basically two types of database models. OLTP :

    OnLine Transaction Processin!. Used for hi!h volume transactions. "ormali#ed data with more relations. $any %oins& few inde'es. (enerally used by the clerical !roup. OL)P: OnLine )nalytical Pro!rammin!.

    Used for historical analysis. *enormali#ed data with less relations +starschema,.

    -ew %oins& many inde'es. (enerally used by the mana!ement !roup.

    ased on the above pointers& fi!ure out which type of database model would youli/e to implement which best suits your re0uirement.

    2

  • 8/12/2019 Charan SQL

    3/31

    STRUCTURED QUERY LANGUAGE (SQL)

    12L is a lan!ua!e that provides an interface to relational database systemso that the user can retrieve information from the database& perform somemanipulations and store data on the database.

    3.1 *atatypes:

    1ome of the datatypes in Oracle are listed below.

    *ata type *escription *efault len!th"U$34 1tores inte!er as well as

    decimal values38

    I"T3(34 Can store only inte!ervalues.

    38

    C5)4 Character strin!. -i'edlen!th 2000

    6)4C5)42 Character strin!&variable.

    4000

    *)T3 To store date. *efaultformat is ddmonyy

    9

    TI$31T)$P *ate with timestamp 9 (for millisecs)TI$31T)$P WIT5TI$3 7O"3+8i,

    *ate with timestamp andtime #one

    13

    TI$31T)$P WIT5LOC)L TI$3 7O"3+8i,

    *ate with local time #one 11

    I"T346)L 93)4 TO$O"T5 +8I, Time in years andmonths 5

    I"T346)L *)T3 TO13CO"* +8I,

    Time in days& hours&minutes and seconds

    11

    4)W inary data 2000LO"( 4)W 1ame as raw& si#e

    difference2GB

    LO inary Lar!e O%ect Infinity (from10g)

    -IL3 inary file. Only reference is stores& where

    the ima!e is stored inLO

    Infinity (from10g)

    LO"( Character data. 2GBCLO Character lar!e ob%ect Infinity (from

    10g)

    I")49 -LO)T +;!, 30uivalent to

  • 8/12/2019 Charan SQL

    4/31

    3.2 *ata *efinition Lan!ua!e +**L,:

    *ata *efinition Lan!ua!e is used to create& modify and dropdatabase ob%ects. )n ob%ect in a database is nothin! but a table& tablespace&

    procedure& function& tri!!er etc=We will discuss about ob%ects in the latersections.

    **L primarily consists of the followin! commands- C43)T3- )LT34- T4U"C)T3- 43")$3- *4OP- -L)15)C>+;!,- PU4(3+;!,- CO$$3"T

    In the followin! e'amples we will only see the synta' for T)L31.

    a, C43)T3:Creates a tableCRE!E !B"E #t$%le&n$me' (#col1' #$t$&tye1'* #col2'#$t$&tye2'+),If the table contains many records& it can be partitioned dependin! upon someran!e.

    CRE!E !B"E #t$%le&n$me' - -E"EC! #col&n$mes' R/#src&t$%le'

    Creates a table based on some other tables. The column names can berenamed in the new table as well.

    b, )LT34: )lter the table structure.

    "!ER !B"E #t$%le&n$me' (#col&n$me' #$t$&tye'),)dds the new column to the table.

    "!ER !B"E #t$%le&n$me' REE C/" #ol&col&n$me' !/#ne&col&n$me',

    4enames a column in the table.

    "!ER !B"E #t$%le&n$me' R/ C/"(#col&n$me'),*rops a column from the table.

    "!ER !B"E #t$%le&n$me' R/ (#col1'* #col2'+),*rops multiple columns from the table

    8

  • 8/12/2019 Charan SQL

    5/31

    "!ER !B"E #t$%le&n$me' -E! -E C/" #col&n$me',1ets a table as unused temporarily. This is an intermediate state where thecolumn is present in the table but nobody can use the column. It is li/elo!ically droppin! the column from the table. This can be used for variousreasons li/e chec/in! whether there is no effect with the column drop or tosave time and drop later.

    "!ER !B"E #t$%le&n$me' -E! -E (#col1'* #col2'* +),1et a set of columns unused to!ether.

    "!ER !B"E #t$%le&n$me' R/ -E C/"-,*rops the unused columns forever.

    c)!RC!E6 eletes $ll recors from t7e t$%le.

    !RC!E !B"E #t$%le&n$me'

    - *oesn?t push data into the U"*O datafile& hence cannot rollbac/.- Cannot use a where clause with T4U"C)T3& should delete all columns.- The table structure is as it is& only the records are deleted.

    d, 43")$3: 4enames a table.

    REE #ol&t$%le&n$me' !/ #ne&t$%le&n$me'

    e, *4OP: *rops a table from the database.

    R/ !B"E #t$%le&n$me'Till Oracle 9I& any table that was dropped would have been completely deletedand can be brou!ht bac/ only throu!h the recovery process. ut from ;!&when a table is dropped it !oes into the recycle bin from where it can befetched later.

    R/ !B"E #t$%le&n$me' C-CE C/-!RI!-*eletes all references +forei!n /ey, and then drops table.

    R/ !B"E #t$%le&n$me' RGE (10g)*rops the table forever.

    f, -L)15)C>(10g,: 4etrieves the dropped table from the 4ecycle in.

    "-BC #recycle%in&n$me' !/ BE/RE R/ REE !/#ne&t$%le&n$me'

    9

  • 8/12/2019 Charan SQL

    6/31

    We should /now which version of the table we want to retrieve from the4ecycle in as the same table can be dropped number of times. The only wayto retrieve from the 4ecycle in is throu!h the table name in the 4ecycle in.

    !, PU4(3+;!,: *eletes the table from the 4ecycle in.

    RGE :: !B"E #t$%le&n$me' ; IE< #ine=&n$me'>;: REC?C"EBI ; B@REC?C"EBI >; !B"E-CE#t$%les$ce'A -ER #sern$me' > ,

    With the T).L3 or I"*3@ /eyword& you can choose a sin!le table or inde'nameWith the U134 /eyword& you can pur!e every copies of the ob%ect for thespecified userwith the 43C9CL3.I" /eyword& you pur!e the current userAs recycle bincontent

    With the *.)B43C9CL3.I" /eyword& you can pur!e the whole content of therecycle bin +must have the 191*) system privile!e,with the T).L31P)C3 /eyword& you could pur!e all the ob%ects residin! in thespecified tablespace from the recycle bin

    )s of now& only the tables are stored in the 4ecycle in upon bein! dropped.

    h, CO$$3"T: Comment on a table.

    C/E! / !B"E #t$%le&n$me' I- #comments'

    Comment on a table.

    C/E! / C/" #t$%le&n$me'.#colmn&n$me' I- #comment'Comment on a specific column of a table

    3.3*ata $anipulation Lan!ua!e +*$L,:

    *ata $anipulation Lan!ua!e& as the name su!!ests& is used tomanipulate data contained in the ob%ects +e.!. tables,.

    a, I"134T: Inserts data into a table.

    I-ER! I!/ #t$%le&n$me' D"E- (#$l1'*#$l2'* +),Inserts all the column values .

    10

  • 8/12/2019 Charan SQL

    7/31

    I-ER! I!/ #t$%le&n$me' (#col1'* #col2'+) D"E-(#$l1'* #$l2'*+),Inserts only selected columns.

    I-ER! I!/ #t$%le&n$me' D"E- (F#col1'* F#col2'*+),

    Insert usin! script. This synta' will allow the user to enter the value atruntime. When we need to runthiscommand many number of times& we can!o for this synta'.

    I-ER! I!/ #t$%le&n$me' -E"EC! #col&n$mes' R/ #sorce&t$%le'Inserts from another table.

    I-ER! ""I!/ #E-!I!I/@!B"E-1' D"E- (#col1'*#col2')I!/ #E-!I!I/@!B"E-2' D"E- (#col1'*#col2')-E"EC! col1* col2 R/ #-/RCE@!B"E',

    Inserts into multiple destinations.

    b, UP*)T3: Updates the column data in a table. Whenever update command ise'ecuted& it loc/s the table on those columns which are specified in the whereclause +if no where clauseis!iven then puts a loc/ on the entire table,.

    !E #t$%le&n$me' -E! #col1' #ne&$l1'* #col2' #ne&$l2' AHERE #conition'Updates the table by settin! the column values to the new values specified inthe 13T clause.

    c, *3L3T3: *eletes the rows from the table. Li/e update& a delete will also holda loc/ on the table on the !iven columns.

    E"E!E AR/ #t$%le&n$me' AHERE #conition'

    d, $34(3+8i,: $er!es the data between two tables. This feature wasintroduced in 8i version but enhanced in ;!. We can achieve both I"134Tand UP*)T3 in a sin!le statement dependin! on some condition.

    ERGE I!/ #est&t$%le' -IG #sorce&t$%le' / #oin&conition'HE !CE !E#erform some " oer$tion'H8E/! !CE !E#erform some " oer$tion'

    11

  • 8/12/2019 Charan SQL

    8/31

    3.4Constraints:

    Constraints are used to impose rules on the data that is bein! stored intothe tables. It mana!es the behavior of data in the table. There are table level

    constraints as well as column level constraints.

    Column level constraints: "OT "ULL U"I2U3 P4I$)49 >39

    C53C> -O43I(" >39

    Constraints are defined at the time of table creation itself. They can also beadded modifiedafter the table has been created& provided the e'istin! data

    in the table is not violatin! any of the constraints. The !eneral synta' fordefinin! a constraint at column level is :

    CRE!E !B"E #t$%le&n$me' (#col1' #$t$&tye1'AC/-!RI! #const&n$me' #const&tye'),)dd a constraint at the column level.

    "!ER !B"E #t$%le&n$me' /I?(#col&n$me' #$t$&tye'AC/-!RI! #const&n$me' #const&tye'),)ddmodify a constraint after the table is created.

    "!ER !B"E #t$%le&n$me' I-B"EJEB"E C/-!RI!#const&n$me'3nabledisable a constraint. This can be done only if the constraint has aname.

    R/ C/!RI! #const&n$me'*rops the CO"1T4)I"T

    " O T "ULL: The column can never hold a "ULL value. While insertin! data inthe table usin! selected columns& be sure to enter data directly or indirectly+throu!h tri!!ers, into the "OT "ULL columns.

    U" I 2 U 3 : "o two rows can have the same data i.e. there are no duplicateentries for this column.

    P4I $ )49 >39: The column is U"I2U3 and "OT "ULL at the same time. )nyrow can be clearly identified in the table usin! the primary /ey. There can beonly one primary /ey in the whole table.

    12

  • 8/12/2019 Charan SQL

    9/31

    C 53 C > : 6alidates the columns at the time of insertin! into the table. If thecondition is not met& raises an error.

    CRE!E !B"E C@!B (-" BER(10*4) CEC -" ' 0)The above e'ample chec/s that the salary is always a positive number.

    - O 4 3 I ( " >39: This constraint has a synta' a little different from the otherconstraints.

    CRE!E !B"E #t$%&n$me'(#col1' #$t$&tye1'* #col2' #$t$&tye2' REERECE- #m$ster&t$%le'(#m$stert$%&Key')A/ E"E!E C-CE J / E"E!E -E! "")

    ) forei!n /ey always references a column in the master table. The column inthe master table should basically be a primary /ey. If the user tries to entersome data in the forei!n /ey column of the child table and that particular datais not present in the master table& then an error is thrown. 1o& we first have toenter value in the master table and then enter the child table data.

    The option O" *3L3T3 C)1C)*3 deletes all the rows+which has the mastertable deleted record, in the child table& if the master table record is deleted.The option O" *3L3T3 13T "ULL will set the column values to "ULL to all

    the rows in the child table& if the master table record is deleted.

    Table level Constraints:When we tal/ about table level constraints& we can apply constraints on D ormore columns as well and when we tal/ about the column level constraint Dmultiple constraints can be applied to a sin!le column. Unless a constraint thatspans over multiple columns is re0uired& it?s always better to !o with thecolumn level constraint. The /eyword CO"1T4)I"T is mandatory for tablelevel constraints.

    The only constraints that can be used at the table are

    C53C> U"I2U3 P4I$)49 >39

    -O43I(" >39

    13

  • 8/12/2019 Charan SQL

    10/31

    The !eneral synta' of the tablelevel constraint isCRE!E !B"E #t$%le&n$me' ( #col1' #$t$&tye1'* #col2'#$t$&tye2' C/-!RI! #const&n$me' #const&tye'

    (#colmns')),

    )!ain& for the forei!n /ey the synta' is differentCRE!E !B"E #t$%le&n$me' (#col1' #$t$&tye1'* #col2'#$t$&tye2'* C/-!RI! #const&n$me' /REIG E? (#col&n$me') REERECE- #sorce&t$%le'(#col&n$me')),

    3.5-unctions:

    nctions

    -ystem efine ser efinenctions fnctions ("J-L")

    -ingle ro fnctions lti ro fnctions

    meric -tring $te Conersion /t7ers

    -unctions play a vital role in 12L. With the use of functions we can !et thedesired output with minimal code.

    -unctions can be broadly divided into two cate!ories E 1ystem defined functionsand user defined functions. The user can use the systemdefined functionsdirectly to !et the desired functionality +defined by the system,. -urther& thesystem defined functions fall into the sin!lerow function +which can be used on asin!le row only, and multirow function +which is used to perform calculations onmultiple rows for a sin!le column,.

    14

  • 8/12/2019 Charan SQL

    11/31

    We will discuss about some of the important functions in each of the cate!ories.Oracle by default provides a dummy table called dual on which we can test allthese functions& these functions can be applied on the user tables columns aswell.

    I. 1I"(L34OW -U"CTIO"1:

    a, "u m e r ic -u n c t io ns: These functions may be applied on the columns with thenumeric datatype +number& inte!er etc=,.

    )1 C3IL -LOO4 $O* 124TPOW34 4OU"* T4U"C (43)T31T L3)1T

    )1: 4eturns the absolute value of a number& i.e. the positive value of anumber.-E"EC! B-(&10) R/ ", JJ RE-"!6 10

    C3IL: 4eturns an inte!er value that is !reater or e0ual to this number.-E"EC! CEI"(10.4) R/ ", JJ RE-"!6 11-E"EC! CEI"(&10.4) R/ ", JJ RE-"!6 &9

    -LOO4: 4eturns an inte!er value that is lesser or e0ual to this number.-E"EC! "//R(10.4) R/ ", JJ RE-"!6 10-E"EC! "//R(&10.4) R/ ", JJ RE-"!6 &11

    $O*: Ta/es D ar!uments. 4eturns the reminder after dividin! the stby theDnd. If Dnd ar!ument is #ero& returns the first ar!ument.-E"EC! /(10*3) R/ ", JJ RE-"!6 1-E"EC! /(&10*3) R/ ", JJ RE-"!6 &1-E"EC! /(10*0) R/ ", JJ RE-"!6 10

    124T: 4eturns the s0uare root of the number.-E"EC! -LR!(9) R/ ", JJ RE-"!6 3

    POW34: Ta/es D ar!uments. 4eturns the value st ar!ument raised to thepower of the Dnd ar!ument.

    -E"EC! /HER(5*2) R/ ", JJ RE-"!6 25

    4OU"*: 4eturns the value rounded to the nearest inte!er.-E"EC! R/(5.3) R/ ", JJ RE-"!6 5-E"EC! R/(5.M) R/ ", JJ RE-"!6 N-E"EC! R/(&5.3) R/ ", JJ RE-"!6 &N-E"EC! R/(&5.M) R/ ", JJ RE-"!6 &5

    15

  • 8/12/2019 Charan SQL

    12/31

    -E"EC! !RC(10.453) R/ ", JJ RE-"!6 10-E"EC! !RC(10.453*1) R/ ", JJ RE-"!6 10.4-E"EC! !RC(121.453*&1) R/ ", JJ RE-"!6 120

    4OU"* can also ta/e a Dnd ar!ument& which specifies the number of decimalstoberounded.-E"EC! R/(5.34M*1) R/ ", JJ RE-"!6 5.3-E"EC! R/(5.34M*2) R/ ", JJ RE-"!6 5.35

    T4U"C: 4eturns the truncated value. It ta/es D ar!uments. The first onebein! the number to truncate and the second one is the number of decimalplaces.

    (43)T31T: 4eturns the !reatest value from the list of values.-E"EC! GRE!E-!(10*5*13) R/ ", JJ RE-"!6 13-E"EC! GRE!E-!(14*O5O*13) R/ ", JJ RE-"!6 14

    L3)1T: 4eturns the least value from the list of values.-E"EC! "E-!(10*5*34) R/ ", JJ RE-"!6 5

    b, 1t rin! -u nct io ns: -unctions applied on 1trin!s.

    I"ITC)P UPP34 LOW34 CO"C)T 1U1T4 I"1T4 C54 )1CII L3"(T5 LT4I$4T4I$ T4I$ 4P)* LP)* T4)"1L)T3

    43PL)C3 4363413

    I"ITC)P: 4eturns a 1trin! that sets the first character of each word to caps.-E"EC! II!C(P7ello H/R"O) R/ ",JJ RE-"!6 ello Horl

    UPP34: 4eturns the 1trin! with all characters in upper case.-E"EC! ER(P7ello orlO) R/ ",JJ RE-"!6 E""/ H/R"

    LOW34: 4eturns the 1trin! with all characters in the lower case.-E"EC! "/HER(PE""/ H/R"O) R/ ",JJ RE-"!6 7ello orl.

    16

  • 8/12/2019 Charan SQL

    13/31

    CO"C)T: Ta/es D ar!uments. Concatenates the first with the second strin!.-E"EC! C/C!(PelloO*OHorlO) R/ ",JJ RE-"!6 ello Horl

    1U1T4: 4eturns a substrin! of a !iven strin!. Ta/es F ar!uments. )r! isthe strin!&ar!Dis the start position from where the substrin! is ta/en andar!F the len!th of the substrin!. If len!th is not !iven then it ta/es all thecharacters till the end of the strin!.-E"EC! -B-!R(Pello HorlO* 1* 4) R/ ",JJ RE-"!6 ell-E"EC! -B-!R(Pello HorlO* 0* 4) R/ ",

    JJ RE-"!6 ell +even if start position is ;& considers as ,-E"EC! -B-!R(Pello HorlO* M) R/ ",JJ RE-"!6 Horl-E"EC! -B-!R(Pello HorlO* &5* 5) R/ ",

    JJ RE-"!6 Horl +if start position is ne!ative& starts from the end of thestrin!,

    I"1T4: 4eturns the position of a substrin! in a 1trin!.I-!R(str1* str2* Ast$rt&os* Anm%er),

    1tr E strin! to be searched for1trD E the substrin!1tartpos E the position from where it searches for the substrin!"umber which occurrence of the substrin!-E"EC! I-!R(Pello HorlO*PlO*0) R/ ",JJRE-"!6 3

    -E"EC! I-!R(Pello HorlO*PlO*0* 2) R/ ",JJ RE-"!6 4

    I"1T4 has been enhanced from ;! to have re!e' for search pattern.REGE

  • 8/12/2019 Charan SQL

    14/31

    L3"(T5: 4eturns the len!th of the 1trin!.-E"EC! "EG!(Pello HorlO) R/ " JJRE-"!611

    LT4I$: Ta/es two ar!uments. The first is the 1trin! and the second ar!ument

    is the character that needs to be trimmed. y default the second ar!ument ista/en as a blan/ character. Trims all the characters+specified, from the lefthand side of the 1trin!.-E"EC! "!RI(P elloO) R/ ", JJ RE-"!6 ello-E"EC! "!RI(PioioelloO*OioO) R/ ",JJ RE-"!6 ello

    4T4I$: 1ame as LT4I$& trims from the ri!hthand side of the 1trin!.-E"EC! R!RI(Pello P) R/ " JJ RE-"!6 ello

    T4I$: Can trim from left or ri!ht or both.!RI(Ale$ing;tr$iling;%ot7 (trim&c7$r) R/ str) y default ta/esboth.

    4P)*: 1omewhat opposite to T4I$ functions. Pads the 1trin! with the !ivencharacter on the ri!ht hand side.R(str* lengt7A* $&str)1tr E ori!inal strin!Len!th E total len!th of strin! after paddin!Padstr E the strin! to pad.-E"EC! R(PelloO* M* PQO) R/ ",JJ RE-"!6 elloQQ

    LP)*: 1ame as 4P)*& pads from the left.

    T4)"1L)T3: *oes a character to character translation.-E"EC! !R-"!E(Pello HorlO* PelO*OK7O) R/ ",JJ RE-"!6 K77o Hor7replaces all Ge? with G/? and all Gl? with Gh?

    43PL)C3: 4eplaces the se0uence with the new se0uenceRE"CE(str* str&to&rel$ce A* rel$cement&str),

    1tr E ori!inal 1trin!1trtoreplace str to be replaced in str.4eplacementstr str to replaceIf no replacement strin! is !iven& replaces by blan/ and trims.

    18

  • 8/12/2019 Charan SQL

    15/31

    -E"EC! RE"CE(Pello HorlO* PellO* PCellO) R/ ",JJ RE-"!6 Cello Horl.-E"EC! RE"CE(Pello HorlO* PellO) R/ ",JJ RE-"!6 o Horl

    4363413: 4everse a 1trin!.-E"EC! REDER-E(Pello HorlO) R/ "JJ RE-"!6 lroH olle

    c, * at e -u nct io ns: -unctions applied on the datatypedate.

    191*)T3 )**B$O"T51 $O"T51B3TW33""3@TB*)9 CU443"TB*)T3 CU443"TBTI$31T)$P191TI$31T)

    $P1311IO"TI$7O"3 *TI$37O"3

    L)1TB*)9 LOC)LTI$31T)$P

    191*)T3: 4eturns the current system date and time on the local database. Ifthe server is on some other system& !ives the date and time of that system.-E"EC! -?-!E R/ ", JJRE-"!6 Crrent $te in t7eef$lt form$t.

    )**B$O"T51: Ta/es D ar!uments. The first ar!ument is a date and the

    second is the number of months to be added to the date. This functionsreturns a date after addin! the !iven date with the number of months.-E"EC! @/!-(P01&&0NO* 4) R/ ",JJRE-"!6 P01&?&0NO

    $O"T51B3TW33": Ta/es two date parameters and !ives the difference ofmonths between the two dates.-E"EC! /!-@BE!HEE(!/@!E(P01&&0NO*O&/&??O)*!/@!E(P01&R&0NO*O&/&??O)) R/ ", JJ RE-"!6 3

    -E"EC! /!-@BE!HEE(!/@!E(P01&R&0NO*O&/&??O)*!/@!E(P01&&0NO*O&/&??O)) R/ ", JJ RE-"!6 3

    "3@TB*)9: Ta/es D ar!uments and returns the nearest future date that fallson the !iven wee/day.E

    19

  • 8/12/2019 Charan SQL

    16/31

    wee/day H1U"*)9$O"*)9TU31*)9W3*"31*)9T5U41*)9-4I*)91)TU 4*)9.-E"EC! E

    L)1TB*)9: 4eturns the last day of the month for the !iven date.-E"EC! "-!@?(!/@!E(P01&&0NO*O&/@??O)) R/", JJ RE-"!6 P31&&0NO

    CU443"TB*)T3+8i,: 4eturns the current date of the Client.-E"EC! CRRE!@!E R/ ",JJ RE-"!6 crrent client $te.

    CU443"TBTI$31T)$P+8i,: (ives the current date with timestamp withtime#one of the client.-E"EC! CRRE!@!IE-! R/ ", JJ RE-"!6 crrent$te it7 timest$m it7 timeSone of t7e client.

    LOC)LTI$31T)$P+8i,: 1imilar to the CU443"TBTI$31T)$P function&but doesn?t return the Time 7one alon! with Timestamp.-E"EC! "/C"!IE-! R/ ",JJ RE-"!6 crrent $te it7 timest$m of t7e client.

    191TI$31T)$P+8i,: 4eturns server timestamp with time#one.-E"EC! -?-!IE-! R/ ",

    1311IO"TI$37O"3+8i,: 4eturn the session?s time#one offset.-E"EC! -E--I/!IET/E R/ " JJ RE-"!6 U05630

    *TI$37O"3+8i,: 4eturns database time#one offset.-E"EC! B!IET/E R/ " JJ RE-"!6 &08600

    )part from the above standard *)T3 functions& there are some special datefunctions too.

    3@T4)CT: 3'tract a value from a date or intervalE; : !IET/E@/R ; !IET/E@I!E >

    20

  • 8/12/2019 Charan SQL

    17/31

    ; : !IET/E@REGI/ ; !IET/E@BBR >R/ : $te@$le ; inter$l@$le > )

    -E"EC! E

    -E"EC! E

    4OU"*: 4ounds the !iven *)T3 to a specific unit of measure.R/(#$te'*#form$t')*ependin! on the formatJ chosen the date is rounded. 3.!. if the format isG93)4? rounds to the year& if the format is $O"T5 then rounds to the monthetc.-E"EC! R/(!/@!E(P02&&200NO*O&/&????O)* ?ER)JJRE-"!6 P01&&200NO-E"EC! R/(!/@!E(P02&-E&200NO*O&/&????O)* ?ER)

    JJRE-"!6 P01&&200MO

    T4U"C: 1ame as the 4OU"*+dateJ&formatJ, function& but truncates thedate.

    d, Co nv ersion -u nct io ns6 Used to convert from one datatype to the other.

    TOBC5)4 TOB*)T3 TOB"U$34 TOB9$I"T346)L TOB*1I"T346)L

    TOBC5)4: Converts a number or a date to a 1trin!.!/@CR(#$le'* A#form$t'* Anls@l$ng$ge)

    6alue E any date or number-ormat E format you want the result to be converted into. 3.!. 93)4& 99&$O"& 88.88 etc..+when formattin! for number 8 represents a value replacedby anynumber;8,-E"EC! !/@CR(89M.M88*O999.9O) R/ "JJ RE-"!6 89M.M-E"EC! !/@CR(sys$te* Vont7 * ????V) R/ "

    JJ RE-"!6 oem%er 25* 200N.

    TOB*)T3: Opposite of TOBC5)4. Ta/es the same number of ar!uments& thefirst ar!ument is a stin!. Converts the 1trin! value to a date.

    TOB"U$34: Converts a 1trin! to a number.

    21

  • 8/12/2019 Charan SQL

    18/31

    e, 1pecial -unctoins: There are some special functions that can be used on mostof thedatatypes.

    *3CO*3: *ecodes a value and substitutes with the new value !iven.EC/E(#col&n$me'*

    #col&$le1'* #rel$ce&$l'*#col&$le2'*#rel$ce&$l'*#ef$lt&$l'),

    1I(": 4eturns if the result of the e'pression is positive& if the result isne!ative and;if e0ual.

    "6L: 4eplaces the "ULL value with the new value.D"(#nll&col'*#rel$ce&$l')

    "6L2(9i): )dvanced feature of "6L.D"2(#nll&col'* #rel$ce&if&not&nll'* #rel$ce&if&nll')4eplaces with the second ar!ument value if the value of first ar!ument is notnull& if null replaces with the third ar!ument value.

    CO)L31C3+8i,: 4eturns the first nonnull e'pression in the listC/"E-CE(#e=&1'*#e=&2'*#e=&3'+.)

    "ULLI-+8i,:""I(#$rg&1'*#$rg&2')If ar! H ar!D HJ 4eturns "ULLIf ar! J ar!D HJ 4eturns ar!

    II. $ULTI4OW -U"CTIO"1:$ultirow functions are functions that can be applied on not one columnof the row& but on all the rows of a column at the same time. These can betermed as the table level functions.

    1U$: )dds the values of all the rows. -or columns with datatype number.-E"EC! -(#col&n$me') R/ ",

    22

  • 8/12/2019 Charan SQL

    19/31

    )6(: -inds the avera!e of all the rows. )!ain this function is for thenumber columns. If a particular column value is "ULL then doesn?tconsider that column for calculatin! the avera!e.-E"EC! DG(#col&n$me') R/ ",

    $)@: 4eturns the ma'imum value amon! a set of values.-E"EC!

  • 8/12/2019 Charan SQL

    20/31

    Oracle Ki %oins: 1imple

  • 8/12/2019 Charan SQL

    21/31

    -E"EC! emno*en$me*n$me R/ em* etHERE em.etno(U) et.etno,

    "ow if we want to display all employee and correspondin! dept details and also

    those deptarments which doesn?t have any employees in it. The leftouter%oin forthis would be

    -E"EC! emno*en$me*n$me R/ em* etHERE em.etno(U) et.etno,

    1 e l f

  • 8/12/2019 Charan SQL

    22/31

    - With the new synta' the developer can !et a clear picture of how thedifferent tables are %oined to each other.

    The synta' for all the new 8i %oins are as follows:

    C4 O 11 < O I " :The cross %oin represents the Cartesian product of two or more tables selectedwithout %oin conditions.

    -E"EC! #cols' R/ #t$%le&1' CR/-- /I #t$%le&2'

    " ) TU 4)L

  • 8/12/2019 Charan SQL

    23/31

    4I( 5T OUT 34 < OI": 1imilar to Ki 4I(5T OUT34

  • 8/12/2019 Charan SQL

    24/31

    C o rr e l a t e d 2ueri es:There is another version of the sub0ueries called correlated 0ueries. )correlated 0uery is a!ain a sub0uery& but we can perform %oins with a

    correlated sub0uery.

    ) few thin!s to /eep in mind about the correlated sub0uery- -irst the outer 0uery is fired and then the inner 0uery- Unli/e the previous e'amples& they can have %oins with the outer

    0uery- )lways use a table alias for the outer 0uery for %oinin! tables.

    3'ample shows a correlated 0uery that returns the last two rows of theemp table-E"EC! W R/ em $ HERE 2 ' (-E"EC! C/!(W) R/em % HERE $.roi # %.roi)

    1calar sub0uery+8i,:) 0uery can be used in place of a column definition.

    3'ample:-E"EC! E* C/!(E.E!/) R/ E*E!H8EREE.E!/(U) E!.E!/ GR/ B? E

    "OW instead of above we can use-E"EC! E* (-E"EC! C/!(W) R/ E HERE

    E.E!/ E!.E!/) R/ E!

    With the scalar sub0uery the system !ives the outer %oin implicitly

    In the similar manner we can use scalar sub0ueries for column definitionsin theW5343and O4*34 clauses too.

    In line6iew:With Inline views& the output of one 0uery will be !iven as the table foranother.Withtheuse of inline views we can simplify comple' 0ueries andreduce the number of %oins.

    With the use of Inline views& we can lessen the number of 0ueries written.Lets ta/e an e'ample where the user wants to see the employee details andthe avera!e salary of the department in which the employee wor/s& in asin!le resultset. This is possible usin! an inline view for the avera!e salarycalculation.

    28

  • 8/12/2019 Charan SQL

    25/31

    -E"EC! .E!/* .-"*.EE* B.DG-" R/ E *(-E"EC! E!/ * DG(-") DG-" R/ E GR/ B?E!/) B HERE .E!/B.E!/ .-"'B.DG-"

    3.8 *atabase Ob%ects

    *atabase ob%ects can be cate!ori#ed into two.- Code ob%ects- *ata ob%ects

    Code ob%ects are ob%ects for which there is no physical data storedseparately& but they act on the data ob%ect?s data and can modify them aswell.

    *ata ob%ects are ob%ects for which physical data is stored and can bemodified throu!h the ob%ects.

    , Table: ) table is the most common ob%ect used in the database. Used tostore the data.+li/e employee name& employee number etc, It is a data ob%ect Can be created altered& modified contents and dropped. We have seen a lot of operations on tables in the previoussections.

    D, 6iew: ) code ob%ect. Contains a 0uery that is precompiled. Can achieve security by hidin! some columns from the user. Can be associated with one or more tables& but not with comple'relations. When the view is created it is parsed and compiled& aftercreatin! a view ifthe underlyin! table structure chan!es +anyalter command e'ecuted on the table, then the view becomesinvalid and needs to be compiled a!ain. If the column in the table is dropped& the view becomespermanently invalid.

    CRE!E A/R RE"CE DIEH #ie&n$me'A#cols' -#select&stmt' AHI! CEC /!I/

    29

  • 8/12/2019 Charan SQL

    26/31

    $a/in! the view valid can be done by any one of the followin!- 4un the view.- $a/e is ready for e'ecution"!ER DIEH #ie&n$me' C/I"E

    *roppin! the view.R/ DIEH #ie&n$me'

    F, 1ynonym: 1ynonyms are code ob%ects They are the alternative names !iven to the database dataob%ects li/e tables etc.. It also has a security feature& as the user doesn?t /now whichtableob%ect heshe is accessin!. Can use short names for lon! ob%ect names

    CRE!E AB"IC -?/? #syn&n$me' /R #o%&n$me'

    y default they are private and can only be used by the owner of theob%ect. If public access is !iven then all can access the synonym+provided they have appropriate privile!es to the ob%ect,

    *roppin! a synonym.R/ AB"IC -?/? #syn&n$me'

    M, 1e0uence: ) data ob%ect Used for auto !eneration of numbersse0nameJ."3@T6)L E !ives the ne't value in the se0uence. i.e.runs the se0uence.se0nameJ.CU446)L E !ives the current value in the se0uence.

    Creatin! a 1e0uenceCRE!E -ELECE #seX&n$me'-!R! HI! #st$rt&$l'

    ICREE!B? #inc&$le'ID"E #min&$l'

  • 8/12/2019 Charan SQL

    27/31

    minval: The minimum value the se0uence can hold. ma'val:The ma'imum value the se0uence can hold C9CL3"OC9CL3: When C9CL3 mode is selected then the se0uence cana!ain start from first if the ma'valueis e'ceeded.-irst the se0uence starts with the startvalJ and is incremented bythe incval each time& when it reaches the ma'val for the ne't cyclestarts with the minval +and not the startval,. If "O C9CL3 isselected then ends on reachin! the ma'value.

    cachevalJ: number of values it can store in the cache.

    )LT34 statement can be used to chan!e the attribute values

    N, Inde':

    Inde'es are one powerful feature that allows you to retrieve data veryfast. It is a data ob%ect.

    When an inde' is created on a table& the system internally createsanother inde' table internally which contains pseudo columnscontainin! the address of each row +sorted on the inde' column,. Theaddress is K characters and stored in the followin! format

    1 & N 6 o%ect IM Y 9 6 file I10 Y 15 6 %locK I1N Y 18 6 seXence

    a, 1imple Inde': ) simple inde' is one that is created on the tablecolumns thatmay have duplicate values.

    CRE!E IE< #ine=&n$me' / #t$%le&n$me' (#col&n$me')

    The above create statement creates an inde' table with theaddresses of rows of the table sorted on the column on which inde'is applied. "ow when the usertriesto fetch data from theunderlyin! table and uses the inde' column& the inde' table is

    parsed and the address for the matched row is fetched andinformation is e'tracted from it. This will eliminate the need toperform a full table scan. We still have to ma/e a !ood desi!ndecision to ma/e it wor/ effectively by !ivin! the ri!ht inde'columns. When there are more of inserts and updates than retrieval& havin! inde'es would not be much effective as every insertupdateon the table would also need an update on the inde' table.

    31

  • 8/12/2019 Charan SQL

    28/31

    b, -unction based Inde': Inde'es can also be created on functions.The inde' columns should not be used in the function.

    CRE!E IE< #ine=&n$me' / #t$%le&n$me'(#fnction')

    c, Uni0ue Inde': Inde'es created on table columns that have uni0uecolumns. When we apply a U"I2U3 or P4I$)49 >39 constrainton any column& implicitly the U"I2U inde' is created for thatcolumn. )lso& when a uni0ue inde' is created on a column& theU"I2U3 constraint is imposed on that column implicitly.

    CRE!E ILE IE< #ine=&n$me' / #t$%le&n$me'(#col&n$me')

    d, itmap Inde': Used when we have low cardinality on a column.

    e.!. a !ender column which has only two values malefemale. Theyare hi!hly compressed structures& which allows faster access.

    CRE!E BI! IE< #ine=&n$me' / #t$%le&n$me'(#colmn&n$me')

    e, 4everse >ey Inde': 4everses the value and stores in the inde'table. -or e'ample& empno of MF is stored as FM.

    CRE!E IE< #ine=&n$me' / #t$%le&n$me'(#colmn&n$me') REDER-E

    , Cluster: *ata ob%ects. 1tores related tables data. The cluster column must be inde'ed.The cluster implementation is as follows

    Table : 3$P

    E/ EE /1 < 10

    2 ? 10

    3 T 20

    32

  • 8/12/2019 Charan SQL

    29/31

    Table D: *3PT

    / E "/C10 I

    20 B

    Cluster on *"O:

    10 I

    < Y 1? Y 2

    20B

    T & 3

    )s it can be fi!ured out from the above e'ample& a cluster stores relatedtables? data to!ether. In the above e'ample a cluster is created on thedepartment number and the cluster table holds all information from therelated tables based on the department number.

    1teps for creatin! a cluster.- Create a cluster on a table column

    CRE!E C"-!ER #clster&n$me'(#col&n$me'#$t$tye') A!B"E-CE #t$%les$ce&n$me'

    - Create Inde' on the clusterCRE!E IE< #ine=&n$me' / C"-!ER #clster&n$me'

    - Create the table !ivin! the cluster nameCRE!E !B"E #t$%&n$me'(#cols') C"-!ER#clster&n$me'(#col&n$me')

    33

  • 8/12/2019 Charan SQL

    30/31

    , *Lin/: Combination of dataob%ect and codeob%ect. Connection between two databases.)llows to access ob%ects on another database.

    Creatin! a databse lin/CRE!E !B-E "I #linK&n$me' C/EC! !/#ser&n$me' IE!IIE B? #$ssor' -IG#%n$me'

    "ow from another database the ob%ects from this database can beaccessed.-E"EC! #cols' R/ #sern$me'.#t$%le&n$me'Z#linK&n$me'

    Usin! a snapshot allows us to !et the copy of the table from theremote database to the local database.

    CRE!E --/! #sn$s7ot&n$me' / #t$%le&n$me'

    34

  • 8/12/2019 Charan SQL

    31/31

    1. A!!ENDI2 - A

    *ata *ictionary tables:1ome of the dictionary tables used in Oracle.

    user_ : objects created in the current user

    schema all_ : objects created by all usersdba_ : objects owned by system

    user_unused_col_tab : unused columns in a table

    user_tab_comments : comments on table/column

    user_constraints : all constraints on tables

    user_cons_columns : constraint columns

    user_objects : status of the user objects

    all_objects : status of all objects

    dba_objects : status of dba objects