Sei sulla pagina 1di 80

INTRODUCTION TO RDBMS

What Is DBMS? Data is one of the most important assets of a company. It is very important to make sure data is stored and maintained accurately and quickly. DBMS (Database Management System) is a system that is used to store and manage data. dding ne! data" for e#ample adding details of ne! student. Deleting un!anted data" for e#ample deleting the details of students !ho have completed course. $hanging e#isting data" for e#ample modifying the fee paid by the student. Features of DBMS Support for large amount of data % &racle can store terabytes of data. Data sharing, concurrency and locking - 'he same data can be accessed by multiple users at the same time ( data concurrency" DBMS locks data that is being manipulated to avoid t!o users from modifying the same data at the same time. Data Security % )hile DBMS allo!ing data to be shared" it also ensures that data in only accessed by authori*ed users. Data Integrity - Maintaining integrity of the data is an import process. If data loses integrity" it becomes unusable and garbage. DBMS provides means to implement rules to maintain integrity of the data. &nce !e specify !hich rules are to be implemented" then DBMS can make sure that these rules are implemented al!ays. 'hree integrity rules ( domain" entity and referential integrity Domain integrity - Data is said to contain domain integrity !hen the value of a column is derived from the domain. Domain is the collection of potential values. +or e#ample" column date of ,oining must be a valid date. ll valid dates form one domain. If the value of date of ,oining is an invalid date" then it is said to violate domain integrity. Entity integrity -'his specifies that all values in primary key must be not null and unique. -ach entity that is stored in the table must be uniquely identified. -very table must contain a primary key and primary key must be not null and unique. eferential Integrity - 'his specifies that a foreign key must be either null or must have a value that is derived from corresponding parent key.

Data Models Data model is a !ay of storing and retrieving the data. .ierarchical /et!ork 0elational !ierarchical In this model" data is stored in the form of a tree. 'he data is represented by parent%child relation ship. -ach tree contains a single root record and one or more subordinate records. +or e#ample" each batch is root and students of the batch !ill be subordinates. 'his model supports only one%to%many relationship bet!een entities. 'his !as used in IBM1s Information management system" IMS. "et#ork Data is stored along !ith pointers" !hich specify the relationship bet!een entities. 'his !as used in .oney!ell2s Integrated Data Store" IDS. 'his model is comple#. It is difficult to

understand both the !ay data is stored and the !ay data is manipulated. It is capable of supporting many%to%many relationship bet!een entities" !hich hierarchical model doesn1t. elational Data$ase Management System % DBMS& DBMS that is based on relational model is called as 0DBMS. 0elation model is most successful mode of all three models. Designed by -.+. $odd" relational model is based on the theory of sets and relations of mathematics. 0elational model represents data in the form a table. table is a t!o dimensional array containing ro!s and columns. Entity and 'ttri$ute n entity is any ob,ect that is stored in the database. -ach entity is associated !ith a collection of attributes. +or e#ample" if you take a data of a training institute" student is an entity as !e store information about each student in the database. -ach student is associated !ith certain values such as roll number" name" course etc." !hich are called as attributes of the entity. 'here !ill be relationship among entities. 'he relationship bet!een entities may be one% to%one" one%to%many or many%to%many. If you take entities student" batch and sub,ect" the follo!ing are the possible relationships. 'here is one%to%one relationship bet!een batch and sub,ect. &ne batch is associated !ith only one sub,ect. 'hree is one%to%many relationship bet!een batch and student entities. &ne batch may contain many students. 'here is many%to% many relationship bet!een student and sub,ect entities. single student may take many sub,ects and a single sub,ect may be taken by multiple students. "ormali(ation 'here is a concept of 3/ormal +orms1 that is often used to design and ,udge the quality of design of databases. 'here are five normal forms. .igher numbered normal forms have all the goodness qualities of the lo!er forms. +or e#ample" third%normal form database is also in second%normal form and first normal form. )ithout putting too fine a point on it" !e !ant our databases to be in as higher normal form as possible. .igher is better. 4enerally" you1re only concerned about the first three normal forms5and in this class" !e1ll also be concerned !ith Boyce%$odd /ormal +orm. First-"ormal Form - 'his is the most basic normal form" and the only requirement is that data is stored in tables. If your data is stored in tables" then you1ve achieved first%normal form. Second "ormal Form-&k" here it goes6 7 database is in second%normal form if it is in first% normal form and every attribute is fully functionally dependent on the primary key.8 nd no! to e#plain it6 primary keys are fields that uniquely identify a record. ttributes are everything else in the record. /o!" functionally dependent means that given a primary key" !e can get the value of any attribute. +or e#ample" given your student id" !e can find your first name and last name6 your first and last names are functionally dependent on your student id. 'he fully functionally dependent mostly applies to composite primary keys. It basically means that the attribute needs to be functionally dependent on the !hole primary key (not one of its parts). +or e#ample" some applications use first name" last name" and date of birth as a composite primary key. -very attribute in that record needs to depend on all first name" last name" and date of birth. Design It is very easy to achieve second%normal form by simply choosing a unique abstract primary key that doesn1t depend on the data. i.e.6 adding an auto%increment primary key to your tables. )hird-"ormal Form 7 database is in third%normal form if it is in second%normal form and contains no transitive attribute dependencies.8 'his one is a bit easier. )hat this means is that none of our attributes imply any other attributes. +or e#ample" in a 79erson8 table" !e might have person1s

phone" address" and *ip code. More often than not" the *ip code !ill imply part of the street address" and possibly the phone1s area code. 'his is precisely !hat third%normal form must avoid. :ou can1t generally avoid this problem in real life5!hen you1re using someone else1s identification systems in your databases. ;et1s ,ust say that for 3common1 things like addresses and *ip codes" it is 3ok1" !hile for your o!n data" no field should imply other fields (ie6 you shouldn1t have 3date of birth1 and 3age1 in your database" etc.). Boyce-*odd "ormal Form 7 relation 0 is in Boyce%$odd normal form if its primary key" <" implies all nonkey attributes5a" b" c" . . .5and < is a superkey.8 )ell" a key is a superkey if it implies all other attributes and no portion of < less than the !hole implies all other attributes. Basically if !e pick a ne! unique id for each record (the auto%increment" etc.) and pick fields 3appropriately1 then !e1ll get Boyce%$odd normal form. 'he Boyce%$odd normal form doesn1t e#actly fit into the numbered normal form idea6 it starts !ith normal form (assumes that data is in tables). It has been proved= that Boyce% $odd is also in third%normal form. So !e can consider Boyce%$odd as a >.?%normal form. )uple + entity. 'ttri$ute + *olumn column stores an attribute of the entity. +or e#ample" if details of students are stored then student name is an attribute@ course is another attribute and so on. ,rimary -ey table contains the data related entities. If you take S'AD-'/S table" it contains data related to students. +or each student there !ill be one ro! in the table. -ach student1s data in the table must be uniquely identified. In order to identify each entity uniquely in the table" !e use a column in the table. 'hat column" !hich is used to uniquely identify entities (students) in the table is called as primary key. Some other e#amples for primary keys are account number in bank" product code of products" employee number of an employee. *omposite ,rimary -ey In some tables a single column cannot be used to uniquely identify entities (ro!s). In that case !e have to use t!o or more columns to uniquely identify ro!s of the table. )hen a primary key contains t!o or more columns it is called as composite primary key. Foreign -ey In relational model" !e often store data in different tables and put them together to get complete information. +or e#ample" in 9 :M-/'S table !e have only 0&;;/& of the student. 'o get remaining information about the student !e have to use S'AD-'/S table. 0oll number in 9 :M-/'S table can be used to obtain remaining information about the student. 'he relationship bet!een entities student and payment is one%to%many. Structured .uery /anguage %S./& lmost all relational database management systems use SB; (Structured Buery ;anguage) for data manipulation and retrieval. SB; is the standard language for relational database systems. SB; is a non%procedural language" !here you need to concentrate on !hat you !ant" not on ho! you get it. 9ut it in other !ay" you need not be concerned !ith procedural details. SB; $ommands are divided into four categories" depending upon !hat they do. DD; (Data Definition ;anguage) DM; (Data Manipulation ;anguage) o# single ro! in the table is called as tuple. -ach ro! represents the data of a single

D$; (Data $ontrol ;anguage) Buery (0etrieving data)

GETTING STARTED WITH ORACLE 9i


What is 0racle? &racle is the name of the relational database management system that comes from &racle $orporation. *reating a )a$le 'able is a collection of ro!s and columns. Data in relational model is stored in tables. Before a table is created the follo!ing factors of a table are to be finali*ed. )hat data table is supposed to store. 'he name of the table. It should depict the content of the table. )hat are the columns that table should contains 'he name" data type and ma#imum length of each column of the table. )hat are the rules to be implemented to main data integrity of the table. ules to $e follo#ed for names 'hese rules are applicable for name of the table and column. 'he name must begin !ith a letter % %C or a%*. ;etters" digits and special characters ( underscore (D)" E and F are allo!ed. Ma#imum length of the name is >G characters. It must not be an SB; reserved !ord. 'here should not be any other ob,ect !ith the same name in your account. /ote6 table can contain up toHGGG columns in &racleI or above" !hereas in &racleJ a table can contain only =?K columns. Datatypes -ach column of the table contains the datatype and ma#imum length" if it is length is applicable. Datatype of the column specifies !hat type of data can be stored in the column. 1' *!' 2% len& $an store up to len number of characters. -ach character !ould occupy one byte. Ma#imum !idth is KGGG characters. *!' %len& +i#ed length character data. If len is given then it can store up to len number of characters. Default !idth is H. String is padded on the right !ith spaces until string is of len si*e. Ma#imum !idth is =GGG. "3MBE %p ,s& 9 represents the ma#imum significant digits allo!ed. S is the number of digits on the right of the decimal point.(pLH to >I" sL%IK to MH=J) D')E $an store dates in the range H%H%KJH= B.$ to >H%H=%NNNN D. /0"4 Oariable length character values up to = gigabytes. &nly one ;&/4 column is allo!ed per table. :ou cannot use ;&/4 datatype in functions" ).-0- clause of S-;-$'" in inde#ing and subqueries. 'W and /0"4 'W -quivalent to O 0$. 0= and ;&/4 respectively" but used for storing byte%oriented or binary data such as digital sound or graphics images. */0B, B/0B, "*/0B Ased to store large character and binary ob,ects. -ach can accommodate up to K gigabytes. BFI/E Stores a pointer to an e#ternal file. 'he content of the file resides in the file system of the operation system. &nly the name of the file is stored in the column. 0WID Stores a unique number that is used by &racle to uniquely identify each ro! of the table. $0- '- ' B;- courses(

ccode O 0$. 0=(?)" name O 0$. 0=(>G)" duration /AMB-0(>)" fee /AMB-0(?)" prerequisite O 0$. 0=(HGG) )@ Displaying ta$le definition using DES* IBE :ou can display the structure of a table using SB;P9;AS command D-S$0IB-. D-S$Q0IB-R ob,ectname 'o display the structure of $&A0S-S table" enter6 SB;S D-S$ $&A0S-S /ame /ullT 'ype %%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%% $$&D/&' /A;; O 0$. 0=(?) / MO 0$. 0=(>G) DA0 'I&/ /AMB-0(>) +-/AMB-0(?) 90-0-BAISI'O 0$. 0=(HGG) What is a constraint? $onstraints are used to implement standard and business rules. Data integrity of the database must be maintained. In order to ensure data has integrity !e have to implement certain rules or constraints. s these constraints are used to maintain integrity they are called as integrity constraints. )ypes of constraints *olumn *onstraint constraint given at the column level is called as $olumn $onstraint )a$le *onstraint constraint given at the table level is called as 'able $onstraint.

, IM' 5 -E5 *onstraint 'his constraint is used to define the primary key of the table. primary key is used to uniquely identify ro!s in a table. 'here can be only one primary key in a table. It may consist of more than one column ie $omposite primary key. $reates a unique inde# to enforce uniqueness. Defines /&' /A;; constraint to prevent null values. 'he follo!ing e#ample sho!s ho! to use 90IM 0: <-: constraint at column level. $0- '- ' B;- $&A0S-S ( ccode O 0$. 0=(?) $&/S'0 I/' coursesDpk 90IM 0: <-:" ... )@ 'he follo!ing e#ample sho!s ho! to define composite primary key using 90IM 0: <-: constraint at the table level. $0- '- ' B;- $&A0S-D+ $A;': ( ..." $&/S'0 I/' $&A0S-D+ $A;':D9< 90IM 0: <-: (ccode"faccode))@ 3"I.3E *onstraint -nforces uniqueness in the given column(s). &racle automatically creates a unique inde# for this column. $0- '- ' B;- courses ( ... "name O 0$. 0=(=G) $&/S'0 I/' coursesDnameDu A/IBA-"... )@ If t!o or more columns collective should be unique then A/IBA- constraint must be given at the table level.

"0) "3// *onstraint Ased to prevent any null value from entering into column. 'his is automatically defined for column !ith 90IM 0: <-: constraint. $0- '- ' B;- $&A0S-S( ..." name O 0$. 0=(=G) $&/S'0 I/' coursesDnameDnn /&' /A;;"...)@ $&/S'0 I/' option is used to given a name to constraint. 'he convention follo!ed here is ' B;-/ M-D$&;AM/D':9-. F0 EI4" -E5 *onstraint foreign key is used to ,oin the child table !ith parent table. +&0-I4/ <-: constraint is used to provide referential integrity" !hich makes sure that the values of a foreign key are derived from parent key. It can be defined either at the table level or at the column level. If a foreign key is defined on the column in child table then &racle does not allo! the parent ro! to be deleted" if it contains any child ro!s. .o!ever" if &/ D-;-'- $ S$ D- option is given at the time of defining foreign key" &racle deletes all child ro!s !hile parent ro! is being deleted. $0- '- ' B;- courseDfaculty (ccode O 0$. 0=(?) $&/S'0 I/' courses(ccode)"...)@ courseDfacultyDccodeDfk 0-+-0-/$-S

/ote6 )hen the name of the column in the referenced table is same as the foreign key then column need not be given after the table name. It means 0-+-0-/$-S courses in the above e#ample !ill suffice. 'able level constraint is used !hen foreign key is a composite foreign key. 0" DE/E)E *'S*'DE option If $$&D- in $&A0S-D+ $A;': table is defined as foreign key referencing $$&D- column of $&A0S-S table then it is /&' possible to delete ro!s from $&A0S-S table if dependent ro!s e#ists in $&A0S-D+ $A;': table. .o!ever" by using &/ D-;-'- $ S$ D- it is possible to delete all child ro!s !hile parent ro! is being deleted. 'he follo!ing code sho!s ho! to use &/ D-;-'- $ S$ D- option. $0- '- ' B;- courseDfaculty (ccode O 0$. 0=(?) $&/S'0 I/' courseDfacultyDccodeDfk 0-+-0-/$-S courses(ccode) &/ D-;-'- $ S$ D-"... )@ *!E*- *onstraint Defines the condition that should be satisfied before insertion or updation is done. 'he condition used in $.-$< constraint may /&' contain6 reference to pseudo column S:SD ' Subquery If it is given as column constraint" it can refer only to current column. But if it is given as table constraint" it can refer to more than one column of the table. In neither case it can refer to a column of other tables. 'he follo!ing e#ample sho!s ho! to create $.-$< constraint to make sure 40 D- column of $&A0S-D+ $A;': contains letters " B and $ only. $0- '- ' B;- courseDfaculty ( ..."grade char(H) $&/S'0 I/' courseDfacultyDgradeDchk $.-$< ( grade in (3 1"1B1"1$1) )" ...)@ 'he above $.-$< constraint does not allo! any other characters other than " B and $. It must be noted that character comparison is al!ays case sensitive. So to ignore case differences you can convert 40 D- to uppercase before comparison made as follo!s6 $0- '- ' B;- courseDfaculty ( ." grade char(H) $&/S'0 I/' courseDfacultyDgradeDchk $.-$< ( upper(grade) in (3 1"1B1"1$1) )"...)@

'he follo!ing is an e#ample of $.-$< constraint at table level. 'he constraint makes sure the starting date (S'D '-) of a batch is less than or equal to ending date (-/DD '-) of the batch. $0- '- ' B;- batches ( ..."$&/S'0 I/' batchesDdatesDchk $.-$< ( stdate UL enddate)")@ 4etting information a$out ta$les Data dictionary keeps track of the entire information about the database. It stores information about tables" constraints" procedures etc. &racle provides a set of data dictionary vie!s" !hich can be used to get information about these ob,ects. Data dictionary vie!s are not actually tables instead they are relational vie!s. .o!ever" at this stage you can treat data dictionary vie!s tables for the time being. )e get list of tables from our schema using the follo!ings6 S-;-$' P +0&M tab@ It is also possible to get information about all constraints of all tables in your account by using6 S-;-$' P +0&M userDconstraints@ If you !ant to get information about constraints of a single table" you can give the follo!ing to get names of constraints of B '$.-S table.$&/S'0 I/'D':9- column of AS-0D$&/S'0 I/'S may contain any of the follo!ing characters. *haracter Meaning $ $heck A Anique 0 0eference 9 9rimary key O $heck on vie! /ote6 'he table name must be given in uppercase !hile searching based on table name as all ob,ect names (table is an ob,ect) are stored in uppercase in data dictionary. S-;-$' constraintDname +0&M userDconstraints ).-0- tableDname L 2B '$.-S2@ $&/S'0 I/'D/ M%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% B '$.-SDS'D '-D// B '$.-SD'IMI/4D$.< B '$.-SDD '-SD$.< B '$.-SD9< B '$.-SD$$&D-D+< B $.-SD+$&D-D+<

CHANGING STRUCTURE AND DATA


'ltering the structure of a ta$le It is possible to modify the structure of the table even after the table is created. ;'-0 ' B;command is used to alter the structure of the table. 'he follo!ing are the possible alterations dding a ne! column dding a ne! table level constraint Increasing and decreasing !idth of a column $hanging data type of the column Dropping a column Dropping a constraint Disabling a constraint -nabling a disabled constraint 'dding a ne# column or constraint It is al!ays possible to add a ne! column to an e#isting table. .o!ever" if column is to be added to a table that already contains ro!s" then certain options are not available. 'o add a ne! column $ ' (category) to $&A0S-S table" enter the follo!ing6 ;'-0 ' B;- courses DD (cat O 0$. 0=(?))@ It is not possible to given any constraint that is not satisfied by e#isting data. +or instance" it is not possible to add $ ' as a /&' /A;; column as &racle initiali*es $ ' column in all ro!s !ith /A;; value. See the follo!ing snapshot of the screen. SB;S ;'-0 ' B;- courses = DD ( cat O 0$. 0=(?) /&' /A;;)@ ;'-0 ' B;- courses P -00&0 at line H6 &0 %GHJ?I6 table must be empty to add mandatory (/&' /A;;) column .o!ever" it is possible to have /&' /A;; constraint in the follo!ing cases6 If D-+ A;' option is used to specify the default value for the column )hen table is empty. 'he follo!ing e#ample !ill !ork as D-+ A;' option is used to specify the default value. ;'-0 ' B;- courses DD ( cat O 0$. 0=(?) D-+ A;' 2prog2 /&' /A;;)@ :ou can add a table constraint. &nce table is created" it is not possible to add constraints other than /&' /A;; to columns of the table. .o!ever" it is possible to add any constraint at the table level as follo!s6 ;'-0 ' B;- courses DD ( $&/S'0 I/' coursesDcatDchk $.-$< (;-/4'.(cat) SL =)) 'he above constraint specifies that the column $ ' should have at least t!o characters. It is added as a table constraint as it not possible to add $.-$< constraint at the column level to column that already e#ists.

Modifying attri$utes of e6isting columns 'o increase the si*e of the column $ '" enter the follo!ing6 ;'-0 ' B;- courses M&DI+: (cat O 0$. 0=(HG))@ :ou can decrease the !idth and even change the datatype of the column if the column is empty. 'hat means if no ro! has any value for the column being altered. Dropping a constraint 'o drop a constraint" the name of the constraint is required. :ou may use AS-0D$&/S'0 I/'S data dictionary vie! to get the list of constraints. ;'-0 ' B;- courses D0&9 $&/S'0 I/' coursesDcatDchk@ *'S*'DE 0ption :ou cannot drop a A/IBA- or 90IM 0: <-: constraint that is part of a referential integrity constraint !ithout also dropping the corresponding foreign key. 'o drop 90IM 0: <-: or A/IBA- constraint along !ith 0-+-0-/$-S constraint use $ S$ D- option. 'o drop 90IM 0: <-: constraint of S'AD-/'S along !ith related constraint" do the follo!ing. ;'-0 ' B;- courses D0&9 90IM 0: <-: $ S$ D-@ /ote6 :ou can get information about all the constraint using AS-0D$&/S'0 I/'S data dictionary vie!. Dropping a column 'o drop column $ ' of $&A0S-S table" enter the follo!ing6 ;'-0 ' B;- courses D0&9 column cat@ If column being dropped is either a 90IM 0: <-: or A/IBA- key that is referenced by a foreign key" then it is not possible to drop the column. But it is possible if $ S$ D$&/S'0 I/'S option is used. $ S$ D- $&/S'0 I/'S option drops all constraints that depend on the column being dropped. 'o drop column +$&D- column of + $A;': table along !ith all depending constraints" enter6 ;'-0 ' B;- faculty D0&9 column fcode $ S$ D- $&/S'0 I/'S@ /ote6 )hen you drop a A/IBA- or 90IM 0: <-: column then &racle automatically drops the inde# that it creates to enforce uniqueness. Ena$ling and Disa$ling *onstraints ;'-0 ' B;- can be used to enable and disable constraints !ithout dropping constraints. 'o disable 90IM 0: <-: on SABV-$'S table6 ;'-0 ' B;- courses DIS B;- 90IM 0: <-:@ &r you can drop any constraint by giving its name as follo!s6 ;'-0 ' B;- courses DIS B;- $&/S'0 I/' coursesDcatDchk@ If the constraint has depending constraints then you must use $ S$ D- clause to disable dependent constraints. :ou can enable a disabled constraints using -/ B;- clause as follo!s6 ;'-0 ' B;- courses DIS B;- $&/S'0 I/' coursesDcatDchk@ /ote6 :ou can find out status of a constraint by using S' 'AS column of AS-0D$&/S'0 I/'S data dictionary vie!. Dropping a ta$le 'o drop a table" use DD; command D0&9 ' B;-. D0&9 ' B;- tablename Q$ S$ D- $&/S'0 I/'SR@

$ S$ D- $&/S'0 I/'S clause is used to drop constraints that refer to primary and unique keys in the dropped table. If you do not give this clause and if referential integrity (references constraint) constraints e#ists then &racle displays then &racle displays error and doesn1t drop the table. 'he follo!ing command !ill drop + $A;': table. D0&9 ' B;- faculty@ /ote6 )hen table is dropped" Oie!s" and Synonyms based on the table !ill be made invalid" though they remain in the system. lso note" dropping a table cannot be undone. Manipulating data DM; commands such as I/S-0'" D-;-'- and A9D '- are used to manipulate the data of the table. Inserting ro#s into a ta$le SB; command I/S-0' is used to insert ne! ro! into the table. I/S-0' I/'& courses O ;A-S(2ora2"2&racle database2"=?"K?GG"2<no!ledge of )indo!s2)@ /ote6 fter inserting the required ro!" issues $&MMI' command to make sure the changes are made permanent. )ithout $&MMI'" ro!s that are inserted might be lost if there is any po!er failure. During insertion" character values are enclosed in single quotes. Anless other!ise specified !e have to supply a value for each column of the table. If the value of any column is not kno!n or available then you can give /A;; as the value of the column. +or e#ample" the follo!ing insert !ill insert a ne! ro! !ith null value for 90-0-BAISI'- column. I/S-0' I/'& courses O ;A-S(2c2"2$ 9rogramming2"=?">GGG"null)@ /ote6 I/S-0' command can insert only one ro! at a time. +or multiple ro!" I/S-0' command must be issued for multiple times. D '- type values must be in the format DD%M&/%:: or DD%M&/%::::" !here M&/ is the first three letters of the month (Van" +eb). If only t!o digits are given for year then current century is used. +or e#ample" if you give NN for year" &racle !ill take it as =GNN as the current century is =GGG. So it is important to remember this and give four digits if required. 'he follo!ing is the complete synta# for I/S-0' command. I/S-0' I/'& tablename Q(columns list)R WO ;A-S (value%H"...) X subquery Y Inserting a ro# #ith selected columns It is possible to insert a ne! ro! by giving values only for a fe! columns instead of giving values for all the available columns. 'he follo!ing I/S-0' command !ill insert a ne! ro! only t!o values. I/S-0' I/'& courses(ccode"name) O ;A-S (2odba2"2&racle Database dministration2)@ 'he above command !ill create a ne! ro! in $&A0S-S table !ith values for only t!o columns ( $$&D- and / M-. 'he remaining columns !ill take /A;; value or the default value" if the column is associated !ith default value. "3// 7alue

/ull value means a value that is not available or not kno!n. )hen a column1s value is not kno!n then !e store /A;; value into the column. /A;; value is neither G nor blank nor any other kno!n value. )e have already seen ho! to store null value into a column and !hen &racle automatically stores null value into a column. ME 4E Statement 'his ne! statement is used to combine Insert and Apdate commands into a single command. 'his is also called as Apsert functionality. 'his command is used !here !e have to insert ro! of one table into another table if the ne! ro! is not available in the old table. If ne! ro! is already available in the old table then the ro! in the old table is updated. 'he follo!ing e#ample sho!s ho! to use M-04- statement to insert ro! of /-)90&DA$'S table into 90&DA$'S table if 90&DID is not found in the 90&DA$'S table. If 90&DID of /-)90&DA$'S is found in 90&DA$'S table then the 0 '- column is updated !ith 0 '- column of /-)90&DA$'S. M-04- I/'& 90&DA$'S 9 ASI/4 /-)90&DA$'S /9 &/ (9.90&DID L /9.90&DID) ).-/ M '$.-D '.-/ A9D 'S-' 0 '- L /9.0 ').-/ /&' M '$.-D '.-/ I/S-0' (9.90&DID" 9./ M-"9.0 '-) O ;A-S (/9.90&DID"/9./ M-"/9.0 '-)@ 3pdating ro#s using 3,D')E command A9D '- command is used to modify e#isting data in the ro!s. 'he follo!ing command !ill change course fee of S9 to ZGGG. A9D '- courses set fee L ZGGG ).-0- ccode L 3asp1@ If ).-0- clause is not given then all the ro!s of the table !ill be effected by the change. In fact" it is more often the result of an error than intentional. It is also possible to change more than one column at a time as follo!s6 A9D '- courses set fee L ZGGG" durationL>G ).-0- ccdoe L 3asp1@ /ote6 )e !ill discuss ho! to use subquery in A9D '- command later in this book. Deleting ro#s using DE/E)E command D-;-'- command is used to delete ro!s from a table. 'he follo!ing is the synta# of D-;-'command. D-;-'- +0&M table Q).-0- condition@R If ).-0- clause is not given then all ro!s of the table !ill be deleted. 'he follo!ing command !ill delete ro! ).-0- $$&D- is 7c8. D-;-'- +0&M courses ).-0- ccode L 3c1@ It is not possible to delete a parent ro! !hile it has child ro!s. +or e#ample" it is not possible to delete a ro! from $&A0S-S table if the ro! has dependent ro!s in B '$.-S table or in $&A0S-D+ $A;': table. .o!ever" it is possible to delete parent ro! along !ith its child ro!s provided &/ D-;-'- $ S$ D- option is given at the time of create foreign key constraint in

child table. $hanges made using I/S-0'" A9D '- and D-;-'- are not made permanent until e#plicitly or implicitly they are committed. )ransaction transaction is a collection of statements used to perform a single task. 'hese statements are logically related as they perform a single task. ll these statements must be e#ecuted to successfully complete the task. If any of the statements fails then the all the statements that !ere e#ecuted prior to the statement that failed should be undone other!ise data in the database becomes invalid and inconsistent. 'he follo!ing e#ample !ill illustrate the process. ssume that faculty !ith code kl (<evin ;oney) is leaving the institute. So all his batches are to be assigned to ,c (Vason $ouchman). +or this the follo!ing steps are to be taken. $hange +$&D- of all the batches that are currently being handled by kl to ,c. Delete ro!s +0&M $&A0S-D+ $A;': !here +$&D- is kl. Delete ro! from + $A;': !here +$&D- is kl. 'hat means the follo!ing are the commands to be e#ecuted to perform the abovementioned task. A9D '- batches set fcode L 3,c1 ).-0- fcode L 3kl1@ D-;-'- +0&M courseDfaculty ).-0- fcode L 3kl1@ D-;-'- +0&M faculty ).-0- fcode L 3kl1@ It is important to make sure that all three statements are either successfully completed or all of them are rolled back. 'o ensure this &racle provides transaction mechanism. If A9D 'command in the above set of commands begins the transaction then only $&MMI' command is given after the second D-;-'- is e#ecuted" the changes are committed. If 0&;;B $< command is given then all the changes up to A9D '- !ill be rolled back. So $&MMI' and 0&;;B $< command are used to ensure either everything is committed or everything is rolled back. transaction is a collection of statements !hich is to be either completely done or not done at all. In other !ords the process should not be half%done. 'hat means ;; or /&'.I/4. transaction begins !hen previous transaction ends or !hen the session begins. transaction ends !hen $&MMI' or 0&;;B $< is issued. ne! session starts !hen you connect to &racle. +or e#ample" !hen you log on using SB;P9;AS you start a ne! session. )hen you e#it SB;P9;AS the session is terminated. *0MMI) *ommand Ased to commit all changes made since the beginning of the transaction. It does the follo!ing. Makes all the changes made to database during transaction permanent Anlocks the ro!s that are locked during the transaction. -nds the transaction. -rases all savepoints in the current transaction(covered later). $hanges made to database such as inserting ro!s" deleting ro!s" and updating ro!s are not made permanent until they are committed. Implicit *ommit &racle Implicitly issues commit in the follo!ing cases. Before a DD; command. fter a DD; command. t normal disconnect from the database. +or e#ample" !hen you e#it SB;P9;AS using -[I' command.

/ote6 It is very important to remember not to mi# DM; commands !ith DD; command as the later commands are going to issue $&MMI'" !hich might commit incomplete changes also. 0//B'*- *ommand Ased in transaction processing to undo changes made since the beginning of the transaction. Andoes the changes made to database in the current transaction 0eleases locks held on ro!s duration transaction. -nds the transaction. -rases all savepoints in the current transaction (covered later). S'1E,0I") *ommand Savepoint is used to mark a location in the transaction so that !e can rollback up to that mark and not to the very beginning of the transaction. 'he follo!ing is the synta# of S O-9&I/'. S O-9&I/' savepointDname@ single transaction may also have multiple savepoints. 'he follo!ing e#ample illustrates ho! to use savepoints. SB;S A9D '- . . . SB;S savepoint sH@ Savepoint created. SB;S insert .... @ SB;S insert .... @ SB;S savepoint s=@ Savepoint created. SB;S D-;-'- ...@ SB;S rollback to sH@ 0ollback complete. SB;S A9D '-\ SB;S commit@ In the above e#ample" 0&;;B $< '& SH@ !ill undo changes made from savepoint SH to the point of rollback. 'hat means it !ill undo I/S-0'" I/S-0'" and even D-;-'- given after second savepoint. It doesn1t undo A9D '- given before first savepoint. 'he $&MMI' given after last A9D '- is going to commit first AD9 '- and last A9D '-. Because all the remaining are already rolled back by 0&;;B $< '& SH command. If !e have given 0&;;B $< '& S=@ then it !ould have undone only D-;-'- given after the second savepoint and remaining statements (update" insert" insert" and A9D '-) !ould have been committed. /ocking It is important from database management system1s point of vie! to ensure that t!o user are not modifying the same data at the time in a destructive manner.

Selecting rows fro

! t!"le

;et us see ho! to retrieve data of a table. S-;-$' command of SB; is used to retrieve data from one or more tables. It implements operators of relational algebra such as pro,ection" and selection. 'he follo!ing is the synta# of S-;-$' command. 'he synta# given here is incomplete. +or complete synta#" please refer to online documentation. S-;-$' QDIS'I/$' X ;;R WP X table.P X e#pr Y Qalias R Q WtableY.PX e#pr Y Qalias R R ... +0&M Qschema.Rob,ect Q" Qschema.Rob,ect R ... Q).-0- conditionR Q&0D-0 B: We#prXpositionY Q S$ X D-S$R Q" We#prXpositionY Q S$ X D-S$RR ...R 'he follo!ing is an e#ample of a basic S-;-$' command. S-;-$' P +0&M courses@ $$&D/ M%%%%% %%%%%%%%%%%%%%%%%%%% ora &racle database vbnet OB./-' c $ programming asp S9./-' ,ava Vava ;anguage #ml [M; 9rogramming DA0 'I&/ %%%%%%%%% =? >G =G =? =? H? +-K?GG ??GG >?GG ?GGG K?GG KGGG 90-0-BAISI'%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%% )indo!s )indo!s and programming $omputer !areness Internet and programming $ language .'M;"Scripting" S9]VS9

'he simplest S-;-$' command contains the follo!ing6 $olumns to be displayed. If P is given" all columns are selected. 'he name of the table from !here ro!s are to be retrieved. ,ro8ection 9ro,ection is the operation !here !e select only a fe! columns out of the available columns. 'he follo!ing is an e#ample of pro,ection. S-;-$' name"fee +0&M courses@ / M+-%%%%%%%%%%%%%%%%%%%% %%%%%%%%% &racle database K?GG OB./-' ??GG $ programming >?GG S9./-' ?GGG Vava ;anguage K?GG [M; 9rogramming KGGG 3sing e6pressions in SE/E*) command It is also possible to include e#pressions in the list of columns. +or e#ample" the follo!ing S-;-$' !ill display discount to be given for each course.

S-;-$' name"fee" fee P G.H? +0&M courses@ / M+-+--PG.H? %%%%%%%%%%%%%%%%%%%% %%%%%%% %%%%%%%%% &racle database K?GG ZJ? OB./-' ??GG I=? $ programming >?GG ?=? S9./-' ?GGG J?G Vava ;anguage K?GG ZJ? [M; 9rogramming KGGG ZGG *olumn 'lias 'he column heading of an e#pression !ill be the e#pression itself. .o!ever" as it may not be meaningful to have e#pression as the result of column heading" !e can give an alias to the column so that alias is displayed as the column heading. 'he follo!ing e#ample !ill use alias DIS$&A/' for the e#pression +-- P G.H?. S-;-$' name" fee" fee P G.H? DIS$&A/' +0&M courses / M%%%%%%%%%%%%%%%%%%%% &racle database OB./-' $ programming S9./-' Vava ;anguage [M; 9rogramming 'he follo!ing 0perator M % P ] 0 DE +-%%%%% K?GG ??GG >?GG ?GGG K?GG KGGG DIS$&A/' %%%%%%%%% ZJ? I=? ?=? J?G ZJ? ZGG

are the arithmetic operators that can be used in e#pressions. Description dd Subtract Multiply Divide

B5 clause It is possible to display the ro!s of a table in the required order using &0D-0 B: clause. It is used to sort ro!s on the given column(s) and in the given order at the time of retrieving ro!s. 0emember" sorting takes place on the ro! that are retrieved and in no !ay affects the ro!s in the table. 'hat means the order of the ro!s !ill remain unchanged. /ote6 &0D-0 B: must al!ays be the last of all clauses used in the S-;-$' command. 'he follo!ing S-;-$' command displays the ro!s after sorting ro!s on course fee. S-;-$' name" fee +0&M courses &0D-0 B: fee@ / M+-%%%%%%%%%%%%%%%%%%%% %%%%%%%%% $ programming >?GG [M; 9rogramming KGGG &racle database K?GG Vava ;anguage K?GG S9./-' ?GGG OB./-' ??GG /ote6 /ull values are placed at the end in ascending order and at the beginning in descending order. 'he default order for sorting is ascending. Ase option D-S$ to sort in the descending order. It is also possible to sort on more than one column.

'o sort ro!s of $&A0S-S table in the ascending order of DA0 'I&/ and descending order of +--" enter6 S-;-$' name" duration" fee +0&M courses &0D-0 B: duration " fee desc@ / M%%%%%%%%%%%%%%%%%%%% [M; 9rogramming $ programming S9./-' &racle database Vava ;anguage OB./-' DA0 'I&/ +-%%%%%%%%% %%%%%%%%% H? KGGG =G >?GG =? ?GGG =? K?GG =? K?GG >G ??GG

+irst" all ro!s are sorted in the ascending order of DA0 'I&/ column. 'hen the ro!s that have same value in DA0 'I&/ column !ill be further sorted in the descending order of +-- column. 3sing column position Instead of giving the name of the column" you can also give the position of the column on !hich you !ant to sort ro!s. +or e#ample" the follo!ing S-;-$' sorts ro!s based on discount to be given to each course. S-;-$' name" fee" fee P G.H? +0&M courses &0D-0 B: >@ / M+-+--PG.H? %%%%%%%%%%%%%%%%%%%% %%%%% %%%%%%%%% $ programming >?GG ?=? [M; 9rogramming KGGG ZGG &racle database K?GG ZJ? Vava ;anguage K?GG ZJ? S9./-' ?GGG J?G OB./-' ??GG I=? /ote6 $olumn position refers to position of the column in the selected columns and not the position of the column in the table. 'he above command uses column position in &0D-0 B: clause. lternatively you can use column alias in &0D-0 B: clause as follo!s6 S-;-$' name" fee" fee P G.H? discount +0&M courses &0D-0 B: discount@ / M%%%%%%%%%%%%%%%%%%%% $ programming [M; 9rogramming &racle database Vava ;anguage S9./-' OB./-' +-%%%% >?GG KGGG K?GG K?GG ?GGG ??GG DIS$&A/' %%%%%%%%% ?=? ZGG ZJ? ZJ? J?G I=?

Selection It is possible to select only the required ro!s using ).-0- clause of S-;-$' command. It implements selection operator of relational algebra. ).-0- clause specifies the condition that

ro!s must satisfy in order to be selected. 'he follo!ing e#ample select ro!s !here +-- is more than or equal to ?GGG. S-;-$' name" fee +0&M courses ).-0- fee SL ?GGG / M+-%%%%%%%%%%%%% %%%%%%%%% OB./-' ??GG S9./-' ?GGG 'he follo!ing relational and logical operators are used to form condition of ).-0- clause. ;ogical operators ( /D" &0 ( are used to combine conditions. /&' operator reverses the result of the condition. If condition returns true" /&' !ill make the overall condition false. L" ^L or US" SL" UL" S" U" /D" &0" /&'

'he follo!ing S-;-$' command displays the courses !here duration is more than H? days and course fee is less than KGGG. S-;-$' P +0&M courses ).-0- duration S H? and fee U KGGG@ $$&D/ M%%%%% %%%%%%%%%%%%%%%%%%%% c $ programming DA0 'I&/ %%%%%%%%% =G +-90-0-BAISI'%%%%%%% %%%%%%%%%%%%%%%%%%% >?GG $omputer !areness

'he follo!ing S-;-$' command retrieves the details of course !ith code &0 . S-;-$' P +0&M courses ).-0- ccode L 2ora2@ $$&D- / MDA0 'I&/ %%%%% %%%%%%%%%%%%%%%%%%%% %%%%%%%%% ora &racle database =? +-%%%%%%%%% K?GG 90-0-BAISI'%%%%%%%%%% )indo!s

/ote6 )hen comparing strings" the case of the string must match. ;o!ercase letters are not equivalent to uppercase letters. S./ 0perators part from standard relational operators (L and S)" SB; has some other operators that can be used in conditions. 0perator What it does? BE)WEE" 7alue-9 '"D 7alue-2 $hecks !hether the value is in the given range. 'he range is inclusive of the given values. 'his supports D '- type data also. I"%list& $hecks !hether the value is matching !ith any one of the values given in the list. ;ist contains values separated by comma("). /I-E pattern $hecks !hether the given string is matching !ith the given pattern. More on this later. IS "3// and IS "0) "3// $hecks !hether the value is null or not null. 'o display the list of course !here DA0 'I&/ is in the range =G to =? days" enter6 S-;-$' name +0&M courses

).-0- duration bet!een =G and =?@ / M%%%%%%%%%%%%%%%%%%%% &racle database $ programming S9./-' Vava ;anguage /ote6 B-')--/.. /D is alternative to using SL and UL operators.

I" 0perator $ompares a single value !ith a list of values. If the value is matching !ith any of the values given in the list then condition is taken as true. 'he follo!ing command !ill retrieve all courses !here duration is either =G or >G days. S-;-$' name +0&M courses ).-0- duration in (=G">G)@ / M%%%%%%%%%%%%%%%%%%%% OB./-' $ programming 'he same condition can be formed even !ithout I/ operator using logical operator &0 as follo!s6 S-;-$' name from courses !here duration L =G or duration L >G@ .o!ever" it !ill be more convenient to user I/ operator compared !ith multiple conditions compared !ith &0 operator. /I-E operator 'his operator is used to search for values !hen the e#act value is not kno!n. It selects ro!s that match the given pattern. 'he pattern can contain the follo!ing special characters. Sym$ol Meaning _ D Cero or more characters can take the place of _. (underscore) ny single character can take the place of underscore. But there must be one letter.

'o select the courses !here the course name contains pattern ./-'" enter6 S-;-$' name"duration" fee +0&M courses ).-0- name like 2_./-'_2 / MDA0 'I&/ +-%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% OB./-' >G ??GG S9./-' =? ?GGG 'he follo!ing e#ample selects courses !here second letter in the course code is 7b8 and column 90-0-BAISI'- contains !ord 7programming8. S-;-$' P +0&M courses ).-0- ccode like 2Db_2 and prerequisite like 2_programming_2@ $$&D- / MDA0 'I&/ +-90-0-BAISI'%%%%% %%%%%%%%%%%%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% vbnet OB./-' >G ??GG )indo!s and programming

0emember ;I<- operator is case sensitive. In the above e#ample" if $$&D- contains value in uppercase (OB)" then it !on1t be a match to the pattern. IS "3// and IS "0) "3// operators 'hese t!o operators test for null value. If !e have to select ro!s !here a column is containing null value or not null value then !e have to use these operators. +or e#ample the follo!ing S-;-$' command !ill select all the courses !here the column +-- is null. S-;-$' P +0&M courses !here fee is null@ 'hough &racle provides /A;; key!ord" it cannot be used to check !hether the value of a column is null. +or e#ample" the follo!ing condition !ill al!ays be false as &racle treats t!o null values as t!o different values. S-;-$' P +0&M courses ).-0- fee L null@ 'he above command does /&' !ork as fee though contains null value !ill not be equal to /A;;. S&" !e must use IS /A;; operator. Selecting distinct 7alues DIS'I/$' clause of S-;-$' command specifies only distinct values of the specified column must be selected. S-;-$' distinct fee +0&M courses@ +-%%%%%%%%% >?GG KGGG K?GG ?GGG ??GG )hereas the same query !ithout DIS'I/$' clause !ill select the follo!ing. S-;-$' fee +0&M courses@ +-%%%%%%%%% K?GG ??GG >?GG ?GGG K?GG KGGG

#UNCTIONS
What is a function? function is similar to an operator in operation. function is a name that performs a specific task. function may or may not take values (arguments) but it al!ays returns a value as the result. If function takes values then these values are to be given !ithin parentheses after the function name. 'he follo!ing is the general format of a function. function Q(argument%H" argument%="...) R If the function doesn1t take any value then function name can be used alone and even parentheses are not required. )ypes 9: 2: of functions Single ro# functions rithmetic +unctions. Date ` 'ime functions. String functions. $onversion functions. Miscellaneous functions. Multiple ro# functions

'rithmetic Functions rithmetic functions take numbers and perform arithmetic operations. Function Description BS(value) bsolute value of the given value. $-I;(value) Smallest integer larger than or equal to value +;&&0(value) ;argest integer smaller than or equal to value M&D(value"divisor) 0emainder of the division bet!een the value and divisor. 9&)-0(value"e#ponent) Oalue is raised to e#ponent. 0&A/D(valueQ"precisionR) 0ounds value to precision. 9recision can be negative if rounding is to be done on the left of the decimal point. '0A/$(valueQ"precisionR) 'runcates instead of rounding. &ther!ise same as 0&A/D. SB0'(value) Square root of value. SI4/(value) 0eturns H if value S G" %H if value UG" G if value L G 'he follo!ing are a fe! e#amples of arithmetic functions. S-;-$' M&D(HG"K) +0&M dual@ 'he above command displays = as the result as the remainder of the division bet!een HG and K is =. 03"D and ) 3"* functions 0&A/D and '0A/$ functions are used to round and truncate the given number to the given number of digits (either on the right or left of the decimal point). 0&A/D takes the leftmost digit that is being lost and accordingly adds one to the rightmost digit. '0A/$ doesn1t take the leftmost digit into account. It ,ust truncates the given number to the given precision.

S-;-$' round(HGKJ.JI?"=)" trunc(HGKJ.JI?"=) +0&M dual@ 'he above command !ill display HGKJ.JN and HGKJ.JI. 'his is because '0A/$ doesn1t take the digits being lost into account. 'he follo!ing e#amples illustrate the result of 0&A/D and '0A/$ functions !ith positive and negative precision. Function esult 0&A/D(H=N?.>?Z"=) H=N?.>Z '0A/$(H=N?.>?Z"=) H=N?.>? 0&A/D(H=N?.>?Z"G) H=N? 0&A/D(H=I?.>?Z" %H) H=NG '0A/$(H=I?.>?Z" %H) H=IG 0&A/D(H=N?"%=) H>GG )hen precision in 0&A/D is positive then rounding takes place to the specified number of digits on the right of decimal point. +or e#ample" if precision is = it means round number to = digits on the right of the decimal point. )hen precision is negative@ it means number is to be rounded to the left of the decimal point. In both the cases if the leftmost digit of the digits being lost is SL ? then one is added to the rightmost digit of the digits that are retained. /ote6 0&A/D and '0A/$ functions can also be used !ith date data type. *EI/ ; F/00 functions $-I; produces the smallest integer that is greater than or equal to the given value. )hereas +;&&0 is opposite of $-I;. +unction $-I;(H.>) $-I;(=) $-I;(%=.>) +;&&0(H.>) +;&&0(=) +;&&0(%=.>) 0esult = = %= H = %>

D3'/ )a$le 'his is a table that is made available to every account in &racle database. 'his table contains one ro! and one column. 'his table can be used !ith S-;-$' !hen result of the e#pression is to be displayed only for once. SB;S describe dual /ame /ullT %%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% DAMM: 'ype %%%% O 0$. 0=(H)

+or e#ample" to display the current system date the follo!ing S-;-$' can be used6 SB;S S-;-$' sysdate +0&M dual@ S:SD '%%%%%%%% =K% A4%GH s DA ; table contains only one ro!" the result is displayed only for once. 'he follo!ing e#ample displays the course fee by rounding it to thousands. S-;-$' ccode"name" round(fee"%>) 7fee8 +0&M courses@ $$&D/ Mfee

%%%%% ora vbnet c asp ,ava #ml

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% &racle database ?GGG OB./-' ZGGG $ programming KGGG S9./-' ?GGG Vava ;anguage ?GGG [M; 9rogramming KGGG

Date 'rithmetic )hen arithmetic operators are used !ith D '- datatype it is called as Date rithmetic. 'he follo!ing are the possible arithmetic operations on D '- type data. dding a number to date to get the date after the given number of days. Subtracting a number from a date to get the date before the given number of days. Subtracting t!o dates to get the number of days bet!een these t!o dates. 'he follo!ing e#ample displays the name of the student and number of days bet!een system date and date of ,oining. S-;-$' name" sysdate % d, +0&M students@ / M/o Days %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% 4eorge Micheal ==Z.=NHNK Micheal Douglas ==?.=NHNK ndy 0oberts ==?.=NHNK Malcom Marshall ==G.=NHNK Oivan 0ichards ==G.=NHNK $hirs -vert ===.=NHNK Ivan ;endal ==H.=NHNK 4eorge Micheal HJZ.=NHNK 0ichard Mar# HKG.=NHNK 'ina 'urner HKG.=NHNK Vody +oster H>N.=NHNK In &racle D '- datatype stores date and time. t the time of storing a date If time is not given then it !ill be set to G hours" G minutes and G seconds (beginning of the day or H=6GG a.m.). Default date format ( DD%M&/%:: ( doesn1t include time. .o!ever time is al!ays stored along !ith date and if you !ant to at any time you can e#tract the time portion a date using '&D$. 0 function. /ote6 ll comparisons bet!een t!o dates include time portion also. 'he fraction portion in the result bet!een t!o dates indicates the difference in time. 'he follo!ing e#ample sho!s the due date for first installment (assuming first installment is to be paid !ithin HG days from the date of ,oining). S-;-$' name"d," d, M HG aDue Datea +0&M students@ / MDV %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% 4eorge Micheal HG%V /%GH Micheal Douglas HH%V /%GH ndy 0oberts HH%V /%GH Malcom Marshall HZ%V /%GH Oivan 0ichards HZ%V /%GH $hirs -vert HK%V /%GH Ivan ;endal H?%V /%GH 4eorge Micheal GH%M 0%GH 0ichard Mar# GZ% 90%GH Due Date %%%%%%%%% =G%V /%GH =H%V /%GH =H%V /%GH =Z%V /%GH =Z%V /%GH =K%V /%GH =?%V /%GH HH%M 0%GH HZ% 90%GH

'ina 'urner Vody +oster

GZ% 90%GH GJ% 90%GH

HZ% 90%GH HJ% 90%GH

'he follo!ing query displays the details of the payment that !ere made in the last > days6 S-;-$' P +0&M payments ).-0- sysdate ( dp UL >@ Date Functions Date functions operate on values of D '- datatype. -#cept M&/'.SDB-')--/ all date functions return D '- data type. 'he follo!ing is the list of D '- functions. 'DD<M0")!S%date, count& dds count number of months to date. M0")!S<BE)WEE" %date9, date2& 0eturns number of months bet!een dateH and date=. /'S)<D'5%date& 0eturns the last day of the month in !hich date is. "E=)<D'5%date, >day>& 4ives the date of ne#t day after the date" !here day name of the !eek like 3Monday1. 03"D%date& 0ounds the date depending upon the time. If time is at or after H= hours then date is incremented. 'ime is al!ays set to beginning of the day (G6G6G). ) 3"*%date& Same as 0&A/D (date) but doesn1t increment date.

'dding and su$tracting months :ou can add or subtract months from a date using DDDM&/'.S function. If the count is positive" that many months !ill be added. If count is negative that many months !ill be subtracted. dding months is the process !here &racle !ill give the date of ne#t specified number of months. In the follo!ing e#ample" &racle !ill add t!o months to system date6 SB;S S-;-$' sysdate" addDmonths(sysdate"=) = +0&M dual@ S:SD 'DDDM&/'. %%%%%%%%% %%%%%%%%% =?% A4%GH =?%&$'%GH If the target month doesn1t have the required day then the last day of the month !ill be taken. In the follo!ing e#ample" >G%S-9%=GGH is returned" as >H%S-9 is not available. &racle automatically ad,usts the date according to the requirement. 'he follo!ing e#ample !ill sho! the date on !hich the students of completed batches !ill be issued certificates assuming it !ill take > months time to issue certificates. SB;S S-;-$' bcode" ccode" enddate" addDmonths(enddate">) a$ert. Datea = +0&M batches > ).-0- enddate IS /&' /A;;@ B$&D- $$&D- -/DD '%%%%% %%%%% %%%%%%%%% bH ora =G%+-B%GH b= asp G?%M 0%GH b> c =J%+-B%GH bK #ml >G%M 0%GH b? ,ava HG%M :%GH $ert. Dat %%%%%%%%% =G%M :%GH G?%VA/%GH =J%M :%GH >G%VA/%GH HG% A4%GH

4etting months $et#een t#o dates

:ou can obtain the number of months bet!een t!o dates using M&/'.SDB-')--/ function. 'he follo!ing query returns the number of months bet!een starting date and ending date of all completed batches S-;-$' bcode" ccode" stdate" enddate" monthsDbet!een(enddate" stdate) a/&. Monthsa +0&M batches ).-0- enddate IS /&' /A;;@ B$&D- $$&D- S'D '-/DD '/&. Months %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%%% bH ora H=%V /%GH =G%+-B%GH H.=?IGZK? b= asp H?%V /%GH G?%M 0%GH H.ZJJKHNK b> c =G%V /%GH =J%+-B%GH H.==?IGZ? bK #ml G=%M 0%GH >G%M 0%GH .NG>==?IH b? ,ava G?% 90%GH HG%M :%GH H.HZH=NG> 'he fraction in the result is the number of days beyond the number of months. +or e#ample" the difference bet!een H=%V /%GH and =G%+-B%GH is H.=?I. It means there is one month and =Z_ of another month" !hich comes to I days. /ote6 It is possible to send the return value of a function to another function. 'he follo!ing query displays the batches that !e completed in the last Z months and duration is more that H month. S-;-$' bcode" ccode +0&M batches ).-0- monthsDbet!een(sysdate"enddate) UL Z and monthsDbet!een(enddate"stdate) S H@ B$&D- $$&D%%%%% %%%%% b= asp b> c b? ,ava /'S)<D'5 function ; S'DD : function returns the date of the last day of the month of the given date. 'he follo!ing statement displays the last day of the current month6 S-;-$' sysdate" lastDday(sysdate) +0&M dual@ S:SD '- ; S'DD :( %%%%%%%%% %%%%%%%%% =?% A4%GH >H% A4%GH 'he follo!ing query displays the due date by !hich first installment of each batch is to be paid. ; S'DD : function return the last day of the month in !hich batch has started and if ? is added to that then it !ill be ?th of the ne#t month ( due date of first installment. S-;-$' bcode"ccode" stdate" lastDday(stdate) M ? aDue Datea +0&M batches B$&D- $$&D- S'D 'Due Date %%%%% %%%%% %%%%%%%%% % %%%%%%%% bH ora H=%V /%GH G?%+-B%GH b= asp H?%V /%GH G?%+-B%GH b> c =G%V /%GH G?%+-B%GH bK #ml G=%M 0%GH G?% 90%GH b? ,ava G?% 90%GH G?%M :%GH bZ vbnet H=%VA;%GH G?% A4%GH bJ ora H?% A4%GH G?%S-9%GH "E=)<D'5 function

'his function returns the date of given !eekday that is greater than the given date. It takes !eekday ( Sunday" Monday etc. ( and returns the date on !hich the coming !eekday is falling. 'he return value is al!ays grater than the given date. 'he follo!ing e#ample sho!s !hen is the ne#t +riday. S-;-$' sysdate" ne#tDday(sysdate"2+ri2) +0&M dual@ S:SD '/-['DD :( %%%%%%%%% %%%%%%%%% =?% A4%GH >H% A4%GH 03"D ; ) 3"* functions #ith dates D '- data type contains both date and time. 0&A/D and '0A/$ function can be used to round or truncate the date based on the time portion. 'he follo!ing query displays the date and time portion of system date using '&D$. 0 function. It is suffice to kno! that '&D$. 0 can be used to convert given date to character type using the given format. S-;-$' toDchar(sysdate"2dd%mm%yyyy hh=K6mi6ss2) +0&M dual@ '&D$. 0(S:SD '-"2DD %%%%%%%%%%%%%%%%%%% =?%GI%=GGH HI6K=6GI /ote6 '&D$. 0 converts a D '- type data to character type. 0&A/D function adds one day to the date if time portion of the date is greater than or equal to H= noon. S-;-$' sysdate" toDchar(round(sysdate)"2dd%mm%yyyy hh=K6mi6ss2) 70ound Datea +0&M dual@ S:SD '0ound Date %%%%%%%%% %%%%%%%%%%%%%%%%%%% =?% A4%GH =Z%GI%=GGH GG6GG6GG In the above query first 0&A/D function is used to round S:SD '-. s !e have seen the time in S:SD '- is HI hours" the date is incremented by one ( =Z% A4. 0&A/D al!ays sets the time portion to G6G6G (as seen in the output of the query). '0A/$ function doesn1t increment the date based on the time" but it sets time portion to G hours" G minutes and G seconds. 'he follo!ing query sho!s the result of '0A/$ function. S-;-$' toDchar(sysdate"2dd%mm%yyyy hh=K6mi6ss2) a'odaya" toDchar( trunc(sysdate)"2dd%mm%yyyy hh=K6mi6ss2) a'runcated Datea +0&M dual 'oday 'runcated Date %%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%% =?%GI%=GGH HI6?Z6?> =?%GI%=GGH GG6GG6GG /ote6 Both 0&A/D and '0A/$ set the time portion in the D '- data type to H= .M. (GG6GG6GG). String Functions String functions are functions that manipulate a set of characters. set of characters is a string. +or e#ample" the name of the company" the address of a person all these are e#amples of a string. $. 0 and O 0$. 0 data types contain strings. ;et us first see ho! to concatenate strings in &racle. *oncatenating Strings '!o strings can be concatenated (added one after another) to form a single string using the string concatenation operator" !hich is XX (t!o pipe symbols). 'he follo!ing e#ample concatenates name of the faculty !ith qualification. )e also put t!o spaces bet!een these t!o values to provide required space.

S-;-$' name XX 2 2 XX qual +0&M faculty / M-XX22XXBA ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4eorge <och MS $omputer Science Dan ppleman $S and -- graduate .erbert Schildt MS $omputer Science David .unter MS -lectronics Stephen )alther 9h.D. in 9hilosophy <evin ;oney MS -letronics Vamie Va!orski Bachlors of -lectrical Vason $ouchman &$9 DB /E"4)! %string& 0eturns the number of characters in the string. /0WE %string& 0eturns the string after converting the string to lo!ercase. 3,,E %string& 0eturns the string after converting the string to uppercase. I"I)*', %string& $onverts first character of every !ord to uppercase and remaining to lo!er case. /,'D %string, length ?, fillstring@& Makes the string of the given length by padding the string on the left either !ith space or !ith fillstring. ,'D %string, length ?, fillstring@& Same as ;9 D but pads on the right. /) IM %string ?, charset@& 0emoves all left most characters of string up to the first character that is not in the charset. If charset is not given then it defaults to blank. ) IM %string ?, charset@& Same as ;'0IM" but trims on the right. ) IM %string& 'rims space on both sides. S3BS) %string, pos , length& -#tracts length number of characters from position pos in the string. If length is not given then e#tracts everything from pos. I"S) %s9,s2 ?,pos ?,occurrence@@& +inds the starting position of s= in sH. If occurrence is not given then it finds first occurrence. Search starts at pos" if given" other!ise at the first character in sH. 'S*II %string& 0eturns S$II code of the first character in the given string *! %num$er& 0eturns S$II character for the given S$II code. ) '"S/')E %string, from, to& 0eplaces characters in from !ith to in string. E,/'*E %string, source, replace& 0eplaces source in string !ith replace.

*on7erting *ase S-;-$' name"duration +0&M courses ).-0- name ;I<- 2_programming_2 / M- DA0 'I&/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% $ programming =G 'he above query retrieves only one t!o !hereas there are t!o ro!s that contain the !ord programming. It is because of the difference in the case. So the follo!ing query is converting the name to lo!ercase before comparison. S-;-$' name"duration +0&M courses ).-0- ;&)-0(name) ;I<- 2_programming_2 / MDA0 'I&/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% $ programming =G [M; 9rogramming H? I/I'$ 9 converts first letter of each !ord to capital and remaining letters to lo!ercase. S-;-$' initcap(2this IS to 'est I/I'$ 92) 0esult +0&M dual@ 0-SA;'

%%%%%%%%%%%%%%%%%%%%%%% 'his Is 'o 'est Initcap I"S) function I/S'0 returns the position in the first string !here the second string starts in the first string. If second string is not found in first string" it returns G. 'he follo!ing e#amples illustrate the usage of t!o optional parameters@ start and occurrence. S-;-$' I/S'0(2.o! do you do2"2do2) 9ostion +0&M dual@ 9&S'I&/ %%%%%%%%% ?

S3BS)

function SABS'0 is used to e#tract a sub string from the given string. It takes the position from !here e#traction starts and the number of characters to be e#tracted. 'he follo!ing e#ample displays the first = character from the code of the course. S-;-$' ccode" SABS'0(ccode"H"=) sn +0&M courses $$&D- S/ %%%%% %% &ra or vbnet vb c c asp as ,ava ,a #ml #m )rimming Strings ;'0IM and 0'0IM are used to trim off un!anted characters from the left and right ends of the string respectively. ;eftmost spaces are called as leading spaces and rightmost spaces are called as trailing spaces. 'hey trim spaces by default. &ptionally" you can specify !hich set of characters you !ant to trim. 'he follo!ing e#ample is used to trim spaces on the left using ;-+'. S-;-$' ltrim( 2aabcbad#yabc2"2abc2) 0esult +0&M dual@ 0-SA;' %%%%%% d#yabc ,adding Strings string can be made of a given length by padding either on the left using ;9 D or on the right using 09 D. By default &racle uses space to pad strings. S-;-$' rpad(name"H="2.2) /ame +0&M courses / M%%%%%%%%%%%% &racle datab OB./-'...... $ programmin S9./-'..... Vava ;anguag [M; 9rogramm

) '"S/')E and E,/'*E functions 'hese t!o functions return the string after modifying the given string. '0 /S; '- !orks on individual characters" !hereas 0-9; $- replaces a string !ith another string. 'he follo!ing t!o e#amples !ill make the difference clear. S-;-$' replace(2 B$ B $ [:C D B$2"2 B$2"29B02) 0esult +0&M dual 0-SA;' %%%%%%%%%%%%%%%%% 9B0 B $ [:C D9B0 0-9; $- replaces every occurrence of string 3 B$1 !ith string 390B1. S-;-$' translate(2 B$ B $ [:C D B$2"2 B$2"29B02) 0esult +0&M dual 0-SA;' %%%%%%%%%%%%%%%%% 9B0 9B90 [:C D9B0 '0 /S; '- changes every occurrence of letter !ith 9" B !ith B and $ !ith 0. *on7ersion Functions $onversion functions are used to convert a value from one data type into another. 'hese functions are not required if &racle can automatically convert the value. But there are cases !here these conversion functions are required to convert the value to the required data type. F3"*)I0" '&D$. 0 (value Q" formatR) '&DD '- (char Q" formatR) '&D/AMB-0 (char) DES* I,)I0" $onverts value" !hich is of D '- or /AMB-0 type" to $. 0 type. $onverts the given $. 0 type value to D '- type. $onverts given $. 0 type value to /AMB-0 type.

Before !e understand ho! and !here !e use conversion functions" let us see ho! &racle tries to convert the given data to the required data type. 'utomatic )ype *on7ersion &racle automatically converts the value to the required data type if it is possible. 4AID-;I/-S +&0 A'&M 'I$ $&/O-0SI&/ &+ D ' ':9 ny /AMB-0 or D '- !ill be converted to a $. 0. If D '- is a literal enclose it in quotes. $. 0 type !ill be converted to /AMB-0 if it contains only digits" decimal point" or minus sign on the left. $. 0 !ill be converted to D '- type if it is in DD%M&/%:: or DD%M&/%:::: format. D '- !ill /&' be converted to /AMB-0. /AMB-0 !ill /&' be converted to D '-. 'he follo!ing fe! e#amples !ill give you better idea about automatic conversion of data type6 In the follo!ing e#ample /AMB-0 is automatically converted to $. 0 before ;-/4'. function is used. S-;-$' length(HH>>) +0&M dual@ ;-/4'.(HH>>) %%%%%%%%%%%% K In the e#ample belo!" a D '- given in $. 0 format is converted to D '- before ; S'DD : function is applied. S-;-$' lastDday(2=G%aug%=GGH2) +0&M dual@ ; S'DD :( %%%%%%%%% >H% A4%GH

Similarly it is possible to use a $. 0 value !here a /AMB-0 is required" as sho!n belo!. S-;-$' ? P 2=G2 +0&M dual@ ?P2=G2 %%%%%%%%% HGG .ere are a fe! e#amples !here &racle cannot automatically convert the value. SB;S S-;-$' ne#tDday(2H=%H%=GGH2" 2+ri2) +0&M dual@ S-;-$' ne#tDday(2H=%H%=GGH2" 2+ri2) +0&M dual P -00&0 at line H6 &0 %GHIK>6 not a valid month &racle returns an error saying the date is not having valid month because &racle e#pects months to be of first three letters of the month name. s !e have given only month number" it is not acceptable to &racle. In this case !e need to e#plicitly convert the value to D '- type using '&DD '- function. 'he follo!ing sections !ill sho! ho! to use conversion functions. )0<*!' Function 'his function is used to convert the given D '- or /AMB-0 to $. 0 type. '&D$. 0 function may also be used to format the given date or number !hile converting the value to $. 0 type. +or e#ample" to display date in DD%MM%:::: format instead of standard format % DDM&/% ::" enter the follo!ing6 S-;-$' toDchar(sysdate"2dd%mm%yyyy2) 0esult +0&M dual 0-SA;' %%%%%%%%%% H?%GI%=GGG In fact" '&D$. 0 is one of the most frequently used functions. .ere in the e#ample" belo! it is used to display both date and time of S:SD '-. 0emember this operation needs e#plicit usage of '&D$. 0 as by default &racle displays only date. S-;-$' toDchar(sysdate"2dd Month yyyy hh=K6mi6ss2) +0&M dual '&D$. 0(S:SD '-"2DDM&/'.:: %%%%%%%%%%%%%%%%%%%%%%%%%% H? ugust =GGG G=6HI6?Z In the above e#ample Month is standing for complete month name" yyyy stands for four digits year" hh=K for =K hours based hour" mi minutes and ss for seconds. +ormat in '&D$. 0 function is a collection of more than KG formatting options. +or complete list" please see on%line help for Date +ormat -lements. ll options in the format are replaced !ith the corresponding values and remaining characters are returned as they are. In the above e#ample" 361 bet!een ..=K and MI is returned as it is but ..=K and MI are replaced !ith the corresponding values. Format 0ption MM M&/ M&/'. DDD DD D Day :::: :: :- 0 Description /umber of the month6 HG +irst three letters of month name6 &$' $omplete month name6 &$'&B-0 Day of the year since Vanuary Hst6 >KG Day of the month6 HZ Day of the !eek6 ? Day fully spelled6 )ednesday +our digits year6 HNNZ '!o digits year6 NZ :ear spelled out6 /I/'--/%/I/':%SI[

.. or ..H= ..=K MI SS .M. or 9.M. +m '. S9

.our of the day6 ? .our of the day6 =G Minute of hour6 >G Second of minute6 >G Displays .M. or 9.M. depending on the time. 0emoves trailing spaces. 3May 3 becomes 3May1 Suffi# to number6 DD'. !ill produce HZth /umber Spelled out6 DDS9 !ill produce '.I0D for day >. pril in

'he follo!ing query retrieves details of the students !ho have ,oined in the month of year =GGH. S-;-$' bcode" name +0&M students ).-0- toDchar(d,"2mmyyyy2) L 2GK=GGH2@ B$&D- / M%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% b? 0ichard Mar# b? 'ina 'urner b? Vody +oster

In the follo!ing e#ample '&D$. 0 is used to display month name of the year. .o!ever" as you can see in the output" there are trailing spaces after month name. 'his is because &racle pads the name to N characters. Months that have smaller name than that !ill have trailing spaces. S-;-$' bcode" name" toDchar(d,"2dd%Month%yyyy2) d, +0&M students B$&D- / MDV %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% bH 4eorge Micheal HG%Vanuary %=GGH bH Micheal Douglas HH%Vanuary %=GGH b= ndy 0oberts HH%Vanuary %=GGH b= Malcom Marshall HZ%Vanuary %=GGH b= Oivan 0ichards HZ%Vanuary %=GGH b> $hirs -vert HK%Vanuary %=GGH b> Ivan ;endal H?%Vanuary %=GGH bK 4eorge Micheal GH%March %=GGH b? 0ichard Mar# GZ% pril %=GGH b? 'ina 'urner GZ% pril %=GGH b? Vody +oster GJ% pril %=GGH +ormat fm can be used to remove these trailing spaces in months name. .ere is revised version of the above query. S-;-$' bcode" name" toDchar(d,"2dd%fmMonth%yyyy2) d, +0&M students B$&D- / MDV %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% bH 4eorge Micheal HG%Vanuary%=GGH bH Micheal Douglas HH%Vanuary%=GGH b= ndy 0oberts HH%Vanuary%=GGH b= Malcom Marshall HZ%Vanuary%=GGH b= Oivan 0ichards HZ%Vanuary%=GGH b> $hirs -vert HK%Vanuary%=GGH b> Ivan ;endal H?%Vanuary%=GGH bK 4eorge Micheal GH%March%=GGH b? 0ichard Mar# GZ% pril%=GGH b? 'ina 'urner GZ% pril%=GGH b? Vody +oster GJ% pril%=GGH

/ote6 'he output of '&D$. 0 !ill be in the same case as the format. +or e#ample" if Month is given then output !ill be pril@ if M&/'. is given then output !ill be 90I;. )0<D')E function '&DD '- is used to convert a $. 0 type value to D '- type. If the value is in DD%M&/% :: or DD%MM%:::: format then '&DD '- is not needed because &racle implicitly converts the value to D '- type. )hen you insert a record !ith only date in DD%M&/%:: format" time portion of the date is set to GG6GG6GG. 'he follo!ing I/S-0' inserts a ne! ro! into 9 :M-'S table !ith date as !ell as time. I/S-0' I/'& payments values ( HG"toDdate(2HK%GK%=GGH HG6=G6GG2" 2dd%mm%yyyy hh=K6mi6ss2)" =GGG)@ It is important to make sure the values given are matching !ith the format. 'hat means" in the above e#ample" as !e gave dd%mm%yyyy hh=K6mi6ss as the formation even the data is to given in the same format. 'he format informs to &racle ho! to interpret the given values. If there is any mismatch" the values may be misinterpreted. 'he format options are same as '&D$. 0 function format options. )0<"3MBE function 'his function is required in only t!o occasions. 'he follo!ing are the t!o cases. 'o convert formatted number to number. 'o sort $. 0 data in numeric order. 'he first application of '&D/AMB-0 is to convert formatted number to number. 'he follo!ing e#ample is trying to multiply E>>> by =G. But as the number !ith currency symbol is not taken as a number by &racle" it results in error. SB;S S-;-$' E>>> P =G +0&M dual@ S-;-$' E>>> P =G +0&M dual P -00&0 at line H6 &0 %GGNHH6 invalid character '&D/AMB-0 function can be used to convert E>>> to a number so that it is treated as a number by &racle. 'he format in '&D/AMB-0 specified that the first character is to be taken as currency symbol and remaining as digits. SB;S S-;-$' toDnumber(2E>>>2"2ENNN2) P =G +0&M dual '&D/AMB-0(2E>>>2"2ENNN2)P=G %%%%%%%%%%%%%%%%%%%%%%%%%%% ZZZG Sorting strings in numeric order nother usage of '&D/AMB-0 is to sort a column that contains numbers but stored in the form of $. 0 type. ssume the follo!ing data is e#isting in O/& column of O-.I$;-S table. $olumn O/& is defined as O 0$. 0=(HG). SB;S S-;-$' vno +0&M vehicles@ O/& %%%%%%%%%% HH>> H?I> =?G= ?Z?J N =>K K?

'he follo!ing S-;-$' sorts the data but sorts the column O/& as a collection of strings. 'hat means the numeric values are not taken into account and numbers are taken as a collection of characters (each digits is a character). S-;-$' vno +0&M vehicles &0D-0 B: vno@ O/& %%%%%%%%%% HH>> H?I> =>K =?G= K? ?Z?J N 'he output sho! that number N is at the bottom. It is because of the !ay strings are compared in sorting ( first character first and then second character and so on. 'o sort the data using numeric value" issue the follo!ing command !here O/& column is converted to a number before it is sorted using '&D/AMB-0 function. S-;-$' vno +0&M vehicles &0D-0 B: toDnumber(vno)@ O/& %%%%%%%%%% N K? =>K HH>> H?I> =?G= ?Z?J Miscellaneous Functions

CASE, DECODE, NVL, NVL2, COALEASE, EXTRACT CASE Expression This is one of the features that PL/SQL lac e! till no"# $e use! DECODE to su%stitute this# &ut no" Oracle 'ro(i!es a full)%lo"n case structure# The follo"in* is the s+nta, of CASE e,'ression# CASE selector $-EN e,'ression. T-EN result. /$-EN e,'ression2 T-EN result20### /ELSE elseresult0 END1 The follo"in* e,a2'le "ill *i(e +ou so2e i!ea ho" to use it# Pro*ra22er "ith no"le!*e of S$3TC- state2ent of C shoul! not 4u2' to an+ conclusion that it rese2%les S$3TC-# 5es, it is in conce't %ut in 'ractice these are t"o !ifferent "a+s# The follo"in* e,a2'le co'ies !iscount 'ercenta*e %ase on *ra!e of the 'ro!uct# SELECT case *ra!e "hen 6A6 then .7 "hen 6&6 then .8 "hen 6c6 then .2 "hen 6!6 then 27 else 7 END

9RO: stu!ents1 DECODE function This function "or s li e a 2ulti'le 39 state2ent or a CASE/S$3TC- state2ent in a t+'ical 'ro*ra22in* lan*ua*e# 3t ta es a (alue an! co2'ares it "ith the *i(en (alues one %+ one# $here(er the (alue is e;ui(alent to the *i(en (alue it returns the corres'on!in* (alue# The follo"in* e,a2'le sho"s ho" to !eco!e the <RADE of CO=RSE>9AC=LT5 ta%le# SELECT fco!e, cco!e, !eco!e?*ra!e,6A6,6Ver+ <oo!6, 6&6,6<oo!6, 6C6, 6A(era*e6, 6=n no"n6@ <ra!e 9RO: course>facult+ 9CODE CCODE <RADE ))))) ))))) ))))))))))))) * ora Ver+ <oo! l ora Ver+ <oo! 4c ora Ver+ <oo! !a (%net Ver+ <oo! s" as' Ver+ <oo! !a as' <oo! hs c Ver+ <oo! !h ,2l Ver+ <oo! 44 4a(a Ver+ <oo! hs 4a(a <oo! 44 c Ver+ <oo! 44 (%net <oo! The function is use! to !is'la+ 2eanin*ful te,t for colu2n <RADE, "hich contains onl+ A,& or C# The follo"in* e,a2'le sho"s another usa*e of DECODE "here "e !is'la+ the total re2uneration 'ai! to facult+# Assu2in* the 'a+2ent is %ase! on the ti2e of the %atch an! no# of !a+s of the %atch# SELECT %co!e,cco!e,fco!e, st!ate, en!!ate, !eco!e?ti2in*,.,277,2,.87,.A8@ B ?en!!ate)st!ate@ A2ount 9RO: %atches $-ERE en!!ate 3S NOT N=LL &CODE CCODE 9CODE STDATE ENDDATE A:O=NT ))))) ))))) ))))) ))))))))) ))))))))) ))))))))) %. ora * .2)CAN)7. 27)9E&)7. AD77 %2 as' !a .8)CAN)7. 78):AR)7. AE87 %E c hs 27)CAN)7. 2A)9E&)7. FF87 %G ,2l !h 72):AR)7. E7):AR)7. GH77 %8 4a(a hs 78)APR)7. .7):A5)7. A777 NVL function 3t is use! to return the secon! (alue if first (alue is null# This function has a lot of si*nificance since Oracle returns a null (alue fro2 an+ e,'ression containin* a null (alue# NoteI An+ e,'ression in(ol(in* a null (alue "ill result in a null (alue#

The follo"in* ;uer+ is to !is'la+ the !etails of all %atches# &ut "e *et nothin* J actuall+ null (alue ) for NODA5S of %atches %F an! %A as the+ are ha(e null (alue in ENDDATE# Since Oracle results in null (alue for an+ e,'ression ha(in* a null (alue the result of ENDDATESTDATE is a null (alue# SELECT %co!e, st!ate, en!!ate ) st!ate no!a+s 9RO: %atches1 &CODE STDATE NODA5S ))))) ))))))))) ))))))))) %. .2)CAN)7. EH %2 .8)CAN)7. GH %E 27)CAN)7. ED %G 72):AR)7. 2D %8 78)APR)7. E8 %F .2)C=L)7. %A .8)A=<)7. -o"e(er, no" "e "ant to ta e en!in* !ate if %atch is co2'lete! other"ise "e "ant to ta e s+ste2 !ate as en!in* !ate# SELECT %co!e, st!ate, n(l?en!!ate,s+s!ate@ ) st!ate no!a+s 9RO: %atches1 &CODE STDATE NODA5S ))))) ))))))))) ))))))))) %. .2)CAN)7. EH %2 .8)CAN)7. GH %E 27)CAN)7. ED %G 72):AR)7. 2D %8 78)APR)7. E8 %F .2)C=L)7. 87#.AHD8 %A .8)A=<)7. .F#.AHD8 No" "e "ant to inclu!e e(en the status of the %atch, "hich "ill %e CO:PLETED if ENDDATE is not null other"ise R=NN3N<# SELECT %co!e, st!ate, n(l?en!!ate,s+s!ate@ ) st!ate no!a+s, !eco!e?en!!ate,null,6Runnin*6,6Co2'lete!6@ Status 9RO: %atches1 &CODE STDATE NODA5S STAT=S ))))) ))))))))) ))))))))) ))))))))) %. .2)CAN)7. EH Co2'lete! %2 .8)CAN)7. GH Co2'lete! %E 27)CAN)7. ED Co2'lete! %G 72):AR)7. 2D Co2'lete! %8 78)APR)7. E8 Co2'lete! %F .2)C=L)7. 87#.D.. Runnin* %A .8)A=<)7. .F#.D.. Runnin* COALESCE Returns the first not null (alue in the list of (alues# At least one e,'ression out of the *i(en e,'ressions 2ust not %e null# The function is e,ten!e! (ersion of NVL function# COALESCE?e,'r., e,'r2,### , e,'rn@ EXTRACT E,tracts an! returns the (alue of the s'ecifie! !ateti2e fiel! fro2 a !atati2e (alue# EXTRACT ? !atati2efiel! 9RO: !ateti2e@ The follo"in* e,a2'le returns +ear fro2 the current !ate#

SQLK SELECT e,tract? +ear fro2 s+s!ate@ 9RO: !ual1 EXTRACT?5EAR9RO:S5SDATE@ )))))))))))))))))))))))) 2772

GROU$ING DATA
4 03, B5 *lause Some times" !e have to group the ro!s of the table by a particular column and perform certain operations on each group. +or e#ample" you may !ant to display the number of students in each batch. +or this !e have to group ro!s of S'AD-/'S table based on the column B$&D-. 'his !ill create groups ( one for each unique batch code. 'hen using group function $&A/' !e can count the number of ro!s (equivalent to number of students) in each group. /o! let us see ho! the above%mentioned task can be accomplished. 'he follo!ing S-;-$' command groups ro!s of S'AD-/'S table on B$&D- using 40&A9 B: clause. 'hen it counts number of students !e have in each batch using group function $&A/'. S-;-$' bcode" $&A/'(rollno) +0&M students 40&A9 B: bcode@ B$&D- $&A/'(0&;;/&) %%%%% %%%%%%%%%%%%% bH = b= > b> = bK H b? > )e !ill see one more e#ample. In this !e !ill display the total amount of fee paid by each student. +or this !e use 9 :M-/'S table and group function SAM. .ere is the required query. S-;-$' rollno" sum(amount) +0&M payments 40&A9 B: rollno@ 0&;;/& SAM( M&A/') %%%%%%%%% %%%%%%%%%%% H K?GG = K?GG > ?GGG K ?GGG ? ?GGG Z >?GG J >?GG I KGGG N >GGG HG Z?GG HH K?GG )hile you are grouping the data the follo!ing points are to be taken in to account.

+ind out the table from !here the data is to be taken. +ind out the column or columns on !hich the data is to be grouped. +ind out the group function that is to be used to get required aggregate.

40&A9 B: clause is used to specify the column(s) on !hich the ro!s of the table are to be grouped. It means it divides the ro!s into different groups based on the column(s) that are given in 40&A9 B: clause. +or e#ample" in the above e#ample" the ro!s of S'AD-/'S table are to be grouped based on the value of column 0&;;/&. So all ro!s that contain the same roll number !ill be taken as one group. ;ike this the number of groups !ill be equivalent to the number of unique roll numbers in the table. ,oints to remem$er It is important to remember that only the follo!ing can be selected in S-;-$' !hile you are grouping the data. 'he columns that are given in 40&A9 B: clause can be selected. 4roup function 4roup Functions 4roup functions are the functions that are used to perform operations on groups. group%function (DIS'I/$' column) If DIS'I/$' option is used then only distinct (unique) values are taken into account. 'he follo!ing query is used to count the number of students !ho have paid some amount. S-;-$' count(rollno) +0&M payments@ $&A/'(0&;;/&) %%%%%%%%%%%%% HJ But the count includes the duplicates. 'hat means" if the same student has made the payment t!ice then his number !ill be counted for t!ice. But !hat if I !ant to count ho! many students have made some payment !ithout taking duplicatesT. 'he ans!er is DIS'I/$' clause in the group function as sho!n in the ne#t query. S-;-$' count(DIS'I/$' rollno) +0&M payments@ $&A/'(DIS'I/$'0&;;/&) %%%%%%%%%%%%%%%%%%%%% HH 'he DIS'I/$' clause is making $&A/' function count only distinct value and not all values. /ote6 $&A/'(P) counts the number of ro!s in each group. sterisk (P) refers to the entire ro!. :ou can use any column name instead to count the number of not null values in that column. 4roup +unction Description SAM 0eturns the sum of the given column. O4 0eturns the average of the given column. MI/ 0eturns the minimum value in the given column. M [ 0eturns the ma#imum value in the given column. S'DD-O 0eturns the standard deviation of the values in the given column. O 0 0eturns the variance of the values in the given column.. $&A/' 0eturns the number of not null values in the given column. 0eturns number of ro!s" if P is given instead of column. 'he follo!ing query displays the sub,ect and date on !hich the most recent batch of that sub,ect has started. S-;-$' ccode"ma#(stdate) +0&M batches 40&A9 B: ccode@

$$&D- M [(S'D ' %%%%% %%%%%%%%% asp H?%V /%GH c =G%V /%GH ,ava G?% 90%GH ora H?% A4%GH vbnet H=%VA;%GH #ml G=%M 0%GH It is also possible to use group functions !ithout using 40&A9 B: clause. In this case the entire selected ro!s !ill be taken as a single group and group function performs the operation on the entire set of selected ro!s. 'he follo!ing query !ill display the highest course fee. S-;-$' ma#(fee) +0&M courses@ M [(+--) %%%%%%%%% ??GG 4 03, B5 and W!E E clause If ).-0- clause is used along !ith 40&A9 B: then ).-0- clause is e#ecuted first. 'he ro!s that are selected by ).-0- clause !ill be grouped by 40&A9 B: clause. 'he follo!ing query sho!s the number of batches that started for each sub,ect in the last > months. S-;-$' ccode" count(P) count +0&M batches ).-0- monthsDbet!een(sysdate"stdate) UL > 40&A9 B: ccode@ $$&D- $&A/' %%%%% %%%%%%%%% ora H vbnet H In the above query" first ro!s that satisfy the given condition are retrieved. 'hen these ro!s are passed to 40&A9 B: clause for grouping. /ote6 40&A9 B: clause should follo! ).-0- clause" if both are used together. ).-0- clause is used to select the ro!s that are to be used for grouping. 4rouping on more than one column It is possible to group ro!s on more than one column. In this case" the first columns is used to group the data" and then !ithin that group records are again grouped based on second column" and so on. 'he follo!ing query displays the date on !hich the last batch !as taken by each faculty for each sub,ect. S-;-$' fcode" ccode" ma#(stdate) +0&M batches 40&A9 B: fcode"ccode@ +$&D- $$&D- M [(S'D ' %%%%% %%%%% %%%%%%%%% da asp H?%V /%GH da vbnet H=%VA;%GH dh #ml G=%M 0%GH gk ora H=%V /%GH hs c =G%V /%GH hs ,ava G?% 90%GH ,c ora H?% A4%GH !'1I"4 *lause

)hat if you have to select only a fe! groups based on the condition that is using the result of one of the group functionsT. +or e#ample" !hat if you have to display the batches that have more than HG students. . OI/4 clause is used for this purpose. It is used to filter groups based on the given condition. 'he follo!ing e#ample sho!s the courses that have got more than H batch. S-;-$' ccode +0&M batches 40&A9 B: ccode . OI/4 count(P) S H@ $$&D%%%%% ora In the above e#ample" first ro!s of B '$.-S table are grouped on $$&D-. 'hen the query selects the groups that contain more than H ro!. 'he later is achieved using . OI/4 clause" !hich is specially meant to select groups based on the given condition. .ere is a list of important points that are to be noted6 ).-0- clause can be used to check for conditions based on values of columns and e#pressions related to individual ro!s. It cannot be used !ith conditions related to groups. . OI/4 clause is specially designed to evaluate the conditions that are based on group functions such as SAM" and $&A/'. . OI/4 clause cannot be used for conditions that are not related to groups. 'he follo!ing fe! e#ample !ill illustrate the above%mentioned important points. SB;S S-;-$' ccode = +0&M batches > ).-0- count(P) S H K 40&A9 B: ccode@ ).-0- count(P) S H P -00&0 at line >6 &0 %GGN>K6 group function is not allo!ed here 'he above e#ample returns error because ).-0- clause cannot be used !ith group functions. SB;S S-;-$' ccode" count(P) = +0&M batches > 40&A9 B: ccode K . OI/4 enddate is null@ . OI/4 enddate is null P -00&0 at line K6 &0 %GGNJN6 not a 40&A9 B: e#pression In the above e#ample as !e tried to use normal condition using . OI/4 clause &racle returned an error saying that the given e#pression is not acceptable. 'he follo!ing query is valid as . OI/4 clause is used !ith a condition that is related to group by e#pression ( $$&D-. SB;S S-;-$' ccode" count(P) = +0&M batches > 40&A9 B: ccode K . OI/4 length(ccode) S >@ $$&D- $&A/'(P) %%%%% %%%%%%%%% ,ava H vbnet H

3sing W!E E and !'1I"4 together It is possible to use both ).-0- and . OI/4 clauses together. )hen these t!o clauses are used together" first ).-0- clause is to be given then . OI/4 clause. &racle first selects ro!s based on ).-0- clause. fter that it groups the selected data. 'hen groups are selected based on . OI/4 clause. 'he follo!ing query displays the courses that !e started for more than once in the last si# months. S-;-$' ccode" count(P) +0&M batches ).-0- monthsDbet!een(sysdate"stdate) UL Z 40&A9 B: ccode . OI/4 count(P) S H@ $$&D- $&A/'(P) %%%%% %%%%%%%%% ora = 0 DE B5 #ith 4 03, B5 &0D-0 B: clause can be used along !ith 40&A9 B: clause to order the results. )hen used &0D-0 B: clause must be the last clause to be used in the query. S-;-$' fcode" count(P) +0&M courseDfaculty 40&A9 B: fcode &0D-0 B: count(P)@ +$&D- $&A/'(P) %%%%% %%%%%%%%% dh H gk H kl H ,c H s! H da = hs = ,, > /ote6 )hen &0D-0 B: is used !ith 40&A9 B: clause" &0D-0 B: should have either the group by column or group function. 0rder of e6ecution .ere is the order &racle uses to e#ecute different clauses given in S-;-$' command. Selects ro!s based on ).-0- clause. 4roups ro!s based on 40&A9 B: clause. $alculates results for each group. -liminates groups based on . OI/4 clause. 'hen uses &0D-0 B: to order the results. 0//3, and *3BE &racleIi enhanced grouping by adding 0&;;A9 and $AB-. 'hese t!o provide totals at multiple dimensions. 'he follo!ing is the synta# of 0&;;A9. S-;-$' ... 40&A9 B: 0&;;A9 (columns)@ 0&;;A9 creates sub totals from most detailed to grand total. It moves from right to left in the list of columns given in 0&;;A9. Before !e use 0&;;A9" let us see the result of simple group by clause using B '$.-S table. S-;-$' ccode"fcode" count(P)

+0&M batches 40&A9 B: ccode"fcode@ $$&D- +$&D- $&A/'(P) %%%%% %%%%% %%%%%%%%% asp da H c hs H c kl H ,ava hs H ora gk = ora kl H vbnet da = #ml dh H In case of normal 40&A9 B: clause !e get count of each course and faculty. But !hat if you !ant to get total number of batches for each course and also the total number of batches. 'he follo!ing 0&;;A9 creates the required aggregates. S-;-$' ccode"fcode" count(P) +0&M batches 40&A9 B: rollup(ccode"fcode)@ $$&D- +$&D- $&A/'(P) %%%%% %%%%% %%%%%%%%% asp da H asp H c hs H c kl H c = ,ava hs H ,ava H ora gk = ora kl H ora > vbnet da = vbnet = #ml dh H #ml H HG part from ro!s that come from 40&A9 B:" 0&;;A9 generates ne! ro!s that display the number of batches for each course and also total number of batches. In case of total number of batches of a single course the $$&D- is contains course code and +$&D- contains null. In case of total number of batches both $$&D- and +$&D- contain null value. 'he follo!ing query !ill display a meaningful value for these columns. S-;-$' nvl(ccode"2 ;; courses2)" nvl(fcode"2 ll faculty2)" count(P) +0&M batches 40&A9 B: rollup(ccode"fcode)@ /O;($$&D-"2 /O;(+$&D-"2 $&A/'(P) %%%%%%%%%%% %%%%%%%%%%% %%%%%%%%% asp da H asp ll faculty H c hs H c kl H c ll faculty = ,ava hs H ,ava ll faculty H ora gk = ora kl H ora ll faculty >

vbnet da = vbnet ll faculty = #ml dh H #ml ll faculty H ;; courses ll faculty HG 4 03,I"4 function 'his !ill return a value of H if the column1s value is generated by 0&;;A9. So !e can use D-$&D- and 40&A9I/4 functions to get the same result as the above. S-;-$' decode(grouping(ccode)"H"2 ;; courses2"ccode) ccode" decode(grouping(fcode)"H"2 ll faculty2"fcode) fcode" count(P) count +0&M batches 40&A9 B: rollup(ccode"fcode)@ $$&D- +$&D- $&A/' %%%%%%%%%%% %%%%%%%%%%% %%%%%%%%% asp da H asp ll faculty H c hs H c kl H c ll faculty = ,ava hs H ,ava ll faculty H ora gk = ora kl H ora ll faculty > vbnet da = vbnet ll faculty = #ml dh H #ml ll faculty H ;; courses ll faculty HG *3BE 'his generates the same subtotals as 0&;;A9 and plus a fe! more. 'his provides all possible subtotals. +or e#ample in the previous output of 0&;;A9 !e got the number of batches taken by each faculty for each course" number of batches for each course and total number of bathes. $AB- apart from generating all these can also generate subtotals for each faculty. 'hat means it provides number of batches taken by each faculty also. S-;-$' decode(grouping(ccode)"H"2 ;; courses2"ccode) ccode" decode(grouping(fcode)"H"2 ll faculty2"fcode) fcode" count(P) count +0&M batches 40&A9 B: cube(ccode"fcode)@ $$&D- +$&D- $&A/' %%%%%%%%%%% %%%%%%%%%%% %%%%%%%%% asp da H asp ll faculty H c hs H c kl H c ll faculty = ,ava hs H ,ava ll faculty H ora gk = ora kl H ora ll faculty >

vbnet da = vbnet ll faculty = #ml dh H #ml ll faculty H ;; courses da > ;; courses dh H ;; courses gk = ;; courses hs = ;; courses kl = ;; courses ll faculty HG $AB- adds five more ro!s to the output of 0&;;A9. -ach of these ne! ro!s is to display the total number of batches taken by each faculty for all courses.

%OINING TABLES
In a relational database system" the total required data might not be available in a single table. Because if the total data is stored in a single table it !ill lead to a lot of redundancy. So" often !e have to bring the data of t!o or more tables together to get the required information. 'he act of combining t!o or more tables in such a !ay that you retrieve values from the columns of all the tables" to get the required data is called as ,oining. In order to ,oin t!o tables" there must be a common column bet!een those t!o tables. +or e#ample to ,oin $&A0S-S and B '$.-S table" !e use $$&D- column as that is a common column bet!een these t!o tables. 'he follo!ing S-;-$' command is used to get information about batches from both $&A0S-S and B '$.-S table. )e take a ro! from B '$.-S table and get the name of course from $&A0S-S table using $$&D- column of B '$.-S. $$&D- column of B '$.-S is used to get the corresponding ro! from $&A0S-S table. s !e used equal to operator to ,oin these t!o tables" the ,oin is also called as equi%,oin. S-;-$' bcode" batches.ccode" name" fcode" stdate +0&M batches" courses ).-0- batches.ccode L courses.ccode B$&D- $$&D- / M- +$&D- S'D '%%%%% %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% %%%%%%%%% bH ora &racle database gk H=%V /%GH b= asp S9./-' da H?%V /%GH b> c $ programming hs =G%V /%GH bK #ml [M; 9rogramming dh G=%M 0%GH b? ,ava Vava ;anguage hs G?% 90%GH bZ vbnet OB./-' da H=%VA;%GH bJ ora &racle database ,c H?% A4%GH In the above query the follo!ing are the important points. H. '!o tables are used in +0&M clause. 'ables are separated by comma. =. ).-0- clause contains the condition using !hich both the tables are to be ,oined. >. $olumn $$&D- is to be qualified using the table name as it e#its in both the table that are used in +0&M clause. )a$le 'lias

)hile ,oining the table !e have to qualify the columns that are in more than one table using the table name. If table name is lengthy this process could be very tedious. 'able alias is a short name that can be used to refer to the table name in the query. +or e#ample" the above query can be re!ritten using table alias as follo!s6 S-;-$' bcode" b.ccode" name" fcode" stdate +0&M batches b" courses c ).-0- b.ccode L c.ccode B is the alias to table B '$.-S and $ is the alias for $&A0S-S. 'hroughout the query table B '$.-S can be referred using the alias B and $&A0S-S using alias $. s the purpose of using an alias is to shorten the reference to table" alias is generally very short. lso remember alias is available only in the query in !hich it is created. ,roduct of t#o ta$les )hile tables are ,oined" if ).-0- clause is not given then it results in 90&DA$' of the table that are being ,oined. 9roduct is the result in !hich each ro! of first table is ,oined !ith each ro! of the second table. 'his is also called as $artesian product. 'he follo!ing e#ample !ill ,oin S-;-$' bcode" b.ccode" name" fcode" stdate" enddate +0&M batches b" courses c@ 'he above command !ill result in K= (ZP J) ro!s as !e have Z ro!s in $&A0S-S and J ro!s in B '$.-S table. 9roduct is generally the result of an error than the desired result. Voin condition and normal condition )hile ,oining t!o tables the condition used to ,oin the table is called as ,oin condition. s !e have above" !ithout ,oin condition" the result of ,oining !ill be product of the table. EAui-8oin part from the ,oin condition" !hich is required for ,oining" normal conditions can also be given in ).-0- clause. 'hen &racle uses normal condition to filter ro!s and then ,oins the filtered ro!s based on the ,oin condition. 'he follo!ing query !ill get the details of batches that are completed along !ith name of the course. 'o get the name of the course it uses $&A0S-S table and to select only those batches that are completed" it uses a normal condition as follo!s. S-;-$' bcode" b.ccode" name" fcode" stdate +0&M batches b" courses c ).-0- b.ccode L c.ccode and enddate IS /&' /A;; B$&D- $$&D- / M- +$&D- S'D '%%%%% %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% %%%%%%%%% bH ora &racle database gk H=%V /%GH b= asp S9./-' da H?%V /%GH b> c $ programming hs =G%V /%GH bK #ml [M; 9rogramming dh G=%M 0%GH b? ,ava Vava ;anguage hs G?% 90%GH It is also possible to order the result of ,oin using &0D-0 B: clause as follo!s. S-;-$' bcode" b.ccode" name" fcode" stdate +0&M batches b" courses c ).-0- b.ccode L c.ccode and enddate IS /&' /A;; &0D-0 B: stdate@ 'he above query displays the result of the ,oin in the ascending order of S'D '- column. Voining more than t!o tables Vust like ho! t!o tables are ,oined" more than t!o tables can also be ,oined to get the required information. +or e#ample" in the above query !e retrieved information about batches and course name. )hat if !e !ant to get name of the faculty and not ,ust the codeT 'hen !e have to use + $A;': table along !ith B '$.-S and $&A0S-S table. 'o

get the details of batches along !ith name of the course and name of the faculty" give the follo!ing6 S-;-$' bcode"c.name course" f.name faculty" stdate +0&M batches b" courses c" faculty f ).-0- b.ccode L c.ccode and b.fcode L f.fcode B$&D- $&A0S- + $A;': S'D '%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% bH &racle database 4eorge <och H=%V /%GH b= S9./-' Dan ppleman H?%V /%GH b> $ programming .erbert Schildt =G%V /%GH bK [M; 9rogramming David .unter G=%M 0%GH b? Vava ;anguage .erbert Schildt G?% 90%GH bZ OB./-' Dan ppleman H=%VA;%GH bJ &racle database Vason $ouchman H?% A4%GH 'he query takes data from three tables ( B '$.-S" $&A0S-S and + $A;':. It uses $$&D- to ,oin B '$.-S table !ith $&A0S-S table. It uses +$&D- to ,oin B '$.-S table !ith + $A;': table. )hen t!o or more tables are ,oined then the minimum number of conditions to be given is derived from the follo!ing formula6 /umber of ,oin conditions L /umber of tables being ,oined % H If more than one column is used to ,oin tables then the number of ,oin conditions may be even more. Self Boin )hen a table is ,oined !ith itself it is called as self%,oin. 'his is a variant of ,oin. In this t!o copies of the same table are taken and ,oined as if they are t!o different types. 'he follo!ing e#ample demonstrates self%,oin. It displays the details of batches that started after batch B>. )e take t!o copies of B '$.-S table. In first copy !e anchor at the ro! !here batch code is B>. 'hen in the second copy of the table !e take ro! !here S'D '- of the batch is more than S'D '- of first copy. Since !e already anchored at ro! !ith batch code B> the S'D '- of first copy !ill be the starting date of batch B>. S-;-$' b=.P +0&M batches bH" batches b= ).-0- bH.bcode L 2b>2 and b=.stdate S bH.stdate@ B$&D- $$&D- +$&D- S'D '- -/DD '- 'IMI/4 %%%%% %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%% b> c hs =G%V /%GH =J%+-B%GH > b> c hs =G%V /%GH =J%+-B%GH > b> c hs =G%V /%GH =J%+-B%GH > b> c hs =G%V /%GH =J%+-B%GH > In the above e#ample bH and b= are t!o alias to the table B '$.-S. Selection b=.P !ould mean !e !ant to select all columns from first table. 0uter Boin )hen t!o tables are ,oined" only the ro!s that contain the common keys are selected. 'hat means if B '$.-S and $&A0S-S tables are ,oined then you get the details of courses that have corresponding values in B '$.-S table. If a course has no corresponding ro! (batch) in B '$.-S table then it is not included in the output. ;et us have a look at the follo!ing data !e have in B '$.-S and $&A0S-S tables. SB;S S-;-$' ccode"name +0&M courses@ $$&D- / M%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ora &racle database vbnet OB./-'

c $ programming asp S9./-' ,ava Vava ;anguage #ml [M; 9rogramming cs $ Sharp SB;S S-;-$' bcode"ccode"stdate +0&M batches@ B$&D- $$&D- S'D '%%%%% %%%%% %%%%%%%%% bH ora H=%V /%GH b= asp H?%V /%GH b> c =G%V /%GH bK #ml G=%M 0%GH b? ,ava G?% 90%GH bZ vbnet H=%VA;%GH bJ ora H?% A4%GH 'he follo!ing S-;-$' command !ill retrieve information from both the tables. S-;-$' c.ccode" name"fee" bcode" stdate" enddate +0&M courses c" batches b ).-0- c.ccode Lb.ccode &0D-0 B: c.ccode $$&D- / M- +-- B$&D- S'D '- -/DD '%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% %%%%% %%%%%%%%% %%%%%%%%% asp S9./-' ?GGG b= H?%V /%GH G?%M 0%GH c $ programming >?GG b> =G%V /%GH =J%+-B%GH ,ava Vava ;anguage K?GG b? G?% 90%GH HG%M :%GH ora &racle database K?GG bH H=%V /%GH =G%+-B%GH ora &racle database K?GG bJ H?% A4%GH vbnet OB./-' ??GG bZ H=%VA;%GH #ml [M; 9rogramming KGGG bK G=%M 0%GH >G%M 0%GH In the above ,oin" !e got the information about all courses e#cept 7$ Sharp8 because there is no corresponding ro! in B '$.-S table for course code $S. 'hat means if parent table contains ro!s that do not have corresponding ro!s in child table" then &racle !ill not retrieve the values of those ro!s of parent table. &uter ,oin allo!s you to retrieve the ro!s from parent table even though there is no corresponding ro!s for the parent table in the child table. In the follo!ing e#ample" !e get details of course $S though it doesn1t have any ro! in B '$.-S table. S-;-$' c.ccode" name"fee" bcode" stdate" enddate +0&M courses c" batches b ).-0- c.ccode Lb.ccode (M) &0D-0 B: c.ccode@ $$&D- / M- +-- B$&D- S'D '- -/DD '%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% %%%%% %%%%%%%%% %%%%%%%%% asp S9./-' ?GGG b= H?%V /%GH G?%M 0%GH c $ programming >?GG b> =G%V /%GH =J%+-B%GH cs $ Sharp JGGG ,ava Vava ;anguage K?GG b? G?% 90%GH HG%M :%GH ora &racle database K?GG bH H=%V /%GH =G%+-B%GH ora &racle database K?GG bJ H?% A4%GH vbnet OB./-' ??GG bZ H=%VA;%GH #ml [M; 9rogramming KGGG bK G=%M 0%GH >G%M 0%GH $ompare this output !ith earlier output. .ere as !e used outer ,oin by using (M) on the right of B '$.-S table. 'he plus (M) on the right of shorter table (taking into account unique

value of $$&D- column) is to add e#tra null ro!s !ith values in common column" that do e#ist in the left table" but not in the right table" and then ,oin the ro!s. /ote6 )hen outer ,oin is used" the order in !hich tables are listed in +0&M clause is important. lso remember" (M) is to be used on the right of the table that is to be e#tended !ith null ro!s. s you can see in the above output" in the ro! $S there is no data for B$&D-" S'D '- and -/DD '- columns. 'his is understandable as there is no ro! in B '$.-S table for course $S. lso remember there is no possibility of having ro!s in B '$.-S table that do not correspond to any course code in $&A0S-S table. It is possible to have a parent ro! !ithout child ro!s" but it is not possible to have a child ro! !ithout a parent ro!. If !e have defined foreign key constraint on the child table" this condition is implemented by &racle !henever you insert or update ro!s in child table. '"SI Boin &racleNi provided standard /SI ,oin synta#. 'his is different from the synta# that !e use in current version of &racle to ,oin tables. &racleNi has also provided full support for outer% ,oin and !ith ne! synta# of /SI ,oin. /SI Voin added some ne! key!ords to &racle. 'he follo!ing is an e#ample of ,oin in &racleIi and then in &racleNi using /SI ,oin. 'he follo!ing command ,oins S'AD-/'S table !ith $&A0S-S table using &racleIi ,oin synta#. S-;-$' rollno"sname" coursename" duration +0&M students s" courses c ).-0- s.coursecode L c.coursecode@ 'he follo!ing command ,oins S'AD-/'S table !ith $&A0S-S table using S-;-$' rollno"sname"coursename"duration +0&M students s I//-0 V&I/ courses c &/ c.coursecode L s.coursecode@ 'he biggest advantages !ith this ne! synta# is it doesn2t allo! you to forget to give ,oin condition. s you kno! that is one of the common mistakes among beginners of &racle. If you omit ,oin condition then it results in $artesian 9roduct. /SI ,oin synta# makes condition after &/ clause mandatory. 3SI"4 clause If you are dealing !ith equi%,oin then it is possible to further simplify the ,oin synta# !ith ASI/4 clause as follo!s6 S-;-$' rollno"sname"coursename"duration +0&M students s I//-0 V&I/ courses c ASI/4 (coursecode)@ ASI/4 clause in the above command specifies that tables S'AD-/'S and $&A0S-S are to be ,oined !hen they have the common values in the column $&A0S-$&D-. )hile you are dealing !ith &/ clause $&A0S-$&D- column from both S'AD-/'S and $&A0S-S is available. So you can select the column as follo!s6 S-;-$' rollno"sname"c.coursecode " coursename"duration +0&M students s I//-0 V&I/ courses c on c.coursecode L s.coursecode@ /SI ,oin synta#.

But if !e are using ASI/4 clause then only one copy of the columns that are used in ASI/4 caluse !ill be available. 'hat means you do not get t!o versions of the column in the query. So if you use ASI/4 clause for the above query referring to $&A0S-$&D- as $.$&A0S-$&D- is invalid as there is only one copy of $&A0S-$&D- column in the query. 'he follo!ing query is a re!rite of the previous query. S-;-$' rollno"sname"coursecode " coursename"duration +0&M students s I//-0 V&I/ courses c ASI/4 (coursecode)@ 0uter Boin /SI ,oin also added support for outer ,oin. ssume that !e !ant to display the details of courses that do not have any students. 'he follo!ing query uses &racle2s proprietry synta# for outer ,oin. S-;-$' c.coursecode" coursename" duration" rollno"sname +0&M courses c" students s ).-0- c.coursecode L s.coursecode(M)@ 'he follo!ing is the ne! /SI outer%,oin synta#6 S-;-$' rollno"sname"coursename"duration +0&M courses c ;-+' &A'-0 V&I/ students s &/ c.coursecode L s.coursecode@ 'he same query can be !ritten using 0I4.' &A'-0 V&I/ also if you change the order in !hich tables are used. ;-+' &A'-0 V&I/ and 0I4.' &A'-0 V&I/ are funtionally same e#cept the order in !hich tables are given. +or ;-+' &A'-0 V&I/ parent table is given on left and for 0I4.' &A'-0 V&I/ child table is given on the left. &uter%,oin using 0I4.' &A'-0 V&I/. S-;-$' rollno"sname"coursename"duration +0&M students s 0I4.' &A'-0 V&I/ courses c &/ c.coursecode L s.coursecode@ It may take some time to get used to this /SI ,oin synta#es" but it is !orth as it !ill your code more protable. nd moreover once you get used to this ne! synta#" you !ill find it more easier and less prone to errors. SE) 0perators S-' operators combine the results of t!o queries into one result. 'he follo!ing are the available S-' operators. 'hese operators are part of 0elational lgebra operators. 0perator A/I&/ A/I&/ ;; I/'-0S-$' MI/AS What it does? 0eturns unique ro!s of both the queries. 0eturns all ro!s selected by both the queries including duplicates. 0eturns common ro!s selected by both the queries. 0eturns ro!s that e#ist in the first query but not in the second query.

ssume there is a table called &;D$&A0S-S !ith the follo!ing ro!s6 S-;-$' P +0&M oldcourses@ $$&D- / M%%%%% %%%%%%%%%%%%%%%%%%%% ora &racleIi c $ ;anguage pas 9ascal ;anguage lH=> ;otus H=> 'o get the list of all the courses from $&A0S-S and &;D$&A0S-S tables by eliminating duplicates" give the follo!ing6 S-;-$' ccode +0&M oldcourses union

$$&D%%%%% asp c cs ,ava lH=> ora pas vbnet #ml

S-;-$' ccode +0&M courses@

'hough courses &0 and $ e#ist in both the tables they are displayed only for once as A/I&/ ignores duplicate entries. A/I&/ ;; is used to retrieve all ro!s from both the tables. It doesn1t ignore duplicates. S-;-$' ccode +0&M oldcourses union all S-;-$' ccode +0&M courses@ $$&D%%%%% ora c pas lH=> ora vbnet c asp ,ava #ml cs 'he follo!ing query retrieves all courses that e#ists in both $&A0S-S table and &;D$&A0S-S table using I/'-0S-$' operator6 S-;-$' ccode +0&M courses intersect S-;-$' ccode +0&M oldcourses@ $$&D%%%%% c ora 'o get the list of courses that e#ist in &;D$&A0S-S but not in $&A0S-S table" give the follo!ing query !ith MI/AS operator6 S-;-$' ccode +0&M oldcourses minus S-;-$' ccode +0&M courses@ $$&D%%%%% lH=> pas 0A;-S to be follo!ed !hile using S-' operators H. Both queries should select the same number of columns.

=. $orresponding columns must be of the same data type. .o!ever the length and name of the columns may be different. >. $olumn names of first query !ill be column headings. K. /ull values are treated as identical. /ormally t!o null values are not equal. But !hen dealing !ith S-' operators" if &racle encounters t!o null values" one in first table and another in second table then &racle !ill treat them as identical. 'he follo!ing e#ample !ill make the last point clear. ssume !e have a ro! in first table !ith values HG and null for columns $H and $= and another ro! in the second table !ith same values (HG and null) for columns $H and $=. )hen you use A/I&/ operator" &racle !ill take null values in column $= as equal and display the ro! !ith HG and null only for once.

&IEWS
What Is ' 1ie#? vie! is a !indo! through !hich you access a portion of one or more tables. Oie! itself doesn2t contain any data but it refers to the data of a table on !hich it is based. 'he table on !hich the vie! is based is called as base table. vie! is also called as 7virtual table8 as it can be used !hen a table can be used. Oie! retrieves the data by e#ecuting the query and presents the data in the form of a table. Oie!s are used to let users access only the portion of the data that they are supposed to access. Oie!s are very commonly used ob,ects in &racle. In fact ob,ects such as AS-0D' B;-S" AS-0D$&/S'0 I/'S etc." are not actually tables and instead they are vie!s. Why We "eed ' 1ie#? vie! is required in several cases. ;et us start !ith a simple requirement. ssume the table $&A0S-S is o!ned by user 7+I4&8. s the o!ner of the table +igo !ill have all the privileges on that table. Aser +igo no! !ants another user ( 0aul to access $&A0S-S table. 'o this effect +igo can grant permission to 0aul. But +igo doesn1t !ant 0aul to access column +--. If +igo grants permission to 0aul then 0aul !ill have complete access to table and +igo cannot stop 0aul from accessing +-- column. So +igo creates a vie! on $&A0S-S table that includes everything from $&A0S-S table e#cept +--. 'hen +igo grants permission on the vie! to 0aul and not on the base table. Since 0aul has access only to the vie!" he can access !hatever data is presented by the vie!. vie! in the above requirement is quite ideal for t!o reasons. H. It fulfills the requirement !ithout storing a separate copy of the data. vie! doesn1t store any data of its o!n and takes the data from base table. =. s the data is taken from base table" accurate and up%to%date information is provided to 0aul. :et the column to be hidden from 0aul is hidden as it is not part of the vie!. 'he follo!ing are the other important applications of vie!s6 9rovides an e#tra layer on the top of table allo!ing only a predetermined ro!s or columns to be accessed. llo!s comple# queries to be stored in the database. vie! stores the query that is used to create it in the database. It uses the query to retrieve the data from the base table(s).

If a comple# query is to be referred again and again then it can be stored in the form of a vie!. $an present the data of the table in different forms. +or instance" the name of the columns can be changed and t!o or more columns can be presented as one column or split one column as t!o or more columns. $an isolate application from the changes in the definition of the table. In the ne#t section let us see ho! to create and use vie!.

*reating and using 7ie#s vie! is created using $0- '- OI-) command. t the time of creating the vie!" !e have to give the name of the vie! and the query on !hich the vie! is based. +or e#ample" to create a vie! that takes everything from $&A0S-S table e#cept +-- column" given the follo!ing $0- '- ' B;- command. SB;S $0- '- OI-) courseDvie! = as > S-;-$' ccode"name"duration" prerequisite +0&M courses@ Oie! created. In the above e#ample" $&A0S-DOI-) is the name of the vie! and $&A0S-S is the base table. $&A0S-DOI-) vie! can access all columns of the table e#cept +-- column. $0- '- Q&0 0-9; $-R Q+&0$- R OI-) vie!name Q(column%name" column%name)R S Buery Q!ith check optionR@ /ote6 &0D-0 B: clause cannot be used in query used !ith $0- '- OI-) command. &0 0-9; $- &ption llo!s a vie! to be created even if one already e#ists. 'his allo!s altering vie! !ithout dropping" recreating and re%granting ob,ect privileges. +&0$- &ption llo!s vie! to be created even if the base table doesn2t e#ist. .o!ever" the base table should e#ist before the vie! is used. &nce a vie! is created" a vie! can be used similar to a table. +or e#ample" you can use S-;-$' command !ith $&A0S-DOI-) as follo!s6 S-;-$' P +0&M courseDvie!@ $$&D- / M- DA0 'I&/ 90-0-BAISI'%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%% ora &racle database =? )indo!s vbnet OB./-' >G )indo!s and programming c $ programming =G $omputer !areness asp S9./-' =? Internet and programming ,ava Vava ;anguage =? $ language #ml [M; 9rogramming H? .'M;"Scripting" S9]VS9 cs $ Sharp >G $ ;anguage s !e have seen before" a vie! can be used ,ust like a table. 'hat is the reason a vie! is called as virtual table. It is also possible to select columns of a vie!" as it is illustrated belo!6 S-;-$' name" duration +0&M courseDvie!@ / M- DA0 'I&/ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% &racle database =? OB./-' >G $ programming =G S9./-' =? Vava ;anguage =? [M; 9rogramming H? $ Sharp >G

In the same !ay it is possible to filter ro!s ,ust like ho! it is done !ith tables. S-;-$' P +0&M courseDvie! ).-0- duration S =?@ $$&D- / M- DA0 'I&/ 90-0-BAISI'%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% %%%%%%%%%%%%%%%%%%% %%%%%%%%%%% vbnet OB./-' >G )indo!s and programming cs $ Sharp >G $ ;anguage Simplifying Auery using 7ie# vie! apart from providing access control can also be used to simplify query. vie! is also called as 7stored query8. 'he query given at the time of creating vie! is stored by &racle and used !henever the vie! is used. ll that you get in the vie! is the data retrieved by the query. Since a query is stored for vie!" a comple# query can be stored in the form of a vie!. 'he follo!ing e#ample creates $0- '- OI-) coursecount as S-;-$' ccode" count(P) nobatches " ma#(stdate) lastdate +0&M batches 40&A9 B: ccode@ /o! instead of giving the lengthy query" it is possible to get the details using vie! $&A0S-$&A/' as follo!s6 SB;S S-;-$' P +0&M coursecount@ $$&D- /&B '$.-S ; S'D '%%%%% %%%%%%%%% %%%%%%%%% asp H H?%V /%GH c H =G%V /%GH ,ava H G?% 90%GH ora = H?% A4%GH vbnet H H=%VA;%GH #ml H G=%M 0%GH If query used to create the vie! contains any e#pression then the e#pression must be given alias. 'he alias of the e#pression becomes the name of the column in the vie!. In the above e#ample the e#pression count(P) is given the alias /&B '$.-S and e#pression ma#(stdate) is given the alias ; S'D '-. )hile referring to vie!" !e have to use these aliases to refer to the values of corresponding e#pressions. 'he follo!ing query !ill display course code and most recent batches starting date using $&A0S-$&A/' vie!. S-;-$' ccode" lastdate +0&M coursecount@ $$&D- ; S'D '%%%%% %%%%%%%%% asp H?%V /%GH c =G%V /%GH ,ava G?% 90%GH ora H?% A4%GH vbnet H=%VA;%GH #ml G=%M 0%GH. 'he follo!ing query !ill display the courses for !hich !e have started more than one batch so far. S-;-$' P +0&M coursecount ).-0- nobatches S H@ $$&D- /&B '$.-S ; S'D '%%%%% %%%%%%%%% %%%%%%%%% ora = H?% A4%GH

/ote6 'hough a column is derived from group function" it can be used !ith ).-0- clause if it is part of the vie!. ,resenting data in different forms using 7ie# 'he follo!ing e#ample demonstrates ho! vie!s can be used to present the data of a table in different forms. + $A;': table contains the name of the faculty in / M- column. /o! for some application" !e have to split the name of the faculty into first name and last name. 'his task can be achieved using a vie!. /o need to restructure the table. 'he follo!ing vie! presents name of the faculty as first name and last name. $0- '- OI-) facultyDnames as S-;-$' fcode" SABS'0(name"H" I/S'0(name"2 2) % H ) firstname" SABS'0(name" I/S'0(name"2 2)M H) lastname +0&M faculty@ /o! it is possible to get the name of the faculty in t!o parts ( firstname and lastname. S-;-$' P +0&M facultyDnames@ +$&D- +I0S'/ M- ; S'/ M%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% gk 4eorge <och da Dan ppleman hs .erbert Schildt dh David .unter s! Stephen )alther kl <evin ;oney ,, Vamie Va!orski ,c Vason $ouchman /o! the task of getting the details of faculty !here lastname contains more than ? characters has become easy as sho!n belo!. SB;S S-;-$' P +0&M facultyDnames ).-0- length(lastname) S ?@ +$&D- +I0S'/ M- ; S'/ M%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% da Dan ppleman hs .erbert Schildt dh David .unter s! Stephen )alther ,, Vamie Va!orski ,c Vason $ouchman Isolating application from changes in definition of ta$le 'his is another important application of a vie!. Oie! can be used to isolate applications from the structure of the tables. 'his is achieved by creating a vie! on the required tables and using the vie! instead of the base table. 'he advantage !ith this is that if the structure of the tables is ever changed then !e ,ust need to recreate the vie! to continue to provide the same information as before the change to structure of the base tables. So that though the structure of the table is ever modified" the application !ill not be effected by the change as application uses a vie! to get the required data. ;ets us see a small e#ample to understand !hat I mean by isolating application from structure of the base tables. )e !ant to access B$&D-" $$&D-" S'D '- and +-- of each batch. 'his can be done by using a query to ,oin B '$.-S and $&A0S-S tables as follo!s6 S-;-$' bcode" b.ccode" fee" stdate +0&M batches b" courses c ).-0- b.ccode L c.ccode@ B$&D- $$&D- +-- S'D '-

%%%%% %%%%% %%%%%%%%% %%%%%%%%% bH ora K?GG H=%V /%GH b= asp ?GGG H?%V /%GH b> c >?GG =G%V /%GH bK #ml KGGG G=%M 0%GH b? ,ava K?GG G?% 90%GH bZ vbnet ??GG H=%VA;%GH bJ ora K?GG H?% A4%GH 'his is fine but !hat if +-- column is moved from $&A0S-S table to B '$.-S table. 'hen the query needs to access only B '$.-S table and $&A0S-S table is not required. So the query is to be re!ritten as follo!s6 S-;-$' bcode" ccode" fee" stdate +0&M batches@ 'hat means the application is to be modified to re!rite the query. 'he column +-- of $&A0S-S table may have been used in several places and no! !e have to modify all those commands. .o! a vie! can solve the problemT Instead of directly accessing tables" it is possible to create a vie! on the required tables. +or e#ample" !e create a vie! to get B$&D-" $$&D-" +-- and S'D '- from $&A0S-S and B '$.-S table as follo!s6 $0- '- OI-) batchdetails as S-;-$' bcode" b.ccode " fee" stdate +0&M batches b" courses c ).-0- b.ccode L c.ccode@ 'hen !e access the data using this vie! as follo!s6 S-;-$' P +0&M batchdetails@ If column +-- is removed from $&A0S-S table and placed in B '$.-S table" then !e recreate the vie! to access only B '$.-S table to get the required data. $0- '- &0 0-9; $- OI-) batchdetails as S-;-$' bcode" ccode " fee" stdate +0&M batches@ 'hen accessing the vie! B '$.D-' I;S !ill give the same data in spite of a change in the structure of underlying tables. 'hat means the application !ill have to give as S-;-$' command to get the information as follo!s6 S-;-$' P +0&M batchdetails@ .o!ever" internally" &racle is using only B '$.-S table to get the data. ll this process !ill be hidden from user and he is a!are of only the presence of the vie!. s you can see" that this operation !ill make the programs totally independent of the structure of the database. Because even the structure of the tables changes" the vie! built on the tables are to be rebuild to reflect ne! structure of the tables. But that doesn1t effect the application. Storage of 7ie# &racle stores the query given at the time of creating vie! in data dictionary. )henever the vie! is referred" &racle e#ecutes the query and retrieves the data from the base tables. )hatever data is retrieved that is provided as the data of the vie!. Since all that &racle stores regarding vie! is only the query" a vie! is also called as stored query. vie! may be based on tables or other vie!s or even snapshots (a replica of remote data). 1ie#s and dependence vie! is dependent on base tables. Base tables may be either real tables or again vie!s. )hether a vie! is valid or not depends on the availability of the base tables. 'he follo!ing e#amples !ill illustrate the dependency. ssume !e have a table 'H created as follo!s6

$0- '- ' B;- tH ( cH number(?)" c= number(?))@ ;et us no! create a vie! on this table as follo!s6 $0- '- OI-) vH as S-;-$' P +0&M tH@ &racle stores the query in data dictionary for vie!. )hen you use P in query" &racle e#pands it to include all columns of the tables. 'he follo!ing query sho!s the query stored by &racle in data dictionary. SB;S S-;-$' te#t = +0&M userDvie!s > ).-0- vie!Dname L 2OH2@ '-[' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% S-;-$' a$Ha"a$=a +0&M tH /ote6 )e must use uppercase letter for ob,ect name !hile querying data dictionary as &racle stores ob,ect name in uppercase. /o! let us see !hat happens if you drop the table 'H. D0&9 ' B;- tH@ 'he vie! still e#ists and the definition of the table !ill remain intact. But the vie! cannot be used as the base table is not e#isting. So referring to vie! !ill displays the follo!ing error message. SB;S S-;-$' P +0&M vH@ S-;-$' P +0&M vH P -00&0 at line H6 &0 %GKGZ>6 vie! aB&&<.OHa has errors &racle marks vie!s that are dependent on the base table that is dropped as Invalid. :ou can get the status of any ob,ect using AS-0D&BV-$'S table. S-;-$' status +0&M userDob,ects ).-0- ob,ectDname L 2OH2@ S' 'AS %%%%%%% I/O ;ID .o!ever" if you recreate the table and then try to refer to the vie! the vie! !ill be compiled and status of the vie! is changed to valid again. $0- '- ' B;- tH ( cH number(?)" c= number(?)" c> number(?))@ t the time of recreating the table &racle ,ust checks !hether columns $H and $= are present and doesn1t mind if base table contains some ne! columns. fter the table is recreated" if you refer to vie! then &racle !ill try to recompile the vie! and as it finds out that all the required columns are in the base table it !ill validate the vie!. :ou can get the status of the vie! using AS-0D&BV-$'S again. S-;-$' status +0&M userDob,ects ).-0- ob,ectDname L 2OH2@ S' 'AS %%%%%%% O ;ID In the above if table is recreated but if either column $H or $= is present the vie! cannot be made valid. /ote6 'he data types of the columns in the base table do not matter at the time of compiling the vie!. 'hat means in the above e#ample even columns $H is of O 0$. 0= type in table 'H still the vie! !ill be made valid. Because &racle precisely looks for columns $H and $= in table 'Hand not for any specific data type.

*hanging Base )a$le )hrough 1ie# 'hough vie! is generally used to retrieve the data from base table" it can also be used to manipulate base table. .o!ever" not every vie! can be used to manipulate base table. 'o be updatable a vie! must satisfy certain conditions. )e !ill discuss !hen and ho! a vie! can be used to update base table. 'he follo!ing manipulations can be done on base table through vie!6 Delete ro!s from base table Apdate data of base table Insert ro!s into base table If a vie! is to be inherently updatable" then it must not contain any of the follo!ing constructs in its query6 set operator DIS'I/$' operator n aggregate function 40&A9 B:" &0D-0 B:" $&//-$' B:" or S' 0' )I'. clause collection e#pression in a S-;-$' list subquery in a S-;-$' list Boins %#ith some e6ceptions& If the vie! contains columns derived from pseudo columns or e#pression the A9D 'command must not refer to these columns. ;et us understand ho! to manipulate the base table through vie!. $reate a vie! called &0 B '$.-S as follo!s6 $0- '- OI-) orabatches as S-;-$' bcode" stdate" enddate" timing +0&M batches ).-0- ccode L 2ora2@ s this vie! doesn1t violate any of the conditions mentioned above" it can be used to delete and update base table as follo!. 'he follo!ing D-;-'- command !ill delete the ro! from base table ( B '$.-S ( !here batch code is bJ. D-;-'- +0&M orabatches ).-0- bcode L 2bJ2@ It is also possible to update the -/DD '- of batch BH as follo!s6 A9D '- orabatches set enddate L sysdate ).-0- bcode L2bJ2@ 3pdating 8oin 7ie#s It is also possible to update a ,oin vie! (a vie! that has more than one base table)" provided the follo!ing conditions are true. 'he DM; operations must manipulate only one of the underlying tables. +or A9D '- all columns updated must be e#tracted from a key%preserved table. +or D-;-'- the ,oin must have one and only one key%preserved table. +or I/S-0' all columns into !hich values are to be inserted must come from a key% preserved table. ll /&' /A;; columns of the key%preserved table must be included in the vie! unless !e have specified D-+ A;' values for /&' /A;; columns. -ey-preser7ed ta$le table is key preserved if every key of the table can also be a key of the result of the ,oin. So" a key%preserved table has its keys preserved through a ,oin. 'o understand !hat is a key%preserved table" take the follo!ing vie!. $0- '- OI-) monthDpayments as S-;-$' p.rollno" name" dp" amount +0&M payments p" students s ).-0- p.rollno L s.rollno@ In the above vie!" table 9 :M-/'S is key%preserved table. So it is possible to make changes to the table even though the vie! is based on t!o tables. 'he follo!ing A9D '- command !ill update M&A/' columns. A9D '- monthDpayments set amount L K?GG

).-0- rollno L H and trunc(dp) L2HG%,an%GH2@ .o!ever" it is not possible to change / M- as follo!s6 A9D '- monthDpayments set /ameL2<och 4eorge2 ).-0- rollno L H@ A9D '- monthDpayments set /ameL2<och 4eorge2 P -00&0 at line H6 &0 %GHJJN6 cannot modify a column !hich maps to a non keypreserved table $olumn / M- doesn1t belong to key%preserved table. So it is not updatable. 4etting information about updateable columns It is possible to get the names of the columns that can be modified in a vie! using AS-0DA9D ' B;-D$&;AM/S data dictionary vie!. S-;-$' columnDname" updatable" insertable" deletable +0&M userDupdatableDcolumns ).-0- tableDname L 2M&/'.D9 :M-/'S2 $&;AM/D/ M- A9D I/S D-; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% %%% 0&;;/& :-S :-S :-S / M- /& /& /& D9 :-S :-S :-S M&A/' :-S :-S :-S WI)! *!E*- 0,)I0" 'his option is used to prevent updations and insertions into base table through vie! that the vie! cannot later retrieve. ;et us create a vie! that retrieves information about payments !here amount paid is more than >GGG. $0- '- OI-) highDpayments as S-;-$' P +0&M payments ).-0- amount S >GGG@ 'he follo!ing is the data that is retrieved by the vie!. S-;-$' P +0&M highDpayments@ 0&;;/& D9 M&A/' %%%%%%%%% %%%%%%%%% %%%%%%%%% H HG%V /%GH K?GG = HH%V /%GH >?GG ? HZ%V /%GH ?GGG Z HK%V /%GH >?GG J H?%V /%GH >?GG HG HG% 90%GH K?GG HH HG% 90%GH >?GG s the vie! is updatable" &racle allo!s any change to be made to the vie!. +or e#ample the follo!ing A9D '- statement !ill change the amount paid by student HH to =?GG. A9D '- highDpayments set amount L =?GG ).-0- rollno L HH@ fter the change is made if !e try to retrieve the data from the vie!" it !ill /&' retrieve ro! that !e have updated as it no longer satisfies the condition ( M&A/' S >GGG. S-;-$' P +0&M highDpayments@ 0&;;/& D9 M&A/' %%%%%%%%% %%%%%%%%% %%%%%%%%% H HG%V /%GH K?GG = HH%V /%GH >?GG ? HZ%V /%GH ?GGG

Z HK%V /%GH >?GG J H?%V /%GH >?GG HG HG% 90%GH K?GG 'hat means vie! allo!s the changes even though the changes !ill make the ro!s of the base table irretrievable after the change. .o!ever" &racle allo!s you to prevent such changes by using )I'. $.-$< &9'I&/ option at the time of creating vie!. 'he follo!ing is the modified $0- '- OI-) command to create .I4.D9 :M-/' vie!. It uses )I'. $.-$< &9'I&/ to make sure that all updations and insertion that are made to the base table are retrievable by the vie!. $0- '- &0 0-9; $- OI-) highDpayments as S-;-$' P +0&M payments ).-0- amount S >GGG !ith check option constraint highDpaymentD!co@ 'he above command replaces the e#isting vie! !ith the ne! version. 'hat is the reason !hy !e used &0 0-9; $- option of $0- '- OI-) command. 'he command added )I'. $.-$< &9'I&/ and assigned a name to that constraint. If !e do not give any name then &racle automatically assigns a name to this constraint. /o! let us see !hat happens if !e try to insert a ro! into the base table ( 9 :M-/'S through .I4.D9 :M-/'S vie! !ith =GGG as the value for M&A/' column. SB;S I/S-0' I/'& highDpayments values (HH"sysdate" =GGG)@ I/S-0' I/'& highDpayments values (HH"sysdate" =GGG) P -00&0 at line H6 &0 %GHKG=6 vie! )I'. $.-$< &9'I&/ !here%clause violation s you can see" )I'. $.-$< &9'I&/ doesn1t allo! the insertion since the condition given in the query of the vie! is not satisfied by the data given in insertion. .o!ever" it is possible to insert the same ro! directly to base table ( 9 :M-/'S" but it cannot be inserted through the vie! .I4.D9 :M-/'S if vie! cannot retrieve ro! after the insertion. Dropping a 1ie# D0&9 OI-) command is used to drop a vie!. Dropping a vie! has no effect on the base tables on !hich vie! is based. Asers !ho !ere accessing the data of the base tables using vie! !ill no longer be able to access the data of the base tables. D0&9 OI-) vie!Dname@

SUB'UERIES
What Is ' Su$Auery subquery is a query !ithin another query. 'he outer query is called as main query and inner query is called as subquery. !e !ill see ho! subqueries are used to retrieve the required data and also ho! to use subqueries in DM; and DD; commands. 'he follo!ing is a simple e#ample of a subquery. S-;-$' name" qual +0&M faculty ).-0- fcode in ( S-;-$' fcode +0&M courseDfaculty ).-0- ccode L 2ora2) / M- BA ; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4eorge <och MS $omputer Science Vason $ouchman &$9 DB <evin ;oney MS -lectronics In the above e#ample !e !ill take the details of faculty members !ho can handle course ora. $&A0S-D+ $A;': table contains information about !hich faculty members can take course ora. So !e first use a subquery to get the list of the codes of the faculty members !ho can handle &racle course. 'hen !e send the list of faculty codes to outer query" !hich !ill then display the details of those faculty members. Subquery is al!ays e#ecuted first and the result is passed to the main query. Main query is e#ecuted by taking the result from subquery. I/ operator plays a very important role in subqueries as generally subqueries generate a list of values and main query is to compare a single value against the list of values supplied by subquery. In the above e#ample" subquery supplies the list of faculty codes to main query. 'hen main query compares each faculty code of the + $A;': table !ith the list supplied by subquery. If the faculty code e#ists in the list then it !ill display the details of the faculty. 'he follo!ing are a fe! other e#amples of subqueries. 4et the details of students !ho have paid today. S-;-$' P +0&M students ).-0- rollno in ( S-;-$' rollno +0&M payments ).-0- trunc(dp) L trunc(sysdate))@

Display the details of batches handled by faculty name 3<evin ;oney1. S-;-$' P +0&M batches ).-0- fcode L ( S-;-$' fcode +0&M faculty ).-0- name L 2<evin ;oney2)@ 'he follo!ing query displays the details of the faculty members !ho have not taken any batch in the last three months. S-;-$' P +0&M faculty ).-0- fcode /&' I/ (S-;-$' fcode +0&M batches ).-0- monthsDbet!een(sysdate"stdate) UL >) +or e#ample" the follo!ing is invalid. SB;S S-;-$' P +0&M sub,ects = ).-0- fulldur > bet!een =? K and (S-;-$' ma#(fulldur) +0&M sub,ects)@ and (S-;-$' ma#(fulldur) +0&M sub,ects) P -00&0 at line K6 &0 %GGN>Z6 missing e#pression Multiple Su$Aueries It is possible for a main query to receive values from more than one subquery. 'he follo!ing e#ample displays the details of batches that are taken by faculty !ith qualification MS or the course fee is more than ?GGG. S-;-$' +0&M batches ).-0- fcode in (S-;-$' fcode +0&M faculty ).-0- qual like 2_MS_2) or ccode in ( S-;-$' ccode +0&M courses ).-0- fee S ?GGG)@ B$&D- $$&D- +$&D- S'D '- -/DD '- 'IMI/4 %%%%% %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%% bH ora gk H=%V /%GH =G%+-B%GH H b> c hs =G%V /%GH =J%+-B%GH > bK #ml dh G=%M 0%GH >G%M 0%GH > b? ,ava hs G?% 90%GH HG%M :%GH H bZ vbnet da H=%VA;%GH H In the above query first the subquery ( S-;-$' fcode from faculty !here qual like 3_MS _1 ( is e#ecuted. It then retrieves faculty codes !here qualification of the faculty contains MS. 'hen it e#ecutes second subquery and then returns course codes of the courses !here +-- is more than ?GGG. fter both the subqueries are e#ecuted then the main query is e#ecuted !ith the data that is passed by subqueries to main query. "esting Su$Auery It is also possible to nest subqueries. So far !e have seen e#amples !here a single subquery is e#ecuted and sends values to main query. It is also possible for a subquery to depend on another subquery and that subquery on another and so on. 'he follo!ing e#ample displays the details of the students !ho belong to batches that are taken by faculty !ith qualification MS. S-;-$' rollno"name" bcode +0&M students ).-0- bcode in ( S-;-$' bcode +0&M batches ).-0- fcode in ( S-;-$' fcode +0&M faculty ).-0- qual like 2_MS_2)

)@ 0&;;/& / M- B$&D%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%% H 4eorge Micheal bH = Micheal Douglas bH Z $hirs -vert b> J Ivan ;endal b> I 4eorge Micheal bK N 0ichard Mar# b? HG 'ina 'urner b? HH Vody +oster b? /ote6 Subqueries can be nested up to HZ levels. But that limit is seldom reached. Moreover it is not recommended to use more than > levels of nesting considering the performance. 'he follo!ing is another e#ample !here !e !ill take details of payments made by students of the batch that started on H=%,ul%=GGH. S-;-$' P +0&M payments ).-0- rollno in (S-;-$' rollno +0&M students ).-0- bcode in (S-;-$' bcode +0&M batches ).-0- stdate L 2H=%,ul%GH2 ) )@ *omparing more than one 7alue subquery can return multiple columns. 'hese multiple columns must be compared !ith multiple values. 'he follo!ing query displays the details of the batches that have taken ma#imum duration among the batches of the same course. S-;-$' P +0&M batches ).-0- (ccode" enddate%stdate) in (S-;-$' ccode" ma#(enddate%stdate) +0&M batches 40&A9 B: ccode)@ B$&D- $$&D- +$&D- S'D '- -/DD '- 'IMI/4 %%%%% %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%% b= asp da H?%V /%GH G?%M 0%GH = b> c hs =G%V /%GH =J%+-B%GH > b? ,ava hs G?% 90%GH HG%M :%GH H bH ora gk H=%V /%GH =G%+-B%GH H bK #ml dh G=%M 0%GH >G%M 0%GH > +irst subquery returns the course and ma#imum duration for that course from B '$.-S table using M [ function and 40&A9 B: clause. 'hen the values are sent to main query !here they are compared !ith $$&D- and duration of each batch. If in a ro! of B '$.-S table the $$&D- and the duration are equivalent to $$&D- and ma#imum duration of any of ro!s returned by subquery then the ro! of B '$.-S table is selected. /o! let us see fe! more e#amples of subqueries. 4et the details of course that has highest course fee. S-;-$' ccode"name"fee +0&M courses ).-0- fee L (S-;-$' ma#(fee) +0&M courses)@ $$&D- / M- +-%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% cs $ Sharp JGGG

4et the details of students !ho have made a payment in the last month but no in the current month. S-;-$' P +0&M students ).-0- rollno not in (S-;-$' rollno +0&M payments ).-0- toDchar(dp"2mmyyyy2) L toDchar(sysdate"2mmyyyy2) ) and rollno in ( S-;-$' rollno +0&M payments ).-0- toDchar(dp"2mmyyyy2)LtoDchar(addDmonths(sysdate"%H)"2mmyyyy2) )@ +irst !e take roll numbers of students !ho have made payment in the current month and roll numbers of students !ho have made payment in the previous month. 'hen the outer query selects students !ho are not part of the first list (!ho made payment in current month) and part of second list ( !ho made payment in previous month). Subqueries in DM; and DD; commands Subqueries can also be used !ith DM; commands. ).-0- clause of A9D '- and D-;-'- can al!ays contain a subquery. 'he follo!ing A9D '- command increases the +-- of the course if more than ? batches have started for that course. A9D '- courses set fee L fee P H.H ).-0- ccode in ( S-;-$' ccode +0&M batches 40&A9 B: ccode . OI/4 count(P) S ?)@ In the above e#ample" subquery returns course codes for !hich more than ? batches have started and then A9D '- !ill update only those courses. 'he follo!ing D-;-'- command uses subquery in ).-0- clause to find out batches for !hich there are no students. D-;-'- +0&M batches ).-0- bcode not in ( S-;-$' bcode +0&M students)@ 'he e#amples above are the cases !here !e used subquery in ).-0- clause and not precisely in DM; command. 'he follo!ing A9D '- command updates +$&D- of batch bJ to the faculty code of the batch bH. A9D '- batches set fcode L (S-;-$' fcode +0&M batches ).-0- bcode L 2bH2) ).-0- bcode L 2bJ2@ Subquery returns a single value that is to be copied to +$&D- of A9D '-. Similarly the follo!ing I/S-0' inserts ro!s into a table called $&M9DB '$.. 'he data is taken from B '$.-S table. 'he follo!ing subquery creates a ne! table from an e#isting table. $0- '- ' B;- ne!Dbatches as S-;-$' bcode" ccode"fcode" stdate "timing +0&M batches ).-0- stdate S sysdate@ 'he subquery is used to retrieve the data using !hich the ne! table is created. 'he structure of the ne! table !ill be same as the structure of the query. In the above query as query selects B$&D-"$$&D-"+$&D-" S'D '- " and 'IMI/4 columns the table is also created !ith same columns. 'he follo!ing is the structure of the ne! table. SB;S desc ne!Dbatches /ame /ullT 'ype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%%%%%%%% B$&D- O 0$. 0=(?) $$&D- O 0$. 0=(?) +$&D- O 0$. 0=(?)

S'D '- /&' /A;; D ''IMI/4 /AMB-0(H) SB;S desc batches /ame /ullT 'ype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%%%%%%%% B$&D- /&' /A;; O 0$. 0=(?) $$&D- O 0$. 0=(?) +$&D- O 0$. 0=(?) S'D '- /&' /A;; D '-/DD '- D ''IMI/4 /AMB-0(H) If you observe the above t!o structures" you !ould notice that only /&' /A;; constraint of S'D '- of B '$.-S table is taken to /-)DB '$.-S table. S-;-$' P +0&M ne!Dbatches )ill display the details of batches !here S'D '- of the batch is after S:SD '-. If you !ant to insert details again of ne! batches after some time you can issue the follo!ing I/S-0' command. I/S-0' I/'& ne!Dbatches S-;-$' bcode" ccode" fcode" stdate " timing +0&M batches ).-0- stdate S sysdate@ /ote6 'he order and type of columns in the query and /-)DB '$.-S should be same. &ther!ise you may have to list out columns in the query according to the requirement. 0enaming a column using subquery 'he follo!ing procedure !ill illustrate ho! to use subquery !ith DD; to rename a column in a table. 0enaming a column is not permitted in &racle. So to rename a column" follo! the given procedure. .o!ever" it is to be noted that this procedure is lengthy and not very refined. But you can consider in case of desperate need. ssume !e created a table called 90&DA$'S as follo!s. $0- '- ' B;- products ( id number(?) primary key " name O 0$. 0=(>G)" qty number(K) check ( qty SL G )" pric number(?) )@ But the column 90I$ is misspelt. It should have been 90I$-. /o! let us see ho! to rename the column. +irst create a ne! table called ne!products using a subquery. 4ive an alias to column 90I$ so that the alias becomes the column name in the ne! table. $0- '- ' B;- ne!products as S-;-$' id" name" qty" pric price +0&M products@ see the structure of the ne! table using D-S$ command. desc ne!products name /ullT 'ype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%% %%%%%%%%%%%%% ID /AMB-0(?) / M- O 0$. 0=(>G) B': /AMB-0(K) 90I$- /AMB-0(?)

s you can see in the output of D-S$ command" no constraint are defined in ne! table % /-)90&DA$'S. So !e need to define all constraints again on this table using ;'-0 ' B;command. But before that let us drop original table and rename /-)90&DA$'S to 90&DA$'S. SB;S D0&9 ' B;- products@ 'able dropped. /ote6 If the table being dropped has any dependent tables !ith ro!s then you have to drop those ro!s also. +or e#ample" if you have S ;-S table referring to 90&DA$'S table then first S ;-S table is to be emptied before ro!s in 90&DA$'S table can be deleted. SB;S rename ne!products to products@ 'able renamed. /o! !e have to define all constraints that !e had in 90&DA$'S table. 'his step is required as constraints of 90&DA$'S table are copied to /-)90&DA$'S table. ;'-0 ' B;- products add ( constraint productsDpk primary key(id))@ ;'-0 ' B;- products add ( constraint productsDqtyDchk check(qty SL G))@ /o! see the structure of the ne! table using D-S$0IB- command and constraints using AS-0D$&/S'0 I/'S vie!. Su$Auery in 1'/3ES clause 'he follo!ing I/S-0' command gets the ne#t 0&;;/& for a ne! student by using a subquery. I/S-0' I/'& students values ( (S-;-$' ma#(rollno) M H +0&M students)" 2bJ2" 20obert ;afore2" 2m2" sysdate" null" null)@ 0 DE B5 is permitted in su$Auery C )0,n analysis 'he follo!ing query !ill use &0D-0 B: clause to get courses in descending order. 'hen main query !ill take the data sent by the subquery and selects only first t!o ro!s. s the result" the query !ill display the details of course !ith first t!o highest course fee. 0&)/AM pseudo column contains the ro! number for the retrieved ro!s. 'he query uses 0&)/AM and takes only those ro!s that have ro! number less than >. S-;-$' ccode"name"fee +0&M (S-;-$' P +0&M courses &0D-0 B: fee desc) ).-0- ro!num U >@ $$&D- / M- +-%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% cs $ Sharp JGGG vbnet OB./-' ??GG *orrelated Su$Auery If there is any correlation bet!een main query and subquery then subquery is called as correlated subquery. correlated subquery is a subquery that receives some input from main query and sends result back to main query. Anlike normal subquery" a correlated subquery receives value from main query. It uses the value (generally in condition) and sends the results of the query back to main query. 'hough most of the requirements can be accomplished !ith normal subqueries" some requirements do need correlated subquery. +or e#ample" !e have to display the details of the batches !here duration of the batch is more than the average duration of all the batches of that course. Before !e !rite the required query" let us look at the data present in B '$.-S table. S-;-$' P +0&M batches@ B$&D- $$&D- +$&D- S'D '- -/DD '- 'IMI/4 %%%%% %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%%

bH ora gk H=%V /%GH =G%+-B%GH H b= asp da H?%V /%GH G?%M 0%GH = b> c hs =G%V /%GH =J%+-B%GH > bK #ml dh G=%M 0%GH >G%M 0%GH > b? ,ava hs G?% 90%GH HG%M :%GH H bZ vbnet da H=%VA;%GH >H% A4%GH H bJ ora gk H?% A4%GH GK%&$'%GH = bN ora kl G?%M :%GH HG%VA/%GH > bHG c kl H?%VA/%GH =G%VA;%GH = bHH vbnet da H?%VA/%GH >G%VA;%GH = /o! let us !rite correlated query to get details of batches !here duration (-/DD '-%S'D '-) is more than the average duration of the course. S-;-$' P +0&M batches bH ).-0- enddate % stdate SL (S-;-$' avg(enddate % stdate) +0&M batches ).-0- ccode L bH.ccode)@ B$&D- $$&D- +$&D- S'D '- -/DD '- 'IMI/4 %%%%% %%%%% %%%%% %%%%%%%%% %%%%%%%%% %%%%%%%%% b= asp da H?%V /%GH G?%M 0%GH = b> c hs =G%V /%GH =J%+-B%GH > bK #ml dh G=%M 0%GH >G%M 0%GH > b? ,ava hs G?% 90%GH HG%M :%GH H bZ vbnet da H=%VA;%GH >H% A4%GH H bJ ora gk H?% A4%GH GK%&$'%GH = In correlated subquery" subquery is e#ecuted once for each ro! of the main query. 'his is required as subquery uses a value sent from main query" !hich may change from ro! to ro! in main query. correlated subquery is identified by the use of a column of main query in the subquery. In the above e#ample" for each ro! of the B '$.-S table the course code ($$&D-) is passed to subquery and then subquery finds out the average duration of all batches of that course. 'he condition ccode L bH.ccode is used to select batches that belong to the course to !hich the batch in the main query belongs. )hen subquery returns the average duration then main query checks !hether duration of the batch is greater than or equal to the average duration sent by subquery. If the condition is satisfied then ro! in the main query is selected other!ise it is not selected. 'he process continues !ith the ne#t ro! in the main query and so on until all ro!s of the main query are processed. Differences $et#een normal and correlated su$Auery 'he follo!ing are the differences bet!een a correlated subquery and ordinary subquery. Su$Auery *orrelated su$Auery -#ecuted only for once before mainquery -#ecuted once for each ro! of main%query. Sends a value to main%query. 0eceives value(s) from main query and sends value(s) to main%query. 'he follo!ing is another e#ample of correlated subquery !here !e get third highest course fee. S-;-$' name" fee +0&M courses cH ).-0- =L ( S-;-$' count(P) +0&M courses

).-0- fee S cH.fee)@ / M- +-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% S9./-' ?GGG In the above e#ample" subquery returns the number of courses !here +-- is more than the fee of the ro! in the main query. If the count returned by subquery is equal to = then it means above that course fee there are t!o more. 'hat means that course fee becomes the third highest. 'he above query is pretty useful. -specially prior to &racleIi. s &racleIi allo!ed &0D-0 B: clause in subquery" !hat !as achieved !ith this correlated subquery can to some e#tent be achieved !ith &0D-0 B: clause in subquery. 'he follo!ing t!o queries" !ill display the details of courses !ith t!o lo!est fees. 'he first query uses &0D-0 B: clause in subquery to retrieve courses in the ascending order of +--. 'hen main query retrieves only first t!o ro!s of the subquery. S-;-$' P +0&M ( S-;-$' ccode" name" fee +0&M courses &0D-0 B: fee) ).-0- ro!num U >@ $$&D- / M- +-%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% c $ programming >?GG #ml [M; 9rogramming KGGG 'he second query uses a correlated subquery to get number of ro!s !here +-- is less than the +-- of the ro! in main query. If the count returned by subquery is greater than or equal to H then ro! of the main query is retrieved. S-;-$' ccode"name" fee +0&M courses cH ).-0- H SL ( S-;-$' count(P) +0&M courses ).-0- fee U cH.fee)@ $$&D- / M- +-%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% c $ programming >?GG #ml [M; 9rogramming KGGG E=IS)S and "0) E=IS)S operators 'hese t!o operators are e#clusively used in correlated subquery. -[IS'S checks !hether any ro! is returned by subquery and condition !ill be true if subquery returns any ro!s. )hereas" /&' -[IS'S returns true if subquery doesn1t retrieve any ro!. -[IS'S is different from other operators like I/" /: etc." because it doesn1t compare values of columns" instead" it checks !hether any ro! is retrieved from subquery or not. If any ro! is retrieved from subquery the -[IS'S returns true other!ise it returns false. 'he follo!ing query displays details of courses for !hich at least one batch started in this month. S-;-$' P +0&M courses ).-0- e#ists ( S-;-$' P +0&M batches ).-0- courses.ccodeL ccode and toDchar(stdate"2mmyy2) L toDchar(sysdate"2mmyy2) )@ )hen using -[IS'S operator" !hat you select in the inner%query does /&' matter. )hat does matter is !hether any ro! is retrieved by inner query or not. 'he follo!ing e#ample displays the details of courses for !hich no batch has yes started. S-;-$' ccode"name"fee +0&M courses ).-0- not e#ists ( S-;-$' P +0&M batches ).-0- ccode L courses.ccode)@ $$&D- / M- +--

%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% cs $ Sharp JGGG It is possible to replace the above /&' -[IS'S !ith /&' I/ operator as sho!n belo!. S-;-$' ccode"name"fee +0&M courses ).-0- ccode not in ( S-;-$' ccode +0&M batches)@ $$&D- / M- +-%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% cs $ Sharp JGGG ;et us see t!o other operators ;; and /:. '"5 and '// 0perators Both are used for comparing one value against a set of values. ;; specifies that all the values given in the list should be taken into account" !hereas /: specifies that the condition is satisfied !hen any of the values satisfies the condition. operator '"5 list 'he operator can be any one of the standard relational operators (L" SL" S" U" UL" ^L) " and list is a series of values. )hat if you !ant to display name of the courses !here +-- is more than +-- of any course !ith DA0 'I&/ =?T 'he follo!ing query !ill do ,ust that. S-;-$' name +0&M courses ).-0- fee S any ( S-;-$' fee +0&M courses ).-0- duration L =?)@ / M%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OB./-' S9./-' $ Sharp /: operator specifies if +-- is more than any value in the list supplied by subquery then the condition is true. 'he same query can also be !ritten as follo!s using MI/ function. S-;-$' name +0&M courses ).-0- fee S ( S-;-$' min(fee) +0&M courses ).-0- duration L =?)@ / M%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OB./-' S9./-' $ Sharp 'he follo!ing list illustrates the result of 0ate /:] ;; &perator 0esult HG HG HG HG 0ate S /: (H?"=G) 0ate S /: (?"H?) 0ate S ;; (HG"=G) 0ate S ;; (?"J) +alse 'rue +alse 'rue /: and ;; operator.

INDE(ING) SE'UENCE AND $SEUDO COLUMNS


What is an Inde6? 'he best !ay of understanding an inde# in &racle (or any database system) is by comparing it !ith the inde# that !e find at the end of a te#tbook. +or instance" if you !ant to read about inde#ing in an &racle te#tbook" you !ill use inde# of the book to locate the topic inde#ing. &nce the topic is found in inde# then you take the page number of that topic from inde#. 'hen you go to the page !ith that page number and start reading about inde#ing. 'he concept of inde#ing in &racle is same as the concept of book inde#. +irst let us look at the features of an inde# of a te#tbook. It is at the end of the te#tbo# so that you need not search for the inde# in the first place. It contains all topics of the book in the ascending (alphabetical) order of the topics. fter the topic the page number(s) !here the topic is found in the book is listed. Inde# does increase the si*e of the book by a fe! pages. )e use inde# only !hen !e need it. In other !ords" !e use inde# !hen !e feel it is going to help locating the topic quickly.

ll the characteristics of an inde# in a te#tbook !ill be found in an inde# of &racle. 'he follo!ing are the characteristics of an inde# in &racle. Inde# is used to search for required ro!s quickly. Inde# occupies e#tra space. Inde# is stored separately from table. Inde# contains the values of key ( column on !hich inde# is created ( in the ascending order. Vust like the page number in book inde#" &racle inde# stores 0&)ID ( a unique value to internally identify each ro! of the table. +or each entry in the inde# a key and corresponding 0&)ID are stored. &racle uses inde# only !hen it feels the inde# is going to improve performance of the query.

/ote6 0&)ID is a unique value assigned to each ro! created in a table. &nce 0&)ID is assigned to a ro! it doesn1t change during the lifetime of the ro!. &racle access ro!s internally using 0&)ID. n inde# in &racle is internally stored as Self%balancing binary tree. data structure that makes searching for a particular value faster. Why )o 3se 'n I"DE= n inde# in &racle is used for t!o purposes. 'o speed up searching for a particular value thereby improving performance of query. 'o enforce uniqueness 3sing inde6 to impro7ing performance Vust like ho! you can quickly locate a particular topic in the book by using inde# at the end of the book" &racle uses inde# to quickly locate the ro! !ith the given value in the inde#ed column. Inde#ed column is the one on !hich inde# is created. +or e#ample if you !ant to search for a particular student by name then &racle does the follo!ing !ithout and !ith inde#. )ithout inde#" &racle !ill start looking for the given name at the first ro! of the table and continues until it finds the name or until end of the table is reached. 'his could be very time consuming process especially for tables !ith many ro!s. )ith inde#" &racle !ill use inde# to search for the given name. Since inde# is stored in the form of binary tree" locating the name in the inde# is going to be very fast. 'hen by using the 0&)ID obtained from inde# entry" &racle !ill take the ro! from the table. 'ables !ith more number of ro!s !ill greatly benefit from inde#es. .aving an inde# and not having an inde# could make a lot of difference for large tables !ith thousands of ro!s. Enforcing uniAueness #ith inde6 n inde# may also be used to enforce uniqueness in the column(s) given in the inde#. &nce a A/IBA- inde# is created" &racle makes sure values in the inde#ed column(s) are unique. /ote6 A/IBA- inde# is automatically created on the columns !ith 90IM 0: <-: and A/IBA- constraints. *reating an Inde6 DD; command $0- '- I/D-[ is used to create an inde#. 'he follo!ing is the synta# of this command. $0- '- QA/IBA-R I/D-[ inde#Dname &/ table (column%H Q" column%=R...)@ A/IBA- key!ord is used to create a unique inde#. Anique inde# makes sure that the inde#ed column(s) is al!ays unique. 'o create an inde# on / M- column of S'AD-/'S table" enter6 $0- '- I/D-[ studentsDnameDid# on students (name)@ If you !ant to create a unique inde# on / M- column of S'AD-/'S table" enter6 create unique inde# studentsDnameDid# on students(name)@ It is also possible to create an inde# on more than one column. 'he follo!ing command creates an inde# on $$&D- and +$&D- columns of B '$.-S table. $0- '- I/D-[ batchesDccodeDfcodeDid# on batches ( ccode"fcode)@ /ote6 )hen t!o or more columns are used in an inde# then give the column in the order of frequency of usage. 'hat means the most frequently used column should be given first.

Vust like an inde# of the book" !hich is not used every time you read the book" even &racle inde# is not used every time by &racle. In the ne#t section !e !ill see !hen &racle uses inde# and !hen not. When 0racle does not use inde6? 'he best part of &racle inde# is@ it is completely automatic. 'hat means" you never have to e#plicitly refer to an inde#. &racle decides !hether to use an inde# or not depending upon the query. &racle can understand !hether using an inde# !ill improve the performance in the given query. If &racle thinks using an inde# !ill improve performance" it !ill use the inde# other!ise it !ill ignore the inde#. ;et us assume !e have an inde# on / M- column of S'AD-'/S table. 'hen the follo!ing query !ill use the inde# as !e are trying to get information about a student based on the name. S-;-$' P +0&M students ).-0- name L 20ichard Mar#2@ But in the follo!ing case &racle does /&' use inde#" as inde#1s usage doesn1t improve performance of the query. S-;-$' doesn1t contain ).-0- clause If S-;-$' command doesn1t contain ).-0- clause then &racle doesn1t use any inde#. Since all ro!s of the table are to be retrieved" &racle !ill directly access the table !ithout referring to any inde#. In the follo!ing e#ample no inde# of S'AD-/'S table !ill be used. S-;-$' P +0&M students@ S-;-$' contains ).-0- clause" but ).-0- clause doesn1t refer to inde#ed column. In this case S-;-$' contains ).-0- clause but the ).-0- clause is not referring to any columns on !hich an inde# is created. +or e#ample" S'AD-'/S table contains t!o inde#es ( one on 0&;;/&" as it is primary key and another on / M-. 'he follo!ing query uses ).-0- clause but condition is based on DV column for !hich there is no inde#. S-;-$' P +0&M students ).-0- d, S 1HZ%,an%=GGH1@ .o!ever" note that if there is any inde# on DV then &racle !ill use that inde#. ).-0- clause uses inde#ed columns but inde#ed column is modified in the ).-0- clause. In this case ).-0- clause refers to inde#ed columns but doesn1t refer to inde#ed column as it is. In the query belo!" / M- column is used but as it is used !ith SABS'0 function that modifies the column in the condition" inde# created on / M- column !ill not be used. S-;-$' P +0&M students ).-0- SABS'0(name"K">) L 3Voh1@ /ote6 Data dictionary vie! AS-0DI/D-[-S provides information about inde#es. $reating function%based inde# Inde# column must be column of the table. If any function is used !ith inde#ed column in the query then &racle does not use inde#. +or e#ample" if !e created an inde# on / M- column of S'AD-/'S table as follo!s6 $0- '- I/D-[ studentsDnameDid# on students (name)@ 'hen the above inde# cannot be used for the follo!ing query as inde#ed column is used !ith A99-0 function. S-;-$' P +0&M students ).-0- upper(name) L 20I$. 0D M 0[2@ It is also not possible to create any inde# based on an e#pression" the follo!ing command creates an inde# on the result of A99-0 function. $0- '- I/D-[ studentsDnameDid# on students ( A99-0(name))@ s the result if !e issue the follo!ing command &racle can use inde# as the e#pression used in the query and e#pression used to crate inde# are same. S-;-$' P +0&M students

).-0- upper(name) L 30I$. 0D M 0[1@ /ote6 'o create a function%based inde#" user must have BA-0: 0-)0I'- system privilege. 'he follo!ing is another e#ample of e#pression%based inde#. .ere inde# is created on duration of the batch. $0- '- I/D-[ batchesDdurationDid# on batches ( enddate % stdate)@ 'he follo!ing query !ill make use of the above inde#. S-;-$' P from batches ).-0- enddate % stdate S >G@ 0nline inde6ing 9rior to &racleIi" &racle used to lock the table on !hich inde# is being created throughout creation process. 'his makes table unavailable for data manipulation during the creation of inde#. But &racleIi introduced online inde#ing" !here &racle doesn1t lock the table on !hich inde# is being built. &nline inde#ing is provided through the key!ord &/;I/-. 'he follo!ing command creates inde# on / M- column of S'AD-/'S table !ithout locking the table. $0- '- I/D-[ studentsDnameDid# on students (name) online@ /ote6 &nline inde#ing increases availability of the table. 'his is a very important facility especially for Internet databases !here availability matters a lot. Dra#$acks of inde6es 'hough inde#es increase performance of query" they can also decrease performance of data manipulation. Many inde#es on a table can slo! do!n I/S-0'S and D-;-'-S drastically. +or e#ample" if !e take ? inde#es on a table then every insertion of a ne! ro! !ill update all ? inde#es of the table. 'hat means" one insertion !ill actually result in si# insertions. Similarly every change to an inde#ed column !ill need a change to inde#. .aving more inde#es is advantageous in case of tables that are primarily used only for querying and not updated frequently. 'hough the e#tra space occupied by inde#es is also a consideration" it may not matter much since the cost of data storage has declined substantially. Dropping an inde6 :ou can drop an inde# using D0&9 I/D-[ command. It removes the named inde#. 0emoving an inde# !ill effect the performance of e#isting applications but not the functionality in any !ay. Asing and not using an inde# is transparent to users. &racle decides !hether to use or not on its o!n. .o!ever" it is possible for users to control the usage of inde# to certain e#tent using hints" !hich are directive to &racle regarding ho! to e#ecute a command. But hints are too heavy in a book meant for beginners. D0&9 I/D-[ inde#name@ 'he follo!ing e#ample drops the inde# created on / M- of S'AD-/'S table. drop inde# studentDnameDid#@ SeAuence Sequence is an ob,ect in &racle database" !hich is used by multiple users to generate unique numbers. Sequence is typically used to generate primary keys like account number" employee number etc." !here uniqueness and sequence matter. In order to use a sequence" first it is to be created using $0- '- S-BA-/$- command. 'hen pseudo columns /-['O ; and $A00O ; are used to retrieve unique values from sequence. 'he follo!ing is the synta# of $0- '- S-BA-/$- command . $0- '- S-BA-/$- sequencename QI/$0-M-/' B: integerR

QS' 0' )I'. integerR QM [O ;A- integer X /&M [O ;A-R QMI/O ;A- integer X /&MI/O ;A-R Q$:$;- X /&$:$;-R@ 'he follo!ing is the description of available options. 0ption Meaning S' 0' )I'. Specifies the values at !hich sequence must start. Default is H. M [O ;AMa#imum value the sequence can generate. Default is HGe=J%H. MI/O ;AMinimum value the sequence can generate. Default is H. I/$0-M-/' B: Specifies by ho! much the value of the sequence is to be incremented. If you !ant numbers in the descending order give negative value. Default is H. $:$;0estarts numbers from MI/O ;A- after reaching M [O ;A-. 'he follo!ing command creates a sequence called 0&;;/& to generate roll numbers for students. $0- '- S-BA-/$- rollno start !ith HGG increment by H@ 'he above sequence starts generating numbers at HGG and increments the number by H every time the number is taken. &nce a sequence is created" it can be used to generate unique numbers in the sequence. &nce a value is taken from sequence" &racle automatically increments the value by one (or !hatever value specified using I/$0-M-/' B: option). &racle guarantees uniqueness. &nce it gives the number then it doesn1t give that number to anyone else. 'he follo!ing t!o pseudo columns are used to access the ne#t and current value of the sequence. "E=)1'/- 'his pseudo column !ill yield the ne#t value from sequence and automatically increments the value of the sequence. *3 1'/- 'his returns the value that is taken by most recent /-['O ;. 'his cannot be used unless /-['O ; is first called. 'he follo!ing e#amples !ill demonstrate ho! to use /-['O ; and $A00O ; pseudo columns. S-;-$' rollno.ne#tval from dual@ /-['O ; %%%%%%%%% HGG s the sequence starts !ith HGG" first /-['O ; returned HGG. nd it also increments the sequence by H. See the ne#t e#ample belo!. S-;-$' rollno.ne#tval from dual@ /-['O ; %%%%%%%%% HGH $A00O ; pseudo column returns the current value of the sequence" !hich is the value returned by most recent /-['O ;. In the follo!ing e#ample $A00O ; returns HGH since that is the most recent value returned by /-['O ;. S-;-$' rollno.currval from dual@ $A00O ; %%%%%%%%% HGH $A00O ; is used to reuse the values returned by most recent /-['O ;. 'he real usage of sequence is in inserting ro!s into table. 'he follo!ing I/S-0' command !ill use 0&;;/& sequence to get ne#t available roll number for a ne! student. I/S-0' I/'& students values (rollno.ne#tval " ...)@

nd if you !ant to insert a ro! into 9 :M-/'S table immediately !ith the same roll number then you can use $A00O ; as follo!s. I/S-0' I/'& payments O ;A-S ( rollno.currval" ...)@ 'hough a sequence can guarantees uniqueness guarantee consecutiveness. See the follo!ing scenario. I/S-0' I/'& students O ;A-S ( rollno.ne#tval" . . . commit@ I/S-0' I/'& students O ;A-S ( rollno.ne#tval" . . . rollback@ I/S-0' I/'& students O ;A-S ( rollno.ne#tval" . . . commit@ and sequence" its usage may not )@ )@ )@

In the above scenario" if you take the value of 0&;;/&./-['O ; as HG= for first I/S-0' then the value in the second I/S-0' !ill be HG>. But as second I/S-0' command is rolled back that number is not actually used as roll number. 'hird I/S-0' command no! takes HGK but not HG> as &racle returns ne#t available number" !hich is HGK. s you can see" HG> is not used at all in the roll number. )hile using sequence one must be a!are of this potential gaps. 'ltering a seAuence Some attributes of a sequence can be altered using ;'-0 S-BA-/$- sequencename QI/$0-M-/' B: integerR QM [O ;A- integer X /&M [O ;A-R QMI/O ;A- integer X /&MI/O ;A-R ;'-0 S-BA-/$- command.

+or instance" the follo!ing command changes M [O ;A- of 0&;;/& sequence to HGGG. alter sequence rollno ma#value HGGG@ Dropping a SeAuence D0&9 S-BA-/$- command is used to drop a sequence. D0&9 S-BA-/$- sequencename@ 'he follo!ing command drops 0&;;/& sequence. drop sequence rollno@ ,seudo *olumns pseudo column is used like a column in a table but it is not a column of any table. :ou can use pseudo columns ,ust like table columns but you cannot modify them. 'he follo!ing is the list of available pseudo columns in &racle. 9seudo $olumn Meaning $A00O ; 0eturns the current value of a sequence. /-['O ; 0eturns the ne#t value of a sequence. /A;; 0eturn a null value. 0&)ID 0eturns the 0&)ID of a ro!. See 0&)ID section belo!. 0&)/AM 0eturns the number indicating in !hich order &racle selects ro!s. +irst ro! selected !ill be 0&)/AM of H and second ro! 0&)/AM of = and so on. S:SD '0eturns current date and time. AS-0 0eturns the name of the current user. AID 0eturns the unique number assigned to the current user. 'he follo!ing are a fe! e#amples on usage of pseudo columns. Display the name of the current user and user1s id. SB;S S-;-$' user" uid from dual@ AS-0 AID

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% B&&< >I 0WID 9seudo column 0&)ID returns the address of each ro! in the table. &racle assigns a 0&)ID to each ro!. &racle uses 0&)ID internally to access ro!s. +or instance" &racle stores 0&)ID in inde# and uses it to access the ro! in the table. :ou can display 0&)ID of ro!s using S-;-$' command as follo!s6 S-;-$' ro!id" ccode from courses@ 0&)ID $$&D%%%%%%%%%%%%%%%%%% %%%%% D$? B <aS ora D$? B <aS B vbnet D$? B <aS $ c D$? B <aS D asp D$? B <aS - ,ava D$? B <aS + #ml D$? B <aS 4 cs &racle provides a package called DBMSD0&)ID to decode 0&)ID. 'he follo!ing S-;-$' command displays only the ro! number from 0&)ID. S-;-$' dbmsDro!id.ro!idDro!Dnumber(ro!id) as ro!number "ccode from courses 0&)/AMB-0 $$&D%%%%%%%%% %%%%% G ora H vbnet = c > asp K ,ava ? #ml Z cs /ote6 &nce a ro! is assigned a 0&)ID &racle does not change 0&)ID during the lifetime of the ro!. s the result you may see some ro! numbers missing in the output of above command. It means those ro!s !ere deleted. 0W"3M 'his pseudo column yields the order in !hich &racle has selected ro!s. 'he follo!ing command displays ro! number of each ro!. S-;-$' ro!num" ccode from courses@ 0&)/AM $$&D%%%%%%%%% %%%%% H ora = vbnet > c K asp ? ,ava Z #ml J cs 0&)/AM can also be used in conditions but only t!o operators@ U and UL. make sense !ith 0&)/AM. 'he follo!ing query displays first five courses. S-;-$' ro!num" ccode from courses ).-0- ro!num UL ? 0&)/AM $$&D-

%%%%%%%%% %%%%% H ora = vbnet > c K asp ? ,ava .o!ever" the follo!ing is not meaningful usage of 0&)/AM. It is because of the fact that &racle assigns number to ro! after ro! is selected. S-;-$' ro!num" ccode from courses ).-0- ro!num L ?@ no ro!s selected lso remember using &racle assigns numbers to ro!s before ro!s are ordered using &0D-0 B: clause as demonstrated by the follo!ing query. S-;-$' ro!num"ccode"duration"fee +0&M courses &0D-0 B: fee@ 0&)/AM $$&D- DA0 'I&/ +-%%%%%%%%% %%%%% %%%%%%%%% %%%%%%%%% > c =G >?GG Z #ml H? KGGG H ora =? K?GG ? ,ava =? K?GG K asp =? ?GGG = vbnet >G ??GG J cs >G JGGG

SECURIT*
3sers and ,ri7ileges -very user in &racle must have a valid username and pass!ord. In order to access &racle database" one must logon by using username and pass!ord. t the time of creation of database" &racle creates t!o users ( S:S'-M and S:S. 'hese t!o users have privileges to perform administrative operations such as creating users" altering and dropping users" roles" profile" tablespaces (pieces that make up the database) etc. .o!ever" it is possible to create ne! users using $0- '- AS-0 command as follo!s6 SB;S create user scott identified by tiger@ Aser created. 'he above command creates a ne! user !ith the name S$&'' and pass!ord 'I4-0. /ote6 In order to create a ne! user you must logon either as S:S'-M or as S:S. 'hough the account !ith the name S$&'' is created" it cannot even logon no! as sho!n belo!. SB;S connect scott]tiger@ -00&06 &0 %GHGK?6 user S$&'' lacks $0- '- S-SSI&/ privilege@ logon denied $&//-$' command is used to move to another user from current user. In the above e#ample" !e !ere moving from S:S'-M to S$&''. 'he error indicates that user S$&'' lacks $0- '- S-SSI&/ privilege. $0- '- S-SSI&/ is a system privilege" !hich allo!s user to create a session !ith &racle (logon). /ote6 session !ith &racle start from the point of login and ends !hen user logs out.

In order to permit user to create a session and perform other operations such as creating tables" vie! etc." user must be granted $&//-$' and 0-S&A0$- roles as follo!s. SB;S grant connect" resource to scott@ 4rant succeeded. ,ri7ilege privilege is a right to access an ob,ect such as a table" vie! etc." or to e#ecute a particular type of SB; command such as $0- '- ' B;-. 9rivileges are classified into t!o categories depending upon !hat type of right they confer !ith the user. System privileges &b,ect 9rivileges System pri7ilege system privilege is a right to perform certain operation in the system. +or e#ample" $0- '- S-SSI&/ privilege allo!s user to create a session !ith &racle" $0- '- ' B;- privilege allo!s user to create table and so on. 4enerally system privileges are granted to users through roles. &nly DB s are concerned !ith system privileges. 0$8ect pri7ilege n ob,ect privilege is a right to perform a particular operation on an ob,ect. either is a table" vie!" sequence" procedure" function" or package. n ob,ect

Aser o!ns the ob,ect that he]she creates. &!ner has complete access to the ob,ect. +or e#ample" if the ob,ect is a table then o!ner can select" insert" delete" update" alter" create an inde# on table and even drop the table. )hereas other users do not have any access to the ob,ect" unless they are granted a privilege e#plicitly. 'he follo!ing is the list of ob,ect privileges available in &racle. ;'-0 $hanging the definition of the ob,ect. D-;-'Deleting ro!s from the ob,ect -[-$A'-#ecute the ob,ect. I/D-[ $reating an inde# on the ob,ect. I/S-0' Inserting ro!s into ob,ect 0-+-0-/$-S 0eferencing the ob,ect in foreign key constraint. S-;-$' Selecting ro!s from the ob,ect. A9D 'Apdating the data of the ob,ect. -ach ob,ect privilege specifies !hat can be done !ith an ob,ect. But not all ob,ect privileges are applicable to all ob,ects. +or instance" ;'-0 privilege is not applicable to vie!s" similarly -[-$A'- privilege is applicable only to procedure and functions. 0$8ect ,ri7ileges '7aila$le ' B;S-;-$'" I/S-0'" D-;-'-" A9D '-" ;'-0" I/D-[" 0-+-0-/$-S. OI-) S-;-$'" I/S-0'" A9D '-" /D D-;-'-. S-BA-/$S-;-$'" ;'-0. 90&$-DA0- -[-$A'-. 4ranting 0$8ect ,ri7ileges In order to grant ob,ect privileges use 40 /' $ommand. 40 /' Wob,ectDprivX ;;Y Q(column Q"columnR...)R &/ ob,ect '& Wuser X role X 9AB;I$Y Q" Wuser X role X 9AB;I$YR ... Q)I'. 40 /' &9'I&/R ;; is used to grant all available ob,ect privileges on the ob,ect. 9AB;I$ is used to grant the privilege to all the users of the system.

/o! assume user S$&'' is the o!ner of $&A0S-S table and he !ants to grant S-;-$' privilege on $&A0S-S table to user 90 /--'.. 'he follo!ing command !ill do ,ust that. grant S-;-$' on courses to praneeth@ 'he follo!ing command grants all available privileges on $&M9B '$.-S vie! to 90 /--'.. grant all on compbatches to praneeth@ It is possible to restrict the privilege to a fe! columns in case of A9D '-" I/S-0' and 0-+-0-/$-S privileges. 'he follo!ing command !ill grant A9D '- privilege to 90 /--'. on DA0 'I&/ column of $&A0S-S table. grant A9D '-(duration) on courses to praneeth@ )I'. 40 /' &9'I&/ allo!s the grantee to grant the privilege to other users. ccessing other user1s ob,ects )hen a user !ants to access a table of other user" the table name is to be preceded by the name of the user !ho o!ns the table. &ther!ise &racle assumes that the current user o!ns the table and if table is not found under current user1s account then &racle displays an error. +or e#ample" if 90 /--'. is trying to access $&A0S-S table to !hich he has been granted S-;-$' privilege" from his account" the follo!ing happens. SB;S S-;-$' P from courses@ S-;-$' P from courses P -00&0 at line H6 &0 %GGNK=6 table or vie! does not e#ist &racle assumes $&A0S- table belongs to user 90 /--'.. 'o specify that $&A0S-S table is belonging to S$&'' and not 90 /--'." !e have to precede the table name !ith username. o!ner.tablename +or e#ample" to access $&A0S-S table from user 90 /--'." give the follo!ing command. S-;-$' P from scott.courses@ 3sing synonyms 'o simplify accessing tables o!ned by other users" create a S:/&/:M. synonym is an alias to a table or a vie!. By creating a synonym you can avoid giving the o!ner name !hile accessing tables of others. 'he follo!ing $0- '- S:/&/:M command creates a synonym" !hich is an alias to $&A0S-S table of S$&''. 0emember synonym is to be created in the account of 90 /--'. and not in the account of S$&''. SB;Screate synonym $&A0S-S for scott.courses@ Synonym created. &nce a synonym is created" you can use synonym to refer to the table. So to refer to S$&''.$&A0S-S" user 90 /--'. may give6 SB;SS-;-$' P from courses@ 9AB;I$ Synonym If synonym is to be available to all the users of the system" create a public synonym by including option 9AB;I$ in $0- '- S:/&/:M command. 'he follo!ing sequence of commands !ill create a public synonym that is accessible to all the users in the system. 4rant S-;-$' on courses to public@

'he above command grants S-;-$' privilege on $&A0S-S table to users of the database. 'hen create a public synonym on S$&''.$&A0S-S so that any user can access the table using the synonym. create public synonym courses for scott.courses@ /ote6 'o create a public synonym" you must have the $0- '- 9AB;I$ S:/&/:M system privilege. /o!" it is possible for anyone in the system to access S$&''.$&A0S-S table by using the public synonym. +or e#ample" user /A0 4 can access $&A0S-S table using public synonym as follo!s6 S-;-$' P from course@ )I'. 40 /' &9'I&/ Asing option )I'. 40 /' &9'I&/ !ith 40 /' command allo!s grantee to grant the privilege that he]she received to other users. In the follo!ing e#ample" S$&'' grants S-;-$' privilege on $&A0S- to 90 /--'. !ith option )I'. 40 /' &9'I&/. grant S-;-$' on courses to praneeth !ith grant option@ /o! user 90 /--'. can grant S-;-$' privilege that he has received from S$&''" to /A0 4 as follo!s6 grant S-;-$' on scott.courses to anurag@ /o! user /A0 4 can access $&A0S-S table of S$&'' as follo!s. S-;-$' P from scott.courses@ /ote6 'hough /A0 4 has got privilege from 90 /--'.@ he has to give S$&''.$&A0S-S to access $&A0S-S because it is o!ned by S$&''. e7oking 0$8ect ,ri7ilege 'o revoke the privileges that !ere granted earlier" use 0-O&<- command. 'he follo!ing is the synta# of 0-O&<- command. Both 40 /' and 0-O&<- commands are D$; commands. 0-O&<- Wob,ectDpriv X ;;Y Q"Wob,ectDpriv X ;;Y R ... &/ Qschema.Rob,ect +0&M Wuser XroleX9AB;I$Y Q"WuserXroleX9AB;I$YR ... Q$ S$ D- $&/S'0 I/'SR &b,ectDpriv is the privilege that is to be revoked. ;; revokes all privileges. $ S$ D$&/S'0 I/'S drops any referential constraint that !as based on 0-+-0-/$-S privilege granted earlier. +or e#ample" user granted 0-+-0-/$-S privilege to user B on $$&D- column of $&A0S-S table. nd user B has referred to $$&D- of $&A0S-S in references constraint. If user revokes 0-+-0-/$-S privilege than references constraint !ill be deleted" if $ S$ D$&/S' 0I/'S options is used. 'he follo!ing command !ill revoke S-;-$' privilege on $&A0S-S from 90 /--'.. SB;S revoke S-;-$' on courses = from praneeth@ e7oking is cascading )hen a privilege is revoked from a user" if that user has previously granted that privilege to other users then all grantees of that privilege !ill also lose that privilege. +or e#ample" if grants a privilege to B and B grants that to $" then both B and $ !ill lose the privilege !hen revokes the privilege from B. What is a ole?

0ole is a collection of privileges. In cases !here granting privileges user by user and table by table is lengthy" a role can come to your rescue. 'he follo!ing are the important characteristics of roles6 role is a collection of privileges. 'he privileges may consist of both system and ob,ect privileges. role is dynamic. Asers of the role !ill en,oy !hatever ne! privileges (added after the role has been granted to users) the role has been granted. In other !ords changes made to privileges of the role !ill affect all the users of the role. 'o create a role one must have $0- '- 0&;- system privilege. &racle comes !ith a fe! predefined roles such as $&//-$'" 0-S&A0$-" and DB . single user can be granted multiple roles. Aser !ill use only those roles that are enabled by default. .o!ever" user canenable]disable any roles that are granted to him. *reating and using role role is created using $0- '- 0&;- command !hose synta# is as follo!s6 $0- '- 0&;- rolename Qidentified by pass!ordR pass!ord is the pass!ord of the role. Asers must use pass!ord of the role at the time of enabling the role. 9ass!ord may be used for e#tra security. 'he follo!ing are the three important steps related to roles. ;et us see ho! to create and use a simple role called M / 4-0. $reating a role using $0- '- 0&;- command. 'he follo!ing command creates a role !ith the name M / 4-0. create role manager@ 4ranting reAuired pri7ileges to role 40 /' command can be used to grant privileges to role. 'he follo!ing 40 /' commands are used to grant privilege to M / 4-0 role. grant S-;-$' on courses to manager@ grant S-;-$'" A9D '-" insert" D-;-'- on batches to manager@ grant all on students to manager@ grant S-;-$' on payments@ 4ranting role to users role can be granted to user using 40 /' command as follo!s. grant manager to praneeth@ grant manager to anurag@ Ena$ling a role It is possible for a single user to have been granted more than one role. .o!ever" all roles granted to user may not be enabled by default. 'hat means" the role is granted to user but user cannot use the privileges of the role. t the time of creating user or even after!ards" administrator can specify !hich roles of the user must be enabled by default. 'he remaining roles are to be enabled e#plicitly. If role M / 4-0 is granted to user but not enabled then user can enable the role as follo!s6 SB; S set role manager@ 'he privileges the user currently has" depend on the roles that are enabled. 'he roles that are not currently enabled are called as disabled roles and roles that are currently enabled are called as enabled roles. Dropping a role It is possible to drop a role using D0&9 0&;- command. 'he follo!ing command drops role M / 4-0 that !e created earlier.

drop role manager@ 3sing pass#ord #ith role It is possible to assign a pass!ord to a role. 'he pass!ord is assigned at the time of creating the role or after the role is created using ;'-0 0&;- command. create role manager identified by efficient@ 'hen grant a fe! privileges to M / 4-0 role. 'hough DB user can grant privileges to role. grant S-;-$' on courses to manager@ /o! grant role to user anurag@ grant manager to anurag@ /o! if user /A0 4 !ants to access $&A0S-S table through the role" first he has to enable the role as follo!s. set role manager identified by efficient@ s the role is assigned a pass!ord" user must supply pass!ord at the time of enabling role. If user doesn1t supply pass!ord !hile enabling role" the follo!ing error occurs. SB;S set role manager@ set role manager P -00&0 at line H6 &0 %GHNJN6 missing or invalid pass!ord for role 2M / 4-02 '/)E 3SE *ommand ;'-0 AS-0 command can be used to modify the characteristics of a user. +or e#ample it can be used to modify6 9ass!ord Default roles 'o change the pass!ord of the current user" user may give6 alter user praneeth identified by tunu@ It is possible to specify the default roles of a user using D-+ A;' 0&;- option of command as follo!s6 alter user book default role all e#cept manager@ /ote6 -#cept changing pass!ord" user cannot change any other of his]her attributes. 9lease see on%line help for remaining options in ;'-0 AS-0 command and their usage. Data Dictionary 1ie#s Data dictionary vie!s contain information regarding database in a simple form so that user can easily understand. ll data dictionary vie!s are based on tables o!ned by user S:S. Data dictionary tables and vie!s are created at the time of creating database. 'he follo!ing is the list of data dictionary vie!s that are commonly used. Data dictionary 7ie# What it contains? ;;D' BD$&;AM/S $olumns of all tables and vie!s accessible to the user. ;;D&BV-$'S &b,ects accessible to user. DI$'I&/ 0: Description of data dictionary vie!. AS-0D$ ' ;&4 'ables" vie!s" synonyms and sequences o!ned by user. ;'-0 AS-0 can only create the role" any

AS-0D$;AS'-0S AS-0D$&;D90IOS AS-0D-00&0S AS-0DI/D-[-S AS-0D&BV-$'S AS-0DS-BA-/$-S AS-0DS:/&/:MS AS-0D' B;-S AS-0D' BD90IOS AS-0D'0I44-0S AS-0D':9-S AS-0DAS-0 AS-0DOI-)S 'he follo!ing Synonym DI$' &BV $ ' ' BS $&;S S-B S:/ I/D

Description of user1s o!n clusters. 4rants on columns for !hich the user is the o!ner" grantor or grantee. $urrent errors on stored ob,ects o!ned by the user. Description of the user1s o!n inde#es. &b,ects o!ned by the user. Description of the user1s o!n sequences. 'he user1s private synonyms. Description of the user1s o!n tables. 4rants on tables for !hich the user is the o!ner" grantor" or grantee. 'riggers o!ned by the user. &b,ect types created by user. Information about the current user. 'e#t of vie!s o!ned by the user.

is the list of synonyms based on Data dictionary vie!s. Data dictionary 7ie# DI$'I&/ 0: AS-0D&BV-$'S AS-0D$ ' ;&4 AS-0D' B;-S AS-0D' BD$&;AM/S AS-0DS-BA-/$-S. AS-0DS:/&/:M. AS-0DI/D-[-S.

'o list all tables o!ned by current user" enter6 SB;S S-;-$' P from tabs@ 'o list the all the ob,ects and their types" enter6 S-;-$' ob,ectDname" ob,ectDtype from userDob,ects@ 'o get the query stored along !ith vie!" enter6 S-;-$' vie!Dname" te#t from userDvie!s@

Potrebbero piacerti anche