Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 31

ORACLE SQL- AN INTRODUCTION

TABLE OF CONTENTS

1. DATAMODELS..2 2. ORACLE ARCHITECTURE.3 3. SQL.7 3.1 SQL Data types...7 3.2 Data Definition Lan !a e..." 3.3 Data Manip!#ation Lan !a e..1$ 3.% Const&aints...12 3.' (!n)tions...1% 3.* +oins...23 3.7 ,&itin S!-.!e&ies..27 3." Data-ase O-/e)ts...20 %. A11E2DE3 4 A .. .3'

* All SQL statements marked in blue * All SQL keyw rds marked in CA!S blue * T"e #i and $%& 'eatures marked in red * Su&&esti ns( ) mments and *ueries )an be + sted t s"arad,balle+u-ya" .) .in

$. 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 : On Line 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: On Line )nalytical Pro!rammin!. Used for historical analysis. *e normali#ed data with less relations +star schema,. -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 you li/e to implement which best suits your re0uirement.

STRUCTURED QUERY LANGUAGE (SQL) 12L is a lan!ua!e that provides an interface to relational database system so that the user can retrieve information from the database& perform some manipulations and store data on the database. 3.1 *atatypes: 1ome of the datatypes in Oracle are listed below. *ata type "U$.34 I"T3(34 C5)4 6)4C5)42 *)T3 TI$31T)$P TI$31T)$P WIT5 TI$3 7O"3+8i, TI$31T)$P WIT5 LOC)L TI$3 7O"3+8i, I"T346)L 93)4 TO $O"T5 +8I, I"T346)L *)T3 TO 13CO"* +8I, 4)W LO"( 4)W .LO. .-IL3 *escription 1tores inte!er as well as decimal values Can store only inte!er values. Character strin!. -i'ed len!th Character strin!& variable. To store date. *efault format is dd mon yy *ate with timestamp *ate with timestamp and time #one *ate with local time #one Time in years and months Time in days& hours& minutes and seconds .inary data 1ame as raw& si#e difference .inary Lar!e O.%ect .inary file. Only reference is stores& where the ima!e is stored in .LO. Character data. Character lar!e ob%ect 30uivalent to <ava float. 30uivalent to <ava double. *efault len!th 38 38 2000 4000 9 9 (for millisecs) 13 11 5 11 2000 2GB Infinity (from 10g) Infinity (from 10g) 2GB Infinity (from 10g)

LO"( CLO. .I")49 -LO)T +:;!, .I")49 *OU.L3+:;!,

3.2 *ata *efinition Lan!ua!e +**L,: *ata *efinition Lan!ua!e is used to create& modify and drop database 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 later sections. **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 table CRE !E ! B"E #t$%le&n$me' (#col1' #($t$&ty)e1'* #col2' #($t$&ty)e2'+), If the table contains many records& it can be partitioned dependin! upon some ran!e. CRE !E ! B"E #t$%le&n$me' - -E"EC! #col&n$mes' .R/0 #src&t$%le' Creates a table based on some other tables. The column names can be renamed in the new table as well. b, )LT34: )lter the table structure. "!ER ! B"E #t$%le&n$me' 11(#col&n$me' #($t$&ty)e'), )dds the new column to the table. "!ER ! B"E #t$%le&n$me' RE2 0E C/"302 #ol(&col&n$me' !/ #ne4&col&n$me', 4enames a column in the table. "!ER ! B"E #t$%le&n$me' 1R/5 C/"302(#col&n$me'), *rops a column from the table. "!ER ! B"E #t$%le&n$me' 1R/5 (#col1'* #col2'+), *rops multiple columns from the table

"!ER ! B"E #t$%le&n$me' -E! 323-E1 C/"302 #col&n$me', 1ets a table as unused temporarily. This is an intermediate state where the column is present in the table but nobody can use the column. It is li/e lo!ically droppin! the column from the table. This can be used for various reasons li/e chec/in! whether there is no effect with the column drop or to save time and drop later. "!ER ! B"E #t$%le&n$me' -E! 323-E1 (#col1'* #col2'* +), 1et a set of columns unused to!ether. "!ER ! B"E #t$%le&n$me' 1R/5 323-E1 C/"302-, *rops the unused columns forever. c) !R32C !E6 1eletes $ll recor(s from t7e t$%le. !R32C !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. RE2 0E #ol(&t$%le&n$me' !/ #ne4&t$%le&n$me' e, *4OP: *rops a table from the database. 1R/5 ! B"E #t$%le&n$me' Till Oracle 9I& any table that was dropped would have been completely deleted and 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 be fetched later. 1R/5 ! B"E #t$%le&n$me' C -C 1E C/2-!R I2!*eletes all references +forei!n /ey, and then drops table. 1R/5 ! B"E #t$%le&n$me' 53RGE (10g) *rops the table forever.

f, -L)15.)C>(10g,: 4etrieves the dropped table from the 4ecycle .in. ." -8B C9 #recycle%in&n$me' !/ BE./RE 1R/5 RE2 0E !/ #ne4&t$%le&n$me'

We should /now which version of the table we want to retrieve from the 4ecycle .in as the same table can be dropped number of times. The only way to retrieve from the 4ecycle .in is throu!h the table name in the 4ecycle .in. !, PU4(3+:;!,: *eletes the table from the 4ecycle .in. 53RGE :: ! B"E #t$%le&n$me' ; I21E< #in(e=&n$me'> ;: REC?C"EBI2 ; 1B @REC?C"EBI2 >; ! B"E-5 CE #t$%les)$ce'A 3-ER #Bsern$me' C> , With the T).L3 or I"*3@ /eyword& you can choose a sin!le table or inde' name With the U134 /eyword& you can pur!e every copies of the ob%ect for the specified user with the 43C9CL3.I" /eyword& you pur!e the current userAs recycle bin content With the *.)B43C9CL3.I" /eyword& you can pur!e the whole content of the recycle bin +must have the 191*.) system privile!e, with the T).L31P)C3 /eyword& you could pur!e all the ob%ects residin! in the specified 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/00E2! /2 ! B"E #t$%le&n$me' I- #comments' Comment on a table. C/00E2! /2 C/"302 #t$%le&n$me'.#colBmn&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 to manipulate data contained in the ob%ects +e.!. tables,. a, I"134T: Inserts data into a table. I2-ER! I2!/ #t$%le&n$me' D "3E- (#E$l1'*#E$l2'* +), Inserts all the column values .

10

I2-ER! I2!/ #t$%le&n$me' (#col1'* #col2'+) D "3E(#E$l1'* #E$l2'*+), Inserts only selected columns. I2-ER! I2!/ #t$%le&n$me' D "3E- (F#col1'* F#col2'*+), Insert usin! script. This synta' will allow the user to enter the value at runtime. When we need to run this command many number of times& we can !o for this synta'. I2-ER! I2!/ #t$%le&n$me' -E"EC! #col&n$mes' .R/0 #soBrce& t$%le' Inserts from another table. I2-ER! "" I2!/ #1E-!I2 !I/2@! B"E-1' D "3E- (#col1'*#col2') I2!/ #1E-!I2 !I/2@! B"E-2' D "3E- (#col1'*#col2') -E"EC! col1* col2 .R/0 #-/3RCE@! B"E', Inserts into multiple destinations. b, UP*)T3: Updates the column data in a table. Whenever update command is e'ecuted& it loc/s the table on those columns which are specified in the where clause +if no where clause is !iven then puts a loc/ on the entire table,. 351 !E #t$%le&n$me' -E! #col1' G #ne4&E$l1'* #col2' G #ne4&E$l2' AH8ERE #con(ition'C Updates the table by settin! the column values to the new values specified in the 13T clause. c, *3L3T3: *eletes the rows from the table. Li/e update& a delete will also hold a loc/ on the table on the !iven columns. 1E"E!E A.R/0C #t$%le&n$me' AH8ERE #con(ition'C d, $34(3+8i,: $er!es the data between two tables. This feature was introduced in 8i version but enhanced in :;!. We can achieve both I"134T and UP*)T3 in a sin!le statement dependin! on some condition. 0ERGE I2!/ #(est&t$%le' 3-I2G #soBrce&t$%le' /2 #Ioin& con(ition' H8E2 0 !C8E1 !8E2 #)erform some 10" o)er$tion' H8E2 2/! 0 !C8E1 !8E2 #)erform some 10" o)er$tion'

11

3.4 Constraints: Constraints are used to impose rules on the data that is bein! stored into the 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 be added C modified after the table has been created& provided the e'istin! data in the table is not violatin! any of the constraints. The !eneral synta' for definin! a constraint at column level is : CRE !E ! B"E #t$%le&n$me' (#col1' #($t$&ty)e1' AC/2-!R I2! #const&n$me'C #const&ty)e'), )dd a constraint at the column level. "!ER ! B"E #t$%le&n$me' 0/1I.?(#col&n$me' #($t$&ty)e' AC/2-!R I2! #const&n$me'C #const&ty)e'), )ddCmodify a constraint after the table is created. "!ER ! B"E #t$%le&n$me' 1I- B"EJE2 B"E C/2-!R I2! #const&n$me' 3nableCdisable a constraint. This can be done only if the constraint has a name. 1R/5 C/2!R I2! #const&n$me' *rops the CO"1T4)I"T "OT "ULL: The column can never hold a "ULL value. While insertin! data in the table usin! selected columns& be sure to enter data directly or indirectly +throu!h tri!!ers, into the "OT "ULL columns. U"I2U3: "o two rows can have the same data i.e. there are no duplicate entries for this column. P4I$)49 >39: The column is U"I2U3 and "OT "ULL at the same time. )ny row can be clearly identified in the table usin! the primary /ey. There can be only one primary /ey in the whole table.

12

C53C>: 6alidates the columns at the time of insertin! into the table. If the condition is not met& raises an error. CRE !E ! B"E C89@! B (- " 230BER(10*4) C8EC9 - " ' 0) The above e'ample chec/s that the salary is always a positive number.

-O43I(" >39: This constraint has a synta' a little different from the other constraints. CRE !E ! B"E #t$%&n$me'(#col1' #($t$&ty)e1'* #col2' #($t$& ty)e2' RE.ERE2CE- #m$ster&t$%le'(#m$stert$%&)Key') A/2 1E"E!E C -C 1E J /2 1E"E!E -E! 23"") ) forei!n /ey always references a column in the master table. The column in the master table should basically be a primary /ey. If the user tries to enter some data in the forei!n /ey column of the child table and that particular data is not present in the master table& then an error is thrown. 1o& we first have to enter 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 master table 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 or more columns as well and when we tal/ about the column level constraint D multiple constraints can be applied to a sin!le column. Unless a constraint that spans over multiple columns is re0uired& it?s always better to !o with the column level constraint. The /eyword CO"1T4)I"T is mandatory for table level constraints. The only constraints that can be used at the table are C53C> U"I2U3 P4I$)49 >39 -O43I(" >39

13

The !eneral synta' of the table level constraint is CRE !E ! B"E #t$%le&n$me' ( #col1' #($t$&ty)e1'* #col2' #($t$&ty)e2' C/2-!R I2! #const&n$me' #const&ty)e' (#colBmns')), )!ain& for the forei!n /ey the synta' is different CRE !E ! B"E #t$%le&n$me' (#col1' #($t$&ty)e1'* #col2' #($t$&ty)e2'* C/2-!R I2! #const&n$me' ./REIG2 9E? (#col& n$me') RE.ERE2CE- #soBrce&t$%le'(#col&n$me')),

3.5 -unctions: .Bnctions

-ystem (efine( .Bnctions

3ser (efine( fBnctions (5"J-L")

-ingle ro4 fBnctions

0Blti ro4 fBnctions

2Bmeric

-tring

1$te

ConEersion

/t7ers

-unctions play a vital role in 12L. With the use of functions we can !et the desired output with minimal code. -unctions can be broadly divided into two cate!ories E 1ystem defined functions and user defined functions. The user can use the system defined functions directly to !et the desired functionality +defined by the system,. -urther& the system defined functions fall into the sin!le row function +which can be used on a sin!le row only, and multi row function +which is used to perform calculations on multiple rows for a sin!le column,.

14

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 all these functions& these functions can be applied on the user tables columns as well. I. 1I"(L3 4OW -U"CTIO"1:

a, "umeric -unctions: These functions may be applied on the columns with the numeric datatype +number& inte!er etc=,. ).1 POW34 C3IL 4OU"* -LOO4 T4U"C $O* (43)T31T 124T L3)1T

).1: 4eturns the absolute value of a number& i.e. the positive value of a number. -E"EC! B-(&10) .R/0 13 ", JJ RE-3"!6 10 C3IL: 4eturns an inte!er value that is !reater or e0ual to this number. -E"EC! CEI"(10.4) .R/0 13 ", JJ RE-3"!6 11 -E"EC! CEI"(&10.4) .R/0 13 ", JJ RE-3"!6 &9 -LOO4: 4eturns an inte!er value that is lesser or e0ual to this number. -E"EC! ."//R(10.4) .R/0 13 ", JJ RE-3"!6 10 -E"EC! ."//R(&10.4) .R/0 13 ", JJ RE-3"!6 &11 $O*: Ta/es D ar!uments. 4eturns the reminder after dividin! the :st by the Dnd. If Dnd ar!ument is #ero& returns the first ar!ument. -E"EC! 0/1(10*3) .R/0 13 ", JJ RE-3"!6 1 -E"EC! 0/1(&10*3) .R/0 13 ", JJ RE-3"!6 &1 -E"EC! 0/1(10*0) .R/0 13 ", JJ RE-3"!6 10 124T: 4eturns the s0uare root of the number. -E"EC! -LR!(9) .R/0 13 ", JJ RE-3"!6 3 POW34: Ta/es D ar!uments. 4eturns the value :st ar!ument raised to the power of the Dnd ar!ument. -E"EC! 5/HER(5*2) .R/0 13 ", JJ RE-3"!6 25 4OU"*: 4eturns the value rounded to the nearest inte!er. -E"EC! R/321(5.3) .R/0 13 ", JJ RE-3"!6 5 -E"EC! R/321(5.M) .R/0 13 ", JJ RE-3"!6 N -E"EC! R/321(&5.3) .R/0 13 ", JJ RE-3"!6 &N -E"EC! R/321(&5.M) .R/0 13 ", JJ RE-3"!6 &5

15

4OU"* can also ta/e a Dnd ar!ument& which specifies the number of decimals to be rounded. -E"EC! R/321(5.34M*1) .R/0 13 ", JJ RE-3"!6 5.3 -E"EC! R/321(5.34M*2) .R/0 13 ", JJ RE-3"!6 5.35 T4U"C: 4eturns the truncated value. It ta/es D ar!uments. The first one bein! the number to truncate and the second one is the number of decimal places. -E"EC! !R32C(10.453) .R/0 13 ", JJ RE-3"!6 10 -E"EC! !R32C(10.453*1) .R/0 13 ", JJ RE-3"!6 10.4 -E"EC! !R32C(121.453*&1) .R/0 13 ", JJ RE-3"!6 120 (43)T31T: 4eturns the !reatest value from the list of values. -E"EC! GRE !E-!(10*5*13) .R/0 13 ", JJ RE-3"!6 13 -E"EC! GRE !E-!(14*O5O*13) .R/0 13 ", JJ RE-3"!6 14 L3)1T: 4eturns the least value from the list of values. -E"EC! "E -!(10*5*34) .R/0 13 ", JJ RE-3"!6 5 b, 1trin! -unctions: -unctions applied on 1trin!s. I"ITC)P I"1T4 4T4I$ 43PL)C3 UPP34 C54 T4I$ 4363413 LOW34 )1CII 4P)* CO"C)T L3"(T5 LP)* 1U.1T4 LT4I$ T4)"1L)T3

I"ITC)P: 4eturns a 1trin! that sets the first character of each word to caps. -E"EC! I2I!C 5(P7ello H/R"1O) .R/0 13 ", JJ RE-3"!6 8ello Horl( UPP34: 4eturns the 1trin! with all characters in upper case. -E"EC! 355ER(P7ello 4orl(O) .R/0 13 ", JJ RE-3"!6 8E""/ H/R"1 LOW34: 4eturns the 1trin! with all characters in the lower case. -E"EC! "/HER(P8E""/ H/R"1O) .R/0 13 ", JJ RE-3"!6 7ello 4orl(.

16

CO"C)T: Ta/es D ar!uments. Concatenates the first with the second strin!. -E"EC! C/2C !(P8elloO*OHorl(O) .R/0 13 ", JJ RE-3"!6 8ello Horl( 1U.1T4: 4eturns a sub strin! of a !iven strin!. Ta/es F ar!uments. )r!: is the strin!& ar!D is the start position from where the sub strin! is ta/en and ar!F the len!th of the sub strin!. If len!th is not !iven then it ta/es all the characters till the end of the strin!. -E"EC! -3B-!R(P8ello Horl(O* 1* 4) .R/0 13 ", JJ RE-3"!6 8ell -E"EC! -3B-!R(P8ello Horl(O* 0* 4) .R/0 13 ", JJ RE-3"!6 8ell +even if start position is ;& considers as :, -E"EC! -3B-!R(P8ello Horl(O* M) .R/0 13 ", JJ RE-3"!6 Horl( -E"EC! -3B-!R(P8ello Horl(O* &5* 5) .R/0 13 ", JJ RE-3"!6 Horl( +if start position is ne!ative& starts from the end of the strin!, I"1T4: 4eturns the position of a sub strin! in a 1trin!. I2-!R(str1* str2* Ast$rt&)osC* AnBm%erC), 1tr: E strin! to be searched for 1trD E the sub strin! 1tart pos E the position from where it searches for the sub strin! "umber which occurrence of the sub strin! -E"EC! I2-!R(P8ello Horl(O*PlO*0) .R/0 13 ", JJRE-3"!6 3 -E"EC! I2-!R(P8ello Horl(O*PlO*0* 2) .R/0 13 ", JJ RE-3"!6 4 I"1T4 has been enhanced from :;! to have re!e' for search pattern. REGE<5@I2-!R(#str'* #)$ttern&se$rc7&str'* #st$rt&)os'* #occBrrence'* #cBrr or ne=t'* #c$se') Curr or ne't: !iven the current position or the ne't position. Case: case sensitive or insensitive C54: 4eturns the character value for the ascii number -E"EC! C8R(N5) .R/0 13 ", JJ RE-3"!6 P O )1CII: The opposite of C54 function. 4eturns the )1CII value for the character. -E"EC! -CII(P O) .R/0 13 ", JJ RE-3"!6 N5

17

L3"(T5: 4eturns the len!th of the 1trin!. -E"EC! "E2G!8(P8ello Horl(O) .R/0 13 " JJRE-3"!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 is ta/en as a blan/ character. Trims all the characters+specified, from the left hand side of the 1trin!. -E"EC! "!RI0(P 8elloO) .R/0 13 ", JJ RE-3"!6 8ello -E"EC! "!RI0(Pioio8elloO*OioO) .R/0 13 ",JJ RE-3"!6 8ello 4T4I$: 1ame as LT4I$& trims from the ri!ht hand side of the 1trin!. -E"EC! R!RI0(P8ello P) .R/0 13 " JJ RE-3"!6 8ello T4I$: Can trim from left or ri!ht or both. !RI0(Ale$(ing; tr$iling;%ot7 (trim&c7$r) .R/0C str) .y default ta/es both. 4P)*: 1omewhat opposite to T4I$ functions. Pads the 1trin! with the !iven character on the ri!ht hand side. R5 1(str* lengt7A* )$(&strC) 1tr E ori!inal strin! Len!th E total len!th of strin! after paddin! Pad str E the strin! to pad. -E"EC! R5 1(P8elloO* M* PQO) .R/0 13 ",JJ RE-3"!6 8elloQQ LP)*: 1ame as 4P)*& pads from the left. T4)"1L)T3: *oes a character to character translation. -E"EC! !R 2-" !E(P8ello Horl(O* PelO*OK7O) .R/0 13 ", JJ RE-3"!6 8K77o Hor7( replaces all Ge? with G/? and all Gl? with Gh? 43PL)C3: 4eplaces the se0uence with the new se0uence RE5" CE(str* str&to&re)l$ce A* re)l$cement&strC), 1tr E ori!inal 1trin! 1tr to replace str to be replaced in str:. 4eplacement str str to replace If no replacement strin! is !iven& replaces by blan/ and trims.

18

-E"EC! RE5" CE(P8ello Horl(O* P8ellO* PCellO) .R/0 13 ", JJ RE-3"!6 Cello Horl(. -E"EC! RE5" CE(P8ello Horl(O* P8ellO) .R/0 13 ", JJ RE-3"!6 o Horl( 4363413: 4everse a 1trin!. -E"EC! REDER-E(P8ello Horl(O) .R/0 13 " JJ RE-3"!6 (lroH olle8 c, *ate -unctions: -unctions applied on the datatype date. 191*)T3 "3@TB*)9 191TI$31T) $P L)1TB*)9 )**B$O"T51 CU443"TB*)T3 1311IO"TI$7O"3 LOC)LTI$31T)$P $O"T51B.3TW33" CU443"TBTI$31T)$P *.TI$37O"3

191*)T3: 4eturns the current system date and time on the local database. If the server is on some other system& !ives the date and time of that system. -E"EC! -?-1 !E .R/0 13 ", JJRE-3"!6 CBrrent ($te in t7e (ef$Blt 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 functions returns a date after addin! the !iven date with the number of months. -E"EC! 11@0/2!8-(P01&R 2&0NO* 4) .R/0 13 ", JJRE-3"!6 P01&0 ?&0NO $O"T51B.3TW33": Ta/es two date parameters and !ives the difference of months between the two dates. -E"EC! 0/2!8-@BE!HEE2(!/@1 !E(P01&R 2&0NO*O11&0/2&??O)* !/@1 !E(P01&0 R&0NO*O11&0/2&??O)) .R/0 13 ", JJ RE-3"!6 3 -E"EC! 0/2!8-@BE!HEE2(!/@1 !E(P01&0 R&0NO*O11&0/2&??O)* !/@1 !E(P01&R 2&0NO*O11&0/2&??O)) .R/0 13 ", JJ RE-3"!6 3 "3@TB*)9: Ta/es D ar!uments and returns the nearest future date that falls on the !iven wee/day. 2E<!@1 ?(#($te'*#4eeK($y'),

19

wee/day H 1U"*)9C$O"*)9CTU31*)9CW3*"31*)9CT5U41*)9C-4I*)9C1)T U 4*)9. -E"EC! 2E<!@1 ?(P01&R 2&0NO*OHE12E-1 ?O) .R/0 13 ", JJ RE-3"!6O04&R 2&200NO L)1TB*)9: 4eturns the last day of the month for the !iven date. -E"EC! " -!@1 ?(!/@1 !E(P01&R 2&0NO*O11&0/2@??O)) .R/0 13 ", JJ RE-3"!6 P31&R 2&0NO CU443"TB*)T3+8i,: 4eturns the current date of the Client. -E"EC! C3RRE2!@1 !E .R/0 13 ", JJ RE-3"!6 cBrrent client ($te. CU443"TBTI$31T)$P+8i,: (ives the current date with timestamp with time#one of the client. -E"EC! C3RRE2!@!I0E-! 05 .R/0 13 ", JJ RE-3"!6 cBrrent ($te 4it7 timest$m) 4it7 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 "!I0E-! 05 .R/0 13 ", JJ RE-3"!6 cBrrent ($te 4it7 timest$m) of t7e client. 191TI$31T)$P+8i,: 4eturns server timestamp with time#one. -E"EC! -?-!I0E-! 05 .R/0 13 ", 1311IO"TI$37O"3+8i,: 4eturn the session?s time#one offset. -E"EC! -E--I/2!I0ET/2E .R/0 13 " JJ RE-3"!6 U05630 *.TI$37O"3+8i,: 4eturns database time#one offset. -E"EC! 1B!I0ET/2E .R/0 13 " JJ RE-3"!6 &08600 )part from the above standard *)T3 functions& there are some special date functions too. 3@T4)CT: 3'tract a value from a date or interval E<!R C! ( : ?E R ; 0/2!8 ; 1 ? ; 8/3R ; 0I23!E ; -EC/21 > ; : !I0ET/2E@8/3R ; !I0ET/2E@0I23!E >

20

; : !I0ET/2E@REGI/2 ; !I0ET/2E@ BBR > .R/0 : ($te@E$lBe ; interE$l@E$lBe > ) -E"EC! E<!R C!(?E R .R/0 -?-1 !E) .R/0 13 " JJ RE-3"!6 200N -E"EC! E<!R C!(0/2 .R/0 -?-1 !E) .R/0 13 " JJ RE-3"!6 2/D 4OU"*: 4ounds the !iven *)T3 to a specific unit of measure. R/321(#($te'*#form$t') *ependin! on the IformatJ chosen the date is rounded. 3.!. if the format is G93)4? rounds to the year& if the format is $O"T5 then rounds to the month etc. -E"EC! R/321(!/@1 !E(P02&R 2&200NO*O11&0/2&????O)* ?E R) JJRE-3"!6 P01&R 2&200NO -E"EC! R/321(!/@1 !E(P02&-E5&200NO*O11&0/2&????O)* ?E R) JJRE-3"!6 P01&R 2&200MO T4U"C: 1ame as the 4OU"*+IdateJ&IformatJ, function& but truncates the date. d, Conversion -unctions6 Used to convert from one data type to the other. TOBC5)4 TOB9$I"T346)L TOB*)T3 TOB*1I"T346)L TOB"U$.34

TOBC5)4: Converts a number or a date to a 1trin!. !/@C8 R(#E$lBe'* A#form$t'C* Anls@l$ngB$geC) 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 replaced by any number ; 8, -E"EC! !/@C8 R(89M.M88*O999.9O) .R/0 13 " JJ RE-3"!6 89M.M -E"EC! !/@C8 R(sys($te* V0ont7 11* ????V) .R/0 13 " JJ RE-3"!6 2oEem%er 25* 200N. TOB*)T3: Opposite of TOBC5)4. Ta/es the same number of ar!uments& the first ar!ument is a stin!. Converts the 1trin! value to a date. TOB"U$.34: Converts a 1trin! to a number.

21

e, 1pecial -unctoins: There are some special functions that can be used on most of the datatypes. *3CO*3: *ecodes a value and substitutes with the new value !iven. 1EC/1E(#col&n$me'* #col&E$lBe1'* #re)l$ce&E$l'* #col&E$lBe2'*#re)l$ce&E$l'* #(ef$Blt&E$l'), 1I(": 4eturns : if the result of the e'pression is positive& : if the result is ne!ative and ; if e0ual. "6L: 4eplaces the "ULL value with the new value. 2D"(#nBll&col'*#re)l$ce&E$l') "6L2(9i): )dvanced feature of "6L. 2D"2(#nBll&col'* #re)l$ce&if&not&nBll'* #re)l$ce&if& nBll') 4eplaces with the second ar!ument value if the value of first ar!ument is not null& if null replaces with the third ar!ument value. CO)L31C3+8i,: 4eturns the first non null e'pression in the list C/ "E-CE(#e=)&1'*#e=)&2'*#e=)&3'+.) "ULLI-+8i,: 23""I.(#$rg&1'*#$rg&2') If ar!: H ar!D HJ 4eturns "ULL If ar!: IJ ar!D HJ 4eturns ar!:

II.

$ULTI 4OW -U"CTIO"1: $ulti row functions are functions that can be applied on not one column of the row& but on all the rows of a column at the same time. These can be termed as the table level functions. 1U$: )dds the values of all the rows. -or columns with datatype number. -E"EC! -30(#col&n$me') .R/0 13 ",

22

)6(: -inds the avera!e of all the rows. )!ain this function is for the number columns. If a particular column value is "ULL then doesn?t consider that column for calculatin! the avera!e. -E"EC! DG(#col&n$me') .R/0 13 ", $)@: 4eturns the ma'imum value amon! a set of values. -E"EC! 0 <(#col&n$me') .R/0 13 ", $I": 4eturns the minimum value from the set of values. -E"EC! 0I2(#col&n$me') .R/0 13 ", *I1TI"CT: 4eturns all distinct rows from the result. i.e. doesn?t return any duplicate rows. -E"EC! 1I-!I2C!(#cols') .R/0 13 ", COU"T: 4eturns the count of all the non null rows. -E"EC! C/32!(#col') .R/0 13 ", 1T**36: 4eturns the standard deviation value. -E"EC! -!11ED(#col&n$me') .R/0 13 ", 6)4I)"C3: 4eturns the variance value. -E"EC! D RI 2CE(#col&n$me') .R/0 13 ",

3.N <oins When there are relationships between tables& we would li/e to ma/e use of those relationships and !enerate some 0uery results based on the relationships. <oins helps us lin/ two tables and e'tract the re0uired information from the D tables on which the %oin has been performed. There are two /inds of %oin synta' in Oracle - Oracle Ki %oins - Oracle 8i %oins Let?s discuss these in detail.

23

Oracle Ki %oins: 1imple <oins 3u0i %oin "on e0ui %oin Outer <oin 1elf <oin 1imple <oin: ) 1imple <oin is one in which a column from one table is be lin/ed to a column in another table to fetch the re0uired details from both the tables. Only the columns that match the !iven %oin condition are returned with the simple %oins. )n e0ui %oin is one in which the GH? operator is used i.e. the condition that is chec/ed for the columns in the two tables is the e0uality condition. -E"EC! #cols' .R/0 #t$%le&1'* #t$%le&2' H8ERE #t$%le&1'.#col' G #t$%le&2'.#col' We can also use table aliases. )n e'ample of table aliases is !iven below. -E"EC! #cols' .R/0 #t$%le&1' A -C t$%1* #t$%le&2' A -C t$%2 H8ERE t$%1.#col' G t$%2.#col' In an non e0ui %oin& the %oin condition is not an e0uality condition. It can be I +less than,& J +!reater than,& IJ +not e0ual to, etc.. -E"EC! #cols' .R/0 #t$%le&1'* #t$%le&2' H8ERE #t$%le&1'.#col' #' #t$%le&2'.#col'

Outer <oin: In an outer %oin& not only the matchin! columns +%oin condition, are retrieved but also the non matchin! columns from one of the tables are retrieved. The outer %oin in Oracle Ki comes in two flavors E left outer %oin and the ri!ht outer %oin. -or the outer %oin& all we need to do is to place a +L, after the column name +on the left or the ri!ht side of the e0uality condition,. If we place the +L, on the ri!ht hand side column& it is a left outer %oin and if we place it on the left hand side column it is a ri!ht outer %oin. On the side the +L, is placed& that table returns all the columns irrespective of the match. )ssume the 3mp table has all 3mployee details and the detp no. *ept table contains the dept details. "ow we want to display all employees with their department name and also those employees who don?t have any detp associated. The ri!ht outer %oin would loo/ li/e the followin!.

24

-E"EC! em)no*en$me*(n$me .R/0 em)* (e)t H8ERE em).(e)tno(U) G (e)t.(e)tno, "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 left outer %oin for this would be -E"EC! em)no*en$me*(n$me .R/0 em)* (e)t H8ERE em).(e)tno(U) G (e)t.(e)tno,

1elf <oin: ) self %oin is %oinin! within the same table. 1ay for e'ample we have emp table with empno& ename and m!r& where the mr! is a!ain an empno in the emp table only and we want to display the employee names with their mana!ers& we have to !o with a self %oin. When we use a self %oin& tables aliases should be used. -E"EC! e1.en$me* e2.en$me .R/0 em) e1* em) e2 H8ERE e1.mgrGe2.em)no,

Oracle 8i %oins: Cross <oins "atural <oins Inner <oin with U1I"( Clause Inner <oin with O" Clause Left Outer <oin 4i!ht Outer <oin -ull Outer<oin With 8i& Oracle has started supportin! the )"1I 12L 88 synta' for <OI"1. Prior to 8i& the <OI"1 in Oracle were very specific to the Oracle database and needed a lot of chan!es if someone had to do a chan!eover. .ut with 8i& Oracle started supportin! the )"1I 12L 88 synta' to ma/e it standard across the industry. -rom a performance aspect& there is not much difference between the two. 1ome of the advanta!es of this new feature is: We can brin! any 12L code and run them on Oracle easily. That would mean that we can easily port from other databases. 1eparation of <OI"1 from the W5343 clause conditions.

25

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

The synta' for all the new 8i %oins are as follows: C4O11 <OI": The cross %oin represents the Cartesian product of two or more tables selected without %oin conditions. -E"EC! #cols' .R/0 #t$%le&1' CR/-R/I2 #t$%le&2'

")TU4)L <OI": The natural %oin is based on table columns with the same name and datatype. This %oin automatically inte!rates into the %oin condition all columns with the same name and datatype. -E"EC! #cols' .R/0 #t$%le&1' 2 !3R " R/I2 #t$%le&2' This is the most dan!erous <OI"1 we have& as the columns will automatically become part of the <OI" condition if they are same. We should be very careful with this <OI" and try to avoid usin! it. <OI" with U1I"( Clause: While all matchin! columns of two tables are used for the %oin with a natural %oin& a specific column may be indicated e'plicitly for the %oin condition via the U1I"( clause. 5ere& too& the columns must have the same name and datatype in both tables. -E"EC! #cols' .R/0 #t$%le&1' AI22ERC R/I2 #t$%le&2' 3-I2G(#Ioin&colBmns') AH8ERE #con('C <OI" with O" Clause: <oin predicates can also be defined with O". This is necessary& for e'ample& if the columns for the %oin condition do not have the same name in the two tables. -E"EC! #cols' .R/0 #t$%le&1' AI22ERC R/I2 #t$%le&2' /2 (#Ioin&con(') A 21 #con('C AH8ERE #con('C, L3-T OUT34 <OI": 1imilar to Ki L3-T OUT34 <OI". -E"EC! #cols' .R/0 #t$%le&1' "E.! A/3!ERC R/I2 #t$%le&2' /2 (#Ioin&con(') A 21 #con('C AH8ERE #con('C

26

4I(5T OUT34 <OI": 1imilar to Ki 4I(5T OUT34 <OI". -E"EC! #cols' .R/0 #t$%le&1' RIG8! A/3!ERC R/I2 #t$%le&2' /2 (#Ioin&con(') A 21 #con('C AH8ERE #con('C -ULL OUT34 <OI": L3-T OUT34 <OI" L 4I(5T OUT34 <OI". -E"EC! #cols' .R/0 #t$%le&1' .3"" /3!ER R/I2 #t$%le&2' /2 (#Ioin&con(') A 21 #con('C AH8ERE #con('C

3.M

Writin! sub 0ueries We have seen how to write simple 0ueries and use different operators and %oins with it. 2ueries become even more comple' with the introduction of sub 0ueries. 3'ecutin! a 0uery containin! a sub 0uery& the sub 0uery is fired first and then the outer 0uery is fired. Let us loo/ at a few simple sub 0uery usa!e. :. Calculatin! the ma'imum salary of all employees from the emp table. -E"EC! s$l .R/0 em) H8ERE s$l G (-E"EC! 0 <(s$l) .R/0 E05), The most common operators used with sub 0ueries are )"9 least value from the sub 0uery )LL hi!hest value from the sub 0uery I" value of outer 0uery in a list of values from sub 0uery 3@I1T1 E (ive more priority over I" as it comes out once a match is found. When in 12L& it is always better to use operators than functions !iven a chance as the performance increases by usin! operators. 1o the same above 0uery can also be written as -E"EC! s$l .R/0 em) H8ERE s$l 'G "" (-E"EC! s$l .R/0 em)) D. 1elect all employees from the emp table whose salary is more than the salary of any employee wor/in! for dept D;. -E"EC! em)no* en$me .R/0 em) H8ERE s$l ' 2? (-E"EC! s$l .R/0 em) H8ERE (e)tnoG20)

27

Correlated 2ueries: There is another version of the sub 0ueries called correlated 0ueries. ) correlated 0uery is a!ain a sub 0uery& but we can perform %oins with a correlated sub 0uery. ) few thin!s to /eep in mind about the correlated sub 0uery - -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 the emp table -E"EC! W .R/0 em) $ H8ERE 2 ' (-E"EC! C/32!(W) .R/0 em) % H8ERE $.ro4i( # %.ro4i()

1calar sub 0uery+8i,: ) 0uery can be used in place of a column definition. 3'ample:
-E"EC! 12 0E* C/32!(E05.1E5!2/) .R/0 E05*1E5! H8ERE E05.1E5!2/(U)G 1E5!.1E5!2/ GR/35 B? 12 0E

"OW instead of above we can use


-E"EC!

12 0E* (-E"EC! C/32!(W) .R/0 E05 H8ERE

E05.1E5!2/

1E5!.1E5!2/) .R/0 1E5!

With the scalar sub 0uery the system !ives the outer %oin implicitly In the similar manner we can use scalar sub 0ueries for column definitions in the W5343 and O4*34 clauses too. Inline 6iew: With Inline views& the output of one 0uery will be !iven as the table for another. With the use of inline views we can simplify comple' 0ueries and reduce 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 and the avera!e salary of the department in which the employee wor/s& in a sin!le resultset. This is possible usin! an inline view for the avera!e salary calculation.

28

-E"EC! .1E5!2/* .- "* .E2 0E* B. DG- " .R/0 E05 * (-E"EC! 1E!52/ * DG(- ") DG- " .R/0 E05 GR/35 B? 1E5!2/) B H8ERE .1E5!2/GB.1E5!2/ 21 .- "'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 stored separately& but they act on the data ob%ect?s data and can modify them as well. *ata ob%ects are ob%ects for which physical data is stored and can be modified throu!h the ob%ects. :, Table: ) table is the most common ob%ect used in the database. Used to store 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 previous sections. D, 6iew: ) code ob%ect. Contains a 0uery that is pre compiled. 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& after creatin! a view if the underlyin! table structure chan!es +any alter command e'ecuted on the table, then the view becomes invalid and needs to be compiled a!ain. If the column in the table is dropped& the view becomes permanently invalid. CRE !E A/R RE5" CEC DIEH #Eie4&n$me'A#cols'C #select&stmt' AHI!8 C8EC9 /5!I/2C -

29

$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 #Eie4&n$me' C/05I"E *roppin! the view. 1R/5 DIEH #Eie4&n$me'

F, 1ynonym: 1ynonyms are code ob%ects They are the alternative names !iven to the database data ob%ects li/e tables etc.. It also has a security feature& as the user doesn?t /now which tableCob%ect heCshe is accessin!. Can use short names for lon! ob%ect names CRE !E A53B"ICC -?2/2?0 #syn&n$me' ./R #o%I&n$me' .y default they are private and can only be used by the owner of the ob%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. 1R/5 A53B"ICC -?2/2?0 #syn&n$me' M, 1e0uence: ) data ob%ect Used for auto !eneration of numbers Ise0 nameJ."3@T6)L E !ives the ne't value in the se0uence. i.e. runs the se0uence. Ise0 nameJ.CU446)L E !ives the current value in the se0uence. Creatin! a 1e0uence CRE !E -EL3E2CE #seX&n$me' -! R! HI!8 #st$rt&E$l' I2CRE0E2! B? #inc&E$lBe' 0I2D "3E #min&E$l' 0 <D "3E #m$=&E$l' C?C"EJ2/ C?C"E C C8E #c$c7e&E$l' start val : The value the se0uence should start with inc val: The value with which the se0uence should increase

30

min val: The minimum value the se0uence can hold. ma' val: The ma'imum value the se0uence can hold C9CL3C"O C9CL3: When C9CL3 mode is selected then the se0uence can a!ain start from first if the ma' value is e'ceeded. -irst the se0uence starts with the Istart valJ and is incremented by the inc val each time& when it reaches the ma' val for the ne't cycle starts with the min val +and not the start val,. If "O C9CL3 is selected then ends on reachin! the ma'value. Icache valJ: 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 very fast. It is a data ob%ect. When an inde' is created on a table& the system internally creates another inde' table internally which contains pseudo columns containin! the address of each row +sorted on the inde' column,. The address is :K characters and stored in the followin! format 1 & N 6 o%Iect I1 M Y 9 6 file I1 10 Y 15 6 %locK I1 1N Y 18 6 seXBence a, 1imple Inde': ) simple inde' is one that is created on the table columns that may have duplicate values. CRE !E I21E< #in(e=&n$me' /2 #t$%le&n$me' (#col& n$me') The above create statement creates an inde' table with the addresses of rows of the table sorted on the column on which inde' is applied. "ow when the user tries to fetch data from the underlyin! table and uses the inde' column& the inde' table is parsed and the address for the matched row is fetched and information is e'tracted from it. This will eliminate the need to perform a full table scan. We still have to ma/e a !ood desi!n decision 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 insertCupdate on the table would also need an update on the inde' table.

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 I21E< #in(e=&n$me' /2 #t$%le& n$me'(#fBnction') c, Uni0ue Inde': Inde'es created on table columns that have uni0ue columns. When we apply a U"I2U3 or P4I$)49 >39 constraint on any column& implicitly the U"I2U inde' is created for that column. )lso& when a uni0ue inde' is created on a column& the U"I2U3 constraint is imposed on that column implicitly. CRE !E 32IL3E I21E< #in(e=&n$me' /2 #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 maleCfemale. They are hi!hly compressed structures& which allows faster access. CRE !E BI!0 5 I21E< #in(e=&n$me' /2 #t$%le& n$me'(#colBmn&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 I21E< #in(e=&n$me' /2 #t$%le& n$me'(#colBmn&n$me') REDER-E

O, Cluster: *ata ob%ects. 1tores related tables data. The cluster column must be inde'ed. The cluster implementation is as follows Table :: 3$P E052/ 1 2 3 E2 0E < ? T 12/ 10 10 20

32

Table D: *3PT 12/ 10 20 Cluster on *"O: 10 B T & 3 I < Y 1 ? Y 2 R 12 0E B "/C I R

20

)s it can be fi!ured out from the above e'ample& a cluster stores related tables? data to!ether. In the above e'ample a cluster is created on the department number and the cluster table holds all information from the related tables based on the department number. 1teps for creatin! a cluster. - Create a cluster on a table column CRE !E C"3-!ER #clBster&n$me'(#col&n$me' #($t$ty)e') A! B"E-5 CE #t$%les)$ce&n$me'C Create Inde' on the cluster CRE !E I21E< #in(e=&n$me' /2 C"3-!ER #clBster& n$me' Create the table !ivin! the cluster name CRE !E ! B"E #t$%&n$me'(#cols') C"3-!ER #clBster&n$me'(#col&n$me')

33

P, *.Lin/: Combination of data ob%ect and code ob%ect. Connection between two databases. )llows to access ob%ects on another database. Creatin! a databse lin/ CRE !E 1 ! B -E "I29 #linK&n$me' C/22EC! !/ #Bser&n$me' I1E2!I.IE1 B? #)$ss4or(' 3-I2G #(%n$me' "ow from another database the ob%ects from this database can be accessed. -E"EC! #cols' .R/0 #Bsern$me'.#t$%le&n$me'Z#linK& n$me' Usin! a snapshot allows us to !et the copy of the table from the remote database to the local database. CRE !E -2 5-8/! #sn$)s7ot&n$me' /2 #t$%le&n$me'

34

1. A!!ENDI2 - A *ata *ictionary tables: 1ome of the dictionary tables used in Oracle.
user_<object-type> : objects created in the current user schema all_<object-type> : objects created by all users dba_<object-type> : 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

35

You might also like