Professional Documents
Culture Documents
SQL
SQL
RDBMS Concepts
Database A database is the place of storage of the data in the form of tables Data means information which is very useful. A database is also collection of 1 or more tables. Table a table is a collection of rows and columns.
CELL CELL
Columns A cell is an intersection of a row and a column A column is also called as a field / attribute A record is also called as a row / tuple. A table is also called as an entity / relation. Note : If we install any of the database related software(s) we can create our own database we can create our own tables and we can store the data inside it. !hen we install any database s/w(s) a part of hard dis" will be designated / reserved to perform database related activities A database can also contain other database ob#ects li"e views inde$es stored procedures functions triggers etc apart from tables. %ome of the database software(s) we have are &racle %'( %erver D)* %ybase Informi$ +y%'( +% Access ,o$base ,o$-ro Among the above database software some of them are D)+% and some of them are .D)+% /he s/w which is widely used today is &racle. /he different versions of &racle starting from the earliest to the latest are &racle * &racle 0 &racle 1 &racle 2 &racle 3 &racle 4 &racle 5i &racle 6i &racle 17g and the latest to hit the mar"et is &racle 11g. here 8i9 stands for Internet and 8g9 stands for :rid / :rid computing. RELATIONSHIPS Marguda Solutions Pvt Ltd : Udith U.Kerudi 1|Page
A relationship is the association between any two tables which preserves data integrity.
Relations ips
Emp Name A ) ;
Dept No$ 17 17 *7
.elationship helps to prevent the incorrect data in the child tables &nce the relationship is created one table becomes master (or parent) and the other one becomes the child ( or detail ). !hatever we insert into the child should be present in the master else the record will be re#ected from the child. /he master table contains the master data which will not change fre<uently. /he child table contains the transactional data which will change <uite often. DBMS = RDBMS DBMS stands for Database +anagement %ystem D)+% is a database s/w which allows us to store the data in the form of tables. RDBMS stands for .elational D)+% .D)+% is also a database s/w which has facility to handle more data volume good performance enhanced security features etc when compared against D)+%. Any D)+% to <ualify as a .D)+% should support the ;odd rules / ;odd laws E' for D)+% ,o$-ro ,o$)ase Dbase E' for .D)+% &racle %ybase D)* /eradata %'( %erver +y%'( CONSTRAINTS A constraint is a condition which restricts the invalid data in the table. A constraint can be provided for a column of a table.
T%pes o( Const!aints >&/ >?(( ?>I'?@ -rimary Aey ,oreign Aey ;hec" Marguda Solutions Pvt Ltd : Udith U.Kerudi 2|Page
N)LL
>?(( is nothing it is neither Bero nor blan" space It will not occupy any space in the memory /wo >?((% are never same in &racle. >?(( represents un"nown value Any arithmetic operation we perform on >?(( will result in >?(( itself. *o! e'+ 177777 C >?(( D >?(( E 177777 F >?(( D >?((
NOT N)LL G >&/ >?(( will ensure atleast some value should be present in a column )NI,)E It will not allow any duplicates in a column ?>I'?@ column can ta"e multiple >?(( (s) P!ima!% -e% It is the combination of NOT N)LL and )NI,)E &nly one -A is allowed in a table -A identifies a record uni<uely in a table ;reation of -A is not mandatory but it is highly recommended to create *o!ei.n -e% ,A creates relationship between any two tables ,A is also called as referential integrity constraints ,A is created on the child table ,A can ta"e both >?(( and duplicate values /o create ,A the master table should have -A defined on the common column of the master table !e can have more than 1 ,A in a given table CHECIt is used to provide additional validations as per the customer re<uirements. E' 1) sal H 7 *) empnum should start with 1 0) commission should be between 1777 = 2777
Dept No$ 17 *7 07
Emp Name A ) ;
Dept No$ 17 17 *7
Email aIgmail G G
RELATIONSHIP
N)LL
CHAPTER 2
%'( %tructured 'uery (anguage %'( it is a language to tal" to the database / to access the database %'( it is a language whereas %'( server is a database. Marguda Solutions Pvt Ltd : Udith U.Kerudi 4|Page
/o wor" on %'( a D) software (.D)+%) is re<uired. %'( is not case sensitive )se!name G %cott Pass4o!& /iger T!oubles ootin. O!acle Error 1 /he account is loc"ed Steps to rectify the error (ogin as username 8system9 = password 8manager9 or 8password 8tiger9 %'( H show user E ?ser is J%K%/@+L %'( H alter user scott account unloc" E ?ser altered %'( H e$it E Error 2 />% M protocol adapter error How to troubleshoot this ;ause is Joracle service has not startedL Now to go here %ettings ;ontrol -anel Administrative /ools %ervices %ort the list /here is an J&racle %ervice &.;(L = Jstart the serviceL
/his <uery gives the description of the table JdepartmentL. /he description of the table has column names+ const!aints+ &atat%pes
/he above <uery gives the description of the JemployeeL table. )ut we see that all the data is in different lines which ma"es it very difficult to analyse. %o we use the following command to see the data in a more orderly fashion
/he 5set linesi6e7 command helps in increasing the line siBe thus the data is arranged in a orderly fashion.
/he above command 5set pa.esi6e 817 increases the page siBe thus accommodating more number of rows in a single page.
/he above <uery gives the value of only these 0 columns from the table JemployeeL.
94 e!e: clause is used to restrict the number of records displayed. It gives only the records of the specified condition.
Any string data should be enclosed within sin.le 2uotes ( 8 8 ) and the same becomes case sensiti;e. Assi.nment <# List t e emplo%ees in &ept 81
OPERATORS
&perators are classified into A!it metic Ope!ato!s ( C G F / ) Relational Ope!ato!s ( H O HD OD D O H o! PD G not e<uals to ) Lo.ical Ope!ato!s ( >&/ A>D &. ) Special Ope!ato!s ( I> (IA@ )@/!@@> I% ) SPECIAL OPERATORS <# IN it is used for evaluating multiple values. E' 3 <# (ist the employees in dept 17 = *7
8# LI-E used for pattern matching ? "pe!centa.e# - matches 7 or 8n9 characters Marguda Solutions Pvt Ltd : Udith U.Kerudi 1" | P a g e
@ "un&e!sco!e# G matches e$actly one character E' 3 <# List all t e emplo%ees 4 ose name sta!ts 4it 9S:
!henever we use Q or R always ensure that it is preceded by the word 9li/e: 8# List t e emplo%ees 4 ose name is a;in. lette! 9L: as 8 n& c a!acte!
8# List t e emplo%ees 4 ose name is a;in. lette! 9E: as t e last but one c a!acte!
># List all t e emplo%ees 4 ose name is a;in. lette! 9R: in t e > !& position
In the above <uery we give * underscores before .Q. B# List all t e emplo%ees 4 o a!e a;in. e'actl% = c a!acte!s in t ei! Cobs
Nere in single <uotes we give 2 underscores. =# List t e emplo%ees 4 ose name is a;in. atleast = c a!acte!s
># BETDEEN operator used for searching based on range of values. E' 3 <# (ist the employees whose salary is between *77 and 077 Marguda Solutions Pvt Ltd : Udith U.Kerudi 12 | P a g e
B# IS operator it is used to compare nulls E' 3 <# (ist all the employees whose commission is null
LOAICAL OPERATORS <# List all t e salesmen in &ept >1 Marguda Solutions Pvt Ltd : Udith U.Kerudi 13 | P a g e
8# List all t e salesmen in &ept numbe! >1 an& a;in. sala!% .!eate! t an <=11
># List all t e emplo%ees 4 ose name sta!ts 4it 9s: o! 9a:
B# List all t e emplo%ees e'cept t ose 4 o a!e 4o!/in. in &ept <1 E 81$
ASSIANMENT <# List t e emplo%ees 4 o a!e not 4o!/in. as mana.e!s an& cle!/s in &ept <1 an& 81 4it a sala!% in t e !an.e o( <111 to >111
8# List t e emplo%ees 4 ose sala!% not in t e !an.e o( <111 to 8111 in &ept <1+81+>1 e'cept all salesmen Marguda Solutions Pvt Ltd : Udith U.Kerudi 15 | P a g e
># List t e &epa!tment names 4 ic a!e a;in. lette! 9O: in t ei! locations as 4ell as t ei! &epa!tment names
SORTINA It arranges the data either in ascending / descending order Ascending A%; / Descending D@%; !e can sort the data using ORDER BG )y default the data is always arranged in A%; order *o! e' 3 <# A!!an.e all t e emplo%ees b% t ei! sala!%
># A!!an.e ename+ sal+ Cob+ empno an& so!t b% &escen&in. o!&e! o( sala!%
In the above <uery we have o!&e! b% 8 thus it arranges only the *nd column 8salary9 in the descending order. /hus to arrange the specific columns in order we must have to specify the column number. NOTE :- ORDER BG should be used always as the last statement in the %'( <uery. Selectin. DISTINCT HAL)ES
/he above <uery arranges all the distinct values of department number.
CHAPTER %
!e have = ARO)P functions 1) %um *) +a$ 0) +in 1) Avg 2) ;ount Sum 3 returns total value Ma' returns ma$imum value Min returns minimum value A;. returns average value Count 3 returns number of records E' 3 <# &ispla% t e ma'imum sala!%+ minimum sala!% an& total sala!% (!om emplo%ee
ARO)PINA It is the process of computing the aggregates by segregating based on one or more columns. :rouping is done by using 9.!oup b%: clause. *o! e' 3 <# Displa% t e total sala!% o( all &epa!tments
HAHINA 9Ha;in.: is used to filter the grouped data. 9D e!e: is used to filter the non grouped data. 8Ha;in.: should be used after .!oup b% clause 9D e!e: should be used before .!oup b% clause *o! e' 3 <# Displa% Cob-4ise i. est sala!% onl% i( t e i. est sala!% is mo!e t an Rs<=11 Marguda Solutions Pvt Ltd : Udith U.Kerudi 21 | P a g e
8# Displa% Cob-4ise i. est sala!% onl% i( t e i. est sala!% is mo!e t an <=11 e'clu&in. &epa!tment >1$ So!t t e &ata base& on i. est sala!% in t e ascen&in. o!&e!$
RESTRICTIONS ON ARO)PINA G we can select only the columns that are part of 8 .!oup b%: statement If we try selecting other columns we will get an error as shown below
/he above <uery is an error because 8Cob9 is there in the select <uery but not in the .!oup b% <uery. If it is enclosed in any of the .!oup (unctions li/e sum"sal# etc then it is not an error. )ut whatever table is included in the select <uery must also be included in the .!oup b% <uery. /he above problem can be overcome with the following <uery as shown below
!hatever is there in the select statement must be there in the .!oup b% statement. )ut whatever is there in the .!oup b% statement need not be present in the select statement. /his is shown in the above two corrected <ueries. ASSIANMENT <# Displa% t e &epa!tment numbe!s alon. 4it t e numbe! o( emplo%ees in it
># Displa% t e ma'imum sala!% (o! eac o( t e Cob e'clu&in. all t e emplo%ees 4 ose name en&s 4it 9S:
B# Displa% t e &epa!tment numbe!s 4 ic a!e a;in. mo!e t an I111 as t ei! &epa!tmental total sala!%
NOTE : /o clear the screen the command used is cl sc! J if it is a large <uery and we cannot type it repeatedly then type in S,L 0 e& J when we type e& J G we get the notepad after ma"ing the necessary changes then clic" on the 9': i.e the close button at the top right corner then clic" on %es when a dialog bo$ as"ing whether to overwrite the file comes after this it comes to the oracle screen in the ne$t line enter 8 K 8 and hit on ente! button another way of ending the <uery is by typing 8 K 8 in the ne$t line of the <uery this indicates the end of the <uery.
CHAPTER &
STATEMENTS
Statements 3 they help us to create the table and insert the data. /here are 0 types of statements DDL Data Definition (anguage the various commands in DD( are MG ;reate Drop /runcate Alter .ename DML Data +anipulation (anguage the various commands in D+( are MG Insert ?pdate Delete TCL /ransaction ;ontrol (anguage the various commands in /;( are MG .ollbac" ;ommit %avepoint CREATE It creates the table. )efore we study the C!eate command let us first study the some of the basic &atat%pes we use in %'(. <# CHAR MG It stores the fi$ed length character data. It can store the alphanumeric data (i.e numbers and characters). 8# HARCHAR It stores the variable length character data It can store alphanumeric data. Marguda Solutions Pvt Ltd : Udith U.Kerudi 25 | P a g e
Di((e!ence bet4een CHAR E HARCHAR (et us consider an e$ample as shown below to e$plain the difference. N"#e ch"r '() * Nere we are defining name which is of 3characters in length. >ow let us store 8To#9 in the name field. (et us understand how the memory is allocated for this Blan/ Space
Rese!;e& K Non-!eusable memo!% !hen we declare anything of type c a! the memory is allocated as of the siBe given and its fi$ed length hence it cannot be altered. >ow when we give to# it allocates 3 bytes for name c a! only the 1st 0bytes are used to store Tom the rest becomes waste as it is a blan" space and it is reserved memory. /he len.t "name# L F. Name ;a!c a! "F# J Nere we are defining name which is of 3characters in length. >ow let us store 8To#9 in the name field. (et us understand how the memory is allocated for this Null
Re-usable memo!% !hen we declare anything of type ;a!c a! the memory is allocated as shown above and it is variable length !hen we give to# it allocates 3bytes for name ;a!c a! only the 1st 0bytes are used to store tom the remaining 0 fields becomes null. As we "now the property of null null does not occupy any memory space 3 t us t e memo!% is not 4aste& e!e$ /he len.t "name# L >. Marguda Solutions Pvt Ltd : Udith U.Kerudi 26 | P a g e
Anot e! &i((e!ence is M G In c a! ma$imum value we can store is *777 characters In ;a!c a! ma$imum value we can store is 1777 characters. ># N)MBER G it stores numeric data. *o! e' 3 <# sal numbe!"B# J Nere the ma$imum possible value is 6666. 8# sal numbe! "F+ 8# J Nere * scale (total number of decimal places) 3 precision (total number of digits including decimal places) +a$imum value is 6666.66 sal numbe! "B+ ># J ma$imum value is 6.666 sal numbe! "8+ 8# ma$imum value is .66 B# DATE G it stores date and time G no need to specify any length for this type. *o! e'+ %'( H orderRdt DA/@ E
NOTE :;a!c a!8 from 17g varchar = varchar* are the same. @arlier varchar was supporting upto *777 characters and varchar* was supporting upto 1777 characters.
=# BLOB %tands for )inary (arge &b#ect It stores binary data (images movies music files) within the database. It stores upto 1:). F# CLOB %tands for ;haracter (arge &b#ect It stores plain character data li"e ;a!c a! field upto 1:). C!eate t e (ollo4in. tables
PROD)CTS P!o&ID " P- # P!o&Name " Not Null # ,t% " C / 0 1 # Desc!iption
ORDERS P!o&ID " *- (!om p!o&ucts # O!&e!ID " P- # ,t%@sol& " c / 0 1 # P!ice O!&e!@Date
De can see t at t e table as been c!eate&$ >ow let us verify if the table has really been created and also the description of the table
/he new table o!&e!s has been created. !e can see from the above <uery how to reference a child table to the parent table using the !e(e!ences "eyword.
/hus we can verify that o!&e!s table has ben created and added to the database.
/hus we get the description of the o!&e!s table. C!eatin. a table (!om anot e! table MG >ow we will see how to create a table from another table i.e it duplicates all the records and the characterstics of another table. /he %'( <uery for it is as follows
/hus we can see that we have created another table temp from the table &ept. !e can verify it as shown below
/hus we can see that the table temp has been created.
/hus we can see that the table temp has copied the structure of the table &ept. Nere we must observe that temp copies all the columns rows and >&/ >?(( constraints only from the table &ept. It never copies -A ,A ;hec" constraints. T us+ 4 en in t e inte!;ie4 somebo&% as/s %ou 5I a;e a table 4 ic as about <million !eco!&s$ Ho4 &o I &uplicate it into anot e! table 4it out usin. Inse!t /e%4o!& an& 4it out inse!tin. it in&i;i&uall% all t e !eco!&s into t e &uplicate& table M Ans4e! is - )se t e abo;e 2ue!% o( c!eatin. a table (!om anot e! table an& e'plain it$
/hus from the above <uery we can see that all the records of the table &ept has been copied into the table temp. TR)NCATE It removes all the data permanently but the structure of the table remains as it is. E' 3 S,L 0 TR)NCATE TABLE test J DROP It removes both data and the structure of the table permanently from the database. Marguda Solutions Pvt Ltd : Udith U.Kerudi 3" | P a g e
E' 3 S,L 0 DROP TABLE test J (et us understand the difference between &!op E t!uncate using the below shown e$ample
/he above gives the description of the table /est*. >ow let us use the T!uncate 2ue!% on Test< and D!op 2ue!% on Test8 and see the difference. Marguda Solutions Pvt Ltd : Udith U.Kerudi 31 | P a g e
/he above 0 <ueries show that 1st <uery has the table test1 truncated. *nd <uery it shows no !o4s selecte& thus only the records from the table has been removed. 0 rd <uery it shows that the structure of the table is still present. &nly the records will be removed. /hus this e'plains t e t!uncate 2ue!%$
/hus from the above <ueries we can e$plain how &!op wor"s. 1st <uery it drops the table. /hus the entire structure and records of the table are dropped. *nd and 0rd <uery since there is no table select E &esc <uery for test8 will throw an error. /hus this e'plains t e &!op 2ue!%$ Nence we have seen the difference between &!op E t!uncate <uery. <1. Rec%cle Bin TABLE DROP
*LASHBAC-
RESTORE IT
PERMANENTLG REMOHE
P)RAE
/he functionality of .ecycle )in was introduced in &racle 17: version only. /hus even though the table has been dropped we can still restore it using (las bac/ comman& or we can permanently remove it using the pu!.e command. /his concept of .ecycle bin was not there in the earlier versions of &racle. RENAME It renames a table. *o! e'+ let us see the <uery of how we do this renaming a table.
In the above 0<ueries we have created a table temp which copies table &ept we see the records of the table temp and also chec" if the table has really been created. >ow let us !ename temp to temp8> as shown below Marguda Solutions Pvt Ltd : Udith U.Kerudi 33 | P a g e
/he above <uery is used to rename a table. >ow let us verify the contents of the table and chec" if it has really been modified %ee ne$t page
/hus the table has been renamed and its contents are verified. ALTER G this <uery alters / changes the structure of the table (i.e G adding columns removing columns renaming columns etc ). >ow let us alte! the table p!o&ucts (which we have created earlier). <# Let us a&& a ne4 column +#o,el-$o: to t e table$
/hus a new column has been added. (ets verify it with the <uery shown below
/hus we can see from the description of the table the column mo&el@no has been dropped. ># Let us !ename t e column .ty to .ty-"!"il"ble.
NOTE : SE/ECT is neit e! DML no! DDL$ It &oes not belon. to an% .!oup because it &oes not alte! an%t in.+ it Cust &ispla%s t e &ata as !e2ui!e& b% t e use! . Marguda Solutions Pvt Ltd : Udith U.Kerudi 35 | P a g e
DML
INSERT It inserts a record to a table. (et us observe how it is done
/his is how we insert values into a table. All characters and alphaGnumeric characters(e$ 177*0sdf45) must be enclosed in single <uotes (8 8 ) and each value must be separated by comma. Also we must be careful in entering the data without violating the primary "ey foreign "ey uni<ue constraints. >ow let us see the table in which the data in has been inserted
>ow let us insert data into the table o!&e!s in which a foreign "ey is referencing primary "ey
Nere we see that 1771 is the same prodid as of the earlier table. %ysdate it displays the current date set in the system . Marguda Solutions Pvt Ltd : Udith U.Kerudi 36 | P a g e
)PDATE MG It updates one or more records. *o! e' 3 <# (et us update salary by increasing it by .s*77 and also give commission of .s177 where empno D 4036.
/hus the record(empno 4036) has been updated. 8# Inc!ease all sala!% b% <1?
(et us verify it
DELETE It deletes one / some / all the records. (et us create a table test from table emp and see how to delete 1 record and how to delete all records from it
/hus we have created the table test. Marguda Solutions Pvt Ltd : Udith U.Kerudi 3! | P a g e
TCL
Any D+( change on a table is not a permanent one. !e need to save the D+( changes in order to ma"e it permanent !e can also undo (ignore) the same D+( changes on a table. /he DD( changes cannot be undone as they are implicitly saved. ROLLBACIt undoes the D+( changes performed on a table. (et us see in the below e$ample how !ollbac/ wor"s
(et us delete the employee table. !hen we perform select operation on emp we can see that all the rows have been deleted. !e now perform the !ollbac/ operation Marguda Solutions Pvt Ltd : Udith U.Kerudi 4" | P a g e
/hus performing the !ollbac/ operation we can retrieve all the records which had been deleted. COMMIT It saves the D+( changes permanently to the database. Committin. a(te! !ollbac/ E ;ice ;e!sa 4ill not a;e an% e((ect (et us e$plain the above statement with an e$ample
/hus from above we can see that !ollbac/ has no effect after commit operation. During an abnormal e$it i.e shutdown or if the %'( window is closed by mouse clic" then all the D+(9s will be rolled bac" automatically. Marguda Solutions Pvt Ltd : Udith U.Kerudi 42 | P a g e
During a normal e$it e'it J G all the D+(9s will be autoGcommitted and there will be no rollbac". E' 3 <# I>%@./ ?-DA/@ A(/@. D@(@/@ .&(()A;A !hen we perform the following operations in the same order for a table then I>%@./ ?-DA/@ will be committed because A(/@. is a DD( and thus all the D+(9s above it will also be committed because DD( operations cannot be undone. Nere only D@(@/@ will be rolled bac" because it9s a D+(. 8# I>%@./ ?-DA/@ D@(@/@ .&(()A;A Nere all are rolled bac". SAHEPOINT M It is li"e a pointer (brea"Gpoint) till where a D+( will be rolled bac". E' :Insert S %ave point $ E ?pdate S Delete .. .ollbac" to $ E S S Nere only D@(@/@ = ?-DA/@ are rolled bac". I>%@./ is neither rolled bac" nor committed.
Assi.nments <# C!eate t e (ollo4in. tables a) /able name MG %/?D@>/% regno (-A) name (>>) semester D&) Marguda Solutions Pvt Ltd : Udith U.Kerudi 43 | P a g e
-hone b) /able name MG )&&A% boo"no (-A) bname author c) /able name MG (I).A.K regno (,A from students) boo"no (,A from boo"s) D&I date of issue D&. date of return 8# Inse!t = !eco!&s to eac o( t ese tables ># Di((e!entiate bet4een+ a# Delete an& T!uncate b# T!uncate an& D!op c# C a! an& Ha!c a! &# D!op an& Delete Delete and /runcate a) Delete deletes whichever records we want to delete from the table /runcate deletes all the records whether we want it or not b) Delete can be undone /runcate cannot be undone.
NOTE /he -rimary Aey created using more than 1 column is called as co#posite pri#"ry 0ey. @$ alte! table lib A&& p!ima!% /e% "!e.no+ boo/no+ DOI# E
CHAPTER (
S)B - ,)ERIES
A subG<uery is also called as a nested <uery. S%nta' o( a sub-2ue!% Marguda Solutions Pvt Ltd : Udith U.Kerudi 44 | P a g e
O)TER ,)ERG
Nere the inne! 2ue!% will be e$ecuted first. /he output of inne! 2ue!% is passed as input to the oute! 2ue!%$ /o write a subG<uery atleast 1 common column should be e$isting between the tables. *o! e' :<# List t e emplo%ees 4o!/in. in 9Resea!c : &epa!tment$
># List t e &epa!tment names t at a!e a;in. atleast < emplo%ee in it$ Marguda Solutions Pvt Ltd : Udith U.Kerudi 46 | P a g e
/his method is not efficient to find the ma$imum and minimum salary. /he limit is 0*. /his is not efficient if you want to find the 177th ma$imum salary. De can a;e upto >8 le;els o( sub-2ue!ies onl%$ I# List t e &epa!tment names t at a!e a;in. no emplo%ees at all
CHAPTER 1
QOIN
Marguda Solutions Pvt Ltd : Udith U.Kerudi 4 |Page
Qoins are used when we need to fetch the data from multiple tables T%pes o( QOIN"s# ;artesian Toin (product) Inner (@<ui) Toin &uter Toin G (eft &uter Toin .ight &uter Toin ,ull &uter Toin %elf Toin CARTESIAN QOIN G It is based on ;artesian product theory. Ca!tesian P!o&uct T eo!% in +athematics states that MG (et there be two sets A U1 * 0V = ) U1 2V /hus the ;artesian product (AF)) will be A F ) D U (1 1) (1 2) (* 1) (* 2) (0 1) (0 2) V /hus there are 3 sets order of A is 0 = order of ) is *. /herefore *F0 D 3 is the ;artesian product.
Nere each and every record of the 1st table will combine with each and every record of the *nd table. If a table A is having 17 records = ) is having 1 records the ;artesian #oin will return 17F1 D 17 records. *o! e'+ let us consider the following <uery Displa% emplo%ee name alon. 4it t e &epa!tment name
,rom above we can see that the above <uery returns 23 records but we are e$pecting 11 records. /his is because each and every record of employee table will be combined with each = every record of department table. /hus ;artesian #oin should not be used in real time scenarios. /he ;artesian #oin contains both correct and incorrect sets of data. !e have to retain the correct ones = eliminate the incorrect ones by using the inne! Coin. INNER QOIN Inner #oin are also called as e2uiCoins. /hey return the matching records between the tables. In the real time scenarios this is the most fre<uently used Toin. *o! e'+ consider the <uery shown below %elect A.ename A.sal ).dname ,rom emp A dept ) !here A.deptno D ).deptno And A.sal H *777 &rder by A.sal E (et us see the output shown below
T&I> condition is mandatory for removing the ;artesian output. (et us consider the following * scenarios shown below Scena!io <
P A , R
B S
C R
De 4ant P , S R
T e S,L 2ue!% 4ill be+ Select A.- A.' ).% ;.W ,rom A ) ; !here A.- D ).Numbe! o( Coins L 8 And A.- D ;.T e!e(o!e+ Numbe! o( QOINS L Numbe! o( tables - <
A ,
B P , S T
C R
De 4ant R
/he S,L 2ue!% is + %elect A.- A.' A.. ).% ;.W ,rom A ) ; !here A.- D ).And A.' D ).' Numbe! o( Qoins L > And A.- D ;.- E
T e!e(o!e+
If there are no common columns then re#ect it saying that the two tables can be #oined. )ut there are some cases where the * columns will be same but having different column names. *o! e' 3 customerid = cid Displa% emplo%ee name+ is Cob+ is &name an& is location (o! all t e mana.e!s li;in. in Ne4 Go!/ o! C ica.o
ANSI st%le QOINS /his was introduced from &racle 6i. Marguda Solutions Pvt Ltd : Udith U.Kerudi 52 | P a g e
/hus we can see the changes In the *nd line G (comma) has been replaced by the word 8#oin9 In the 0rd line 8where9 has been replaced with 8on9 Assi.nment <# Displa% emplo%ee name an& is &epa!tment name (o! t e emplo%ees 4 ose name sta!ts 4it 9S:
O)TER QOIN It returns both matching and nonGmatching records &uter #oin D inner #oin C nonGmatching records >onGmatching records means data present in one table but absent in another table w.r.to common columns. *o! e'+ 17 is there in deptno of dept table but not there in deptno of emp table. Displa% all t e &epa!tment names i!!especti;e o( an% emplo%ee 4o!/in. in it o! not$ I( an emplo%ee is 4o!/in. 3 &ispla% is name$ Marguda Solutions Pvt Ltd : Udith U.Kerudi 53 | P a g e
2si$ ri ht 3oi$
A CQ B L F1!eco!&s A IQ B L >!eco!&s"> matc in.# A LQ B L <1!eco!&s ">matc in. S Onon matc in. o( A# A RQ B L F!eco!&s ">matc in. S >non matc in. o( B# A *Q B L <>!eco!&s ">matc in. o( A E B S Ononmatc in. o( A S >nonmatc in. o( B# Assi.nment <# Displa% emplo%ee name an& is &epa!tment name (o! t e emplo%ees 4 ose name sta!ts 4it 9S: Marguda Solutions Pvt Ltd : Udith U.Kerudi 54 | P a g e
8# Displa% emplo%ee name an& is &epa!tment name 4 o is ea!nin. <st ma'imum sala!%
SEL* QOIN Toining a table to itself is called self #oin /he *ROM clause loo"s li"e this ,.&+ emp A emp ) &r ,.&+ emp A #oin emp ) G ANSI style
Emp "A# EmpNo Ename 171 %cott 17* )la"e 170 Aing 171 %mith 172 Tones
Emp "B# EmpNo Ename 171 %cott 17* )la"e 170 Aing 171 %mith 172 Tones
>ow when we give the above <uery in &racle it starts matching the 8 m.!9 column of emp A with the 8empno9 of emp b we get two tables because in sel( Coin a duplicate of the table re<uired is created. >ow let us consider the (i!st emplo%ee Scott it starts the m.!i& of Scott with the empno of all the records in emp B when two i&s match then the empno in emp B becomes the m.! of the empno in emp A. /hus we can see that m.! i& 17* is matching with empno 17* Bla/e in emp B. /herefore )la"e is the manager of %cott. %imilarly we do the same for all the other records of emp A and thus find the employees and their respective managers. Displa% t e emplo%ees 4 o a!e .ettin. t e same sala!%
Co 3 !elate& ,ue!ies : /hey are special type of sub <ueries Nere both outer = inner <ueries are interGdependent ,or each = every record of outer <uery the entire inner <uery will be e$ecuted /hey wor" on the principles of both sub 3 2ue!ies E QOIN"s#.
/hus if an outer <uery column is being accessed inside the inner <uery then that <uery is said to be coGrelated. (et us see the logic i.e how we get the 1st ma$ salary MG
Emp "A# EmpNo 171 17* 170 171 172 Ename %cott )la"e Aing %mith Tones Sal 0777 1777 2777 *777 1777
Emp "B# EmpNo Ename 171 %cott 17* )la"e 170 Aing 171 %mith 172 Tones
%ince coGrelated <ueries are a combination of Toins and subG<ueries. It follows the concept of Toins and creates multiple copies of the same table. /hen it ta"es 1st record i.e G )la"e sal is 0777. It starts comparing with the sal in the emp table 0777 D 0777 G count starts from 7 thus 7 D 7 0777 O 1777 thus 7 P D 1 0777 O 2777 thus 7 P D * 0777 H *777 thus 7P D * 0777 H 1777 thus 7 P D * if the condition becomes false then the count increments by 1. Nere 0777 is less than 1777 = 2777 thus 7 P D *. /hus )la"e does not have the highest salary. %imilarly it does for the ne$t records )la"e salary of 1777 but 1777 O 2777 thus 7 P D 1. /his is also false. Aing salary of 2777 it is greater than everything thus 7 D 7. /hus Aing has the highest salary. Marguda Solutions Pvt Ltd : Udith U.Kerudi 57 | P a g e
)ut the <uery doesn9t stop here it chec"s for %mith = Tones as well. %imilarly if we want to find the *nd ma$imum salary /hen in the <uery change 879 to 819 = here the logic is it compares until it gets 1 D 1. ,or 0rd ma$imum salary change 7 to * and so on here the logic is it compares until it gets * D *. *o! an% i. est+ al4a%s put it as 91: in t e 2ue!%$ I( %ou 4ant n"t # sala!%+ pass "n-<#$ In inte!;ie4 3 t is is a &e(inite 2uestion$ T e% 4ill as/ %ou 4 at is co-!elate& 2ue!ies$ An& t en t e%:ll as/ %ou (in&+ <st o! ma' o! >!& ma'imum sala!% 3 a(te! %ou 4!ite t e 2ue!% 3 t e% 4ill as/ %ou to e'plain t e lo.ic as to o4 it .ets t e same 3 &!a4 t e table an& e'plain it to t em Cust as s o4n abo;e$
=# Displa% <st+ Bt E Ft
CHAPTER 4
*)NCTIONS
,unctions it is a reGusable program that returns a value. /here are 8 t%pes -re defined ?ser defined P!e 3 &e(ine& :.&?- functions ;NA.A;/@. functions >?+@.I; functions DA/@ functions %-@;IA( functions /hese are used both in %'( and -(/%'(. -( -rocedural (anguage (it9s a e$tension to %'( can contain I, statements loops e$ceptions &&-s etc .. ) )se! 3 &e(ine& ?sed only in -(/%'( and we will not study it here. !e have already learnt about :.&?- functions. Marguda Solutions Pvt Ltd : Udith U.Kerudi 6" | P a g e
>ow let us study the various ;NA.A;/@. functions. CHARACTER (unctions a) ?pper b) (ower c) (ength *o! e' :-
In the 1st <uery we see something called as &ual. Dual 3 is a dummy table which is used for performing some independent operations which will not depend on any of the e$isting tables. *o! e'+ 1)
*)
0)
!e use dual when the data is not present in any of the e$isting tables. /hen we use dual. Len.t it returns the length of a given string. *o! e'+ <#
8#
># Displa% all t e emplo%ees 4 ose name E Cob is a;in. e'actl% = c a!acte!s
REPLACE It replaces the old value with a new value in the given string. *o! e'+
Nere a 3 is the old value to be replaced with p which is the new value.
/his <uery replaces all the names which has 8A9 in it with 8)9. (et us see the output as shown below
S)BSTR /his is called subst!in.. It e$tracts 8n9 characters from $(th) position of a given string. *o! e'+
Nere + "Cob+ 9<: + 9>:# means from Cob e$tract (!om <st position + > c a!acte!s. <# Displa% t e emplo%ees 4 ose Cob sta!ts 4it 9man:
INSTR /his is also called as inst!in.$ It returns position of a given character in a given string. *o! e'+ Select i$str '+or"cle5 6 +"5 6 1 6 1) fro# ,u"l * :iven string
;haracter to be searched -osition from where the search should begin >umber of occurences
List t e emplo%ees 4 ose Cob is a;in. atleast 8 A:s in it Marguda Solutions Pvt Ltd : Udith U.Kerudi 67 | P a g e
N)MERIC *)NCTIONS 1) Mo& MG it returns the remainder when 1 number is divided by the other.
Displa% t e emplo%ees ea!nin. o&& numbe!e& sala!ies$ Marguda Solutions Pvt Ltd : Udith U.Kerudi 6 |Page
Roun& It rounds off a given number to the nearest decimal place. T!unc It truncates the given number to the given decimal place. /runcate does not do any rounding. *o! e'+
Nere 8<9 indicates the number of positions. DATE *)NCTIONS <# S%s&ate %tands for %ystem date. It returns both date = time but by default only date is displayed. /he default format is && 3 mon 3 %%
Nere $I<B111 gives the fraction of millisecond which "eeps changing as shown below
In inte!;ie4 3 i( t e% as/ %ou 3 7 which fu$ctio$ co$t"i$s fr"ctio$s of " seco$, 7 OR 7how to see the syste# ti#e 7 3 t en ans4e! is 5SGSTIMESTAMP7$ SPECIAL *)NCTIONS <# TO 3 CHAR ?sed for displaying the date in different formats. *o! e'+
!e can see that 2 hrs has been added to the current time.
/he above <uery means if the employee has commission then add sal C comm. /o get total salary else add 7 to the sal and display total salary. DECODE It wor"s li"e 8i( 3 t en 3 else9 statement. *o! e'+
/he above <uery states that in #ob if cler" is there replace with ; else if salesman is there replace it with % else replace with 8&9. Marguda Solutions Pvt Ltd : Udith U.Kerudi 72 | P a g e
Displa% emplo%ee name+ Cob+ sala!% an& commission$ I( t e commission is N)LL+ t en &ispla% -<11
CHAPTER 8
NORMALIUATION
No!mali6ation is the process of splitting the bigger table into many small tables without changing its functionality. It is generally carried out during the design phase of %D(;. A&;anta.es 1) it reduces the redundancy (unnecessary repeatation of data) *) avoids problem due to delete anamoly (inconsistency) >ormaliBation is a stepGbyGstep process and in each step we have to perform some activities. STEPS IN NORMALIUATION 1) 1>, 1st >ormal form *) *>, *nd >ormal form 0) 0>, 0rd >ormal form <N* G !e should collect all the re<uired attributes into 1 or more bigger entities. G !e have to assume no * records are same (i.e records should not be duplicated) G Identify the probable primary "ey At the end of 1>, our data loo"s li"e this
COLLEAE .eg>o - P%name %emester D&) +ailID -hone )oo">o G P)name Author D&I D&. ,ine
8N* /o perform *>, G /he tables have to be in 1>, G Nere we identify all the complete dependencies and move them separately into different tables. At the end of *>, our data loo"s li"e this
ST)DENTS .eg>o G -A BOO-S )oo">o G -A
>N* /he table will have to be in *>, Nere we identify all the partial dependencies and move such columns to a separate table.
ST)DENTS .eg>o G -A %name %emester D&) +ailID -hone
Disa&;anta.e o( No!mali6ation /he only minor disadvantage is we may have to write comple$ <ueries as we have more number of tables to be accessed. Deno!mali6ation is the process of combining more than 1 smaller table to form 1 bigger table is called as denormaliBation. CODD !ules ( Di((e!entiates bet4een DBMS E RDBMS ) 1) should support >?(( values *) should support creation of relationship between tables 0) should support DD( D+( /;( 1) should support constraints li"e -A ?ni<ue ;NA 2) should support <uery techni<ues li"e sub <ueries #oins grouping etc. O!acle Ii *eatu!es "i means inte!net# G /I+@%/A+- datatype G %K%/I+@%/A+- function G A>%I style #oins G .enaming a column O!acle <1. (eatu!es ". means .!i&# G .ecycle )in ERD - Entit% Relations ip Dia.!am It is the pictorial representation of all the entities and their relationships (tables).
VERY IMPORTANT P one No$ o( Chethan Sir 9741120618 Email i& o( chethan ir c et an(i. W %a oo$com VVVVV THE END VVVVV