CHAPTER 1
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 – 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 eld / attribute A record is also called as a row / tuple. A table is also called as an entity / relation. Note :If we inst instal alll any any of the the data databa base se relat elated ed soft softwa warre(s e(s – we can can crea create te our our own 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 databa database se can also also contai contain n other other datab databas ase e ob$ect ob$ects s li#e li#e views views!! inde% inde%es! es! store stored d • 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*,& 0he s/w which is widely used today is 'racle. 0he dierent versions of 'racle starting from the earliest to the latest are – 'racle +! 'racle 2! 'racle 3! 'racle 4! 'racle 5! 'racle 6! 17age
'racle 8i! 'racle 9i! 'racle 1:g! and the latest to hit the mar#et is 'racle 11g. here ;i< stands for Internet and ;g< stands for =rid / =rid computing. RELATIONSHIPS A relationship is the association between any two tables which preserves data integrity. Relationsips
Dept No$
Dept Name
Emp No$
Emp Name
Dept No$
Sala!%
1:
Accounting
1:1
A
1:
+::::
+:
esearch
1:+
*
1:
2:::: :
2:
&ales
1:2
>
+:
2::::
Maste! " Pa!ent #
Detail " Cil& #
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. 0he master table table contains the master data data which will will not change change fre?uently fre?uently.. 0he child table table contains the the transactional transactional data which which will change change ?uite often. often. DBMS @ RDBMS DBMS – 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 – RDBMS – stands for elational D*,& D*,& D*,& is also also a databa database se s/w s/w which which has facili facility ty to handl handle e more more data data volu volume! me! good 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 E' for D*,& – -o%ro! -o%*ase! Dbase E' for E' for D*,& – 'racle! &ybase! D*+! 0eradata! &) &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 '0 B)) +7age
BIBC rimary ey -oreign ey >hec#
N)LL → → → → →
B)) is nothing! it is neither Eero nor blan# space It will not occupy any space in the memory 0wo 0wo B))& are are never same in in 'racle. B)) represents un#nown value Any arithmet arithmetic ic opera operatio tion n we perfor perform m on B)) B)) will will resu result lt in B B)) )) itself itself.. *o! e'+ 1::::: F B)) G B)) H 1::::: B)) G B))
NOT N)LL J '0 B)) will ensure atleast some value should be present in a column )NI,)E → It will not allow any duplicates in a column → BIBC column can ta#e multiple B)) (s P!ima!% e% N)LL and )NI,)E → It is the combination of NOT N)LL and → 'nly one is allowed in a table → identies a record uni?uely in a table → >reation of is not mandatory! but it is highly recommended to create *o!ei.n e% → - creates relationship between any two tables → - is also called as referential integrity constraints → - is created on the child table → - can ta#e both B)) and duplicate values 0o create -! the master table should have dened on the common column of the → 0o master table → "e can have more than 1 - in a given table CHEC It is used to provide additional validations as per the customer re?uirements. E' - 1 sal K : + empnum should start with 1 2 commission should be between 1::: @ 4:::
Cec/ "sal 0 1#
27age
P
NN
P
NN
*
NN
)ni2u e
)ni2u e
Dept No$
Dept name
Emp No$
Emp Name
Dept No$
Sala!%
P No$
Email
1:
Accountin g
1:1
A
1:
+:::: :
++++
aLgm ail
+:
esearch
1:+
*
1:
2::::
J
J
2:
&ales
1:2
>
+:
3:::: :
2222
J
RELATIONSHIP
N)LL
CHAPTER 2
S,L 3 St!uctu!e& ,ue!% Lan.ua.e 37age
&) – &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. 0o 0o wor# on &) &) ! a D* software software (D*,& (D*,& is re?uired. re?uired. &) is not case sensitive )se!name J &cott Pass4o!& – Pass4o!& – 0iger T!oublesootin. O!acle Error 1 0he account account is loc#ed loc#ed Steps to rectify the error )ogin as username – ;system< @ password – ;manager< or ;password – ;tiger< • &) K show user H • Bser is M&N&0C,O
&) K alter user scott account unloc# H Bser altered &) K e%it H Error 2 0& P protocol protocol adapter error error How to troubleshoot this >ause is Moracle service has not startedO
Qow to go here! &ettings – >ontrol anel – Administrative 0ools – &ervices &ort the list 0here is an M'racle M'racle &ervice &ervice '>) '>)O @ Mstart the serviceO serviceO
47age
0his ?uery ?uery gives the list list of tables. tables. J selects all
0his ?uery ?uery gives the description description of of the table MdepartmentO. MdepartmentO. 0he description description of the table table has column names+ const!aints+ &atat%pes
0his ?uery ?uery gives the description description of of the table MdepartmentO MdepartmentO
0he above ?uery ?uery gives the the description description of the MemployeeO MemployeeO table. *ut we see that all the the data is in dierent lines which ma#es it very diRcult to analyse. &o we use the following command to see the data in a more orderly fashion!
57age
0he 5set linesi6e7 command linesi6e7 command helps in increasing the line siEe ! thus the data is arranged in a orderly fashion.
0he above command command 5set pa.esi6e 817 increases 817 increases the page siEe! thus accommodating more number of rows in a single page.
67age
0he above ?uery ?uery gives the the value of only only these 2 columns columns from from the table MemployeeO. MemployeeO.
94e!e clause 94e!e clause is used to restrict the number of records displayed. It gives only the records of the specied condition.
Any string data should be enclosed within sin.le 2uotes 2uotes ( ; ; and the the same same beco becomes mes case sensiti;e. sensiti;e. Assi.nment <# List te emplo%ees in &ept 81
87age
8# List te emplo%ees ea!nin. mo!e tan Rs 8=11$
># Displa% all salesmen
CHAPTER 3
OPERATORS 97age
'perators are classied into! A!itmetic Ope!ato!s ( Ope!ato!s ( F! J ! ! / • Relational Ope!ato!s ( Ope!ato!s ( K ! S ! KG ! SG ! G ! S K o! TG o! TG J not e?uals to • Lo.ical Ope!ato!s ( Ope!ato!s ( '0! AD! ' • Special Ope!ato!s ( I ! )IC ! *C0"CC ! I& • SPECIAL OPERATORS <# IN – IN – it is used for evaluating multiple values. E' 3 <# )ist <# )ist the employees in dept 1: @ +:
8# )ist all the cler#s and analysts
"e can provide upto 1::: values at the ma%
8# LIE – LIE – used for pattern matching ? "pe!centa.e# - matches : or ;n< characters 1: 7 a g e
@ "un&e!sco!e# J "un&e!sco!e# J matches e%actly one character E' 3 <# List all te emplo%ees 4ose name sta!ts 4it 9S
"henever we use U or V ! always ensure that it is preceded by the word 9li/e 8# List Lis t te emplo%ee emp lo%ees s 4ose name n ame is a;in. a ;in. lette! l ette! 9L as 8 n& ca!acte!
ASSINMENT <# List te emplo%ees emp lo%ees 4ose name is i s a;in. atleast atl east 8 Ls Ls
8# List List te te empl emplo% o%ee ees s 4os 4ose e name name is a;i a;in. n. lett lette! e! 9E 9E as te te last last but but one one ca!acte!
># List all te emplo%ees 4ose 4o se name is a;in. a;in . lette! 9R in te > !& position
11 7 a g e
In the above ?uery! we give + underscores before U. # List all te emplo%ees 4o a!e a;in. e'actl% = ca!acte!s in tei! obs
Qere ! in single ?uotes – we give 4 underscores. =# List te emplo%ees 4ose name is a;in. atleast = ca!acte!s
Qere! also in single ?uotes – we give 4 underscores ( VVVVV
># BETEEN operator BETEEN operator – used for searching based on range of values. E' 3 <# )ist the employees whose salary is between +:: and 2::
1+ 7 a g e
# IS operator – it is used to compare nulls E' 3 <# )ist all the employees whose commission is null
ASSINMENT <# List all te emplo%ees 4o &ont a;e a !epo!tin. mana.e!
LOICAL OPERATORS <# List all te salesmen in &ept >1
12 7 a g e
8# List all te salesmen in &ept numbe! >1 an& a;in. sala!% .!eate! tan <=11
># List all te emplo%ees 4ose name sta!ts 4it 9s o! 9a
# List all te emplo%ees e'cept tose 4o a!e 4o!/in. in &ept <1 81$
=# List te emplo%ees 4ose name &oes not sta!t 4it 9S
13 7 a g e
F# List all te emplo%ees 4o a!e a;in. !epo!tin. mana.e!s in &ept <1
ASSINMENT <# List te emplo%ees 4o a!e not 4o!/in. as mana.e!s an& cle!/s in &ept <1 an& 81 4it a sala!% in te !an.e o( <111 to >111
8# List List te emplo%e emplo%ees es 4ose 4ose sala! sala!% % not not in te !an.e !an.e o( <111 <111 to 8111 8111 in &ept &ept <1+81+>1 e'cept all salesmen 14 7 a g e
># List te &epa!tment names 4ic a!e a;in. lette! 9O in tei! locations as 4ell as tei! &epa!tment names
SORTIN It arranges the data either in ascending / descending order Ascending – A&> / Descending – DC&> "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 te emplo%ees b% tei! sala!%
15 7 a g e
8# A!!an.e all te emplo%ees b% tei! sala!% in te &escen&in. o!&e!
># A!!an.e ename+ sal+ ob+ empno an& so!t b% &escen&in. o!&e! o( sala!%
16 7 a g e
In the above ?uery we have – o!&e! b% 8 – 8 – thus it arranges only the + nd column ;salary< in the descending order. 0hus to arrange the specic columns in order – we must have to specify the column number. NOTE :- ORDER BG should should be used always as the last statement in the &) ?uery.
Selectin. DISTINCT AL)ES
0he above ?uery ?uery arranges arranges all the distinct distinct values values of department department number. number.
CHAPTER
RO)P (unctions an& !oupin.
18 7 a g e
"e have = RO)P functions! RO)P functions! 1 &um + ,a% 2 ,in 3 Avg 4 >ount Sum 3 returns total value Ma' – Ma' – returns ma%imum value Min – Min – returns minimum value A;. – A;. – returns average value Count 3 returns number of records E' 3 <# &isp &ispla la% % te te ma'i ma'imu mum m sala sala!% !%++ mini minimu mum m sala sala!% !% an& an& tota totall sala sala!% !% (!om (!om emplo%ee
To !i"e !i" e #li#ses #li# ses for f or the colu$%s colu $%s :-
># Te belo4 2ue!% .i;es te total numbe! o( emplo%ees
# Te belo4 2ue!% .i;es te numbe! o( emplo%ees 4o a;e commission
=# List te numbe! o( emplo%ees in &epa!tment >1
19 7 a g e
ASSIMENT <# Displa% te total sala!% in &epa!tment >1
8# List te numbe! o( cle!/s in &epa!tment 81
># List te i.est an& lo4est sala!% ea!ne& b% salesmen
RO)PIN It is the proce process ss of compu computin ting g the aggre aggregat gates es by segre segregat gating ing based on one or more more columns. +: 7 a g e
=rouping is done by using 9.!oup b% clause. b% clause. *o! e' 3 <# Displa% te total sala!% o( all &epa!tments
8# Displa% te ma'imum o( eac ob
HAIN 9Ha;in. is 9Ha;in. is used to lter the grouped data. 9e!e is 9e!e is used to lter the non grouped data. ;Ha;in. should Ha;in. should be used after .!oup b% clause b% clause 9e!e should 9e!e should be used before .!oup b% clause b% clause *o! e' 3 <# Displa% ob-4ise i.est sala!% onl% i( te i.est sala!% is mo!e tan Rs<=11
+1 7 a g e
8# Displa% Displa% ob-4is ob-4ise e i.est i.est sala!% onl% i( te i.est i.est sala!% is mo!e tan <=11 e'clu&in. e'clu&in. &epa!tment >1$ So!t te &ata base& on i.est sala!% in te ascen&in. o!&e!$
RESTRICTIONS ON RO)PIN J we can select only the columns that are part of ;.!oup ; .!oup b% statement b% statement If we try selecting other columns! we will get an error as shown below!
0he above ?uery is an error error because ob< ;ob< is there in the select ?uery select ?uery but not in the .!oup b% ?uery. b% ?uery. If it is enclosed in any of the .!oup (unctions li/e sum"sal# etc sum"sal# etc – then it is not an error. *ut whatever table is included in the select ?uery select ?uery must also be included in the .!oup b% ?uery. 0he above problem problem can be overcome overcome with the following following ?uery ?uery as shown shown below!
++ 7 a g e
0he below ?uery ?uery is also also correct correct to rectify rectify the above error! error!
"hatever is there in the select statement select statement must be there in the .!oup b% statement. b% statement. *ut! whatever is there in the .!oup b% statement b% statement need not be present in the select statement. select statement. 0his is shown shown in the above above two corrected corrected ?ueries. ?ueries. ASSINMENT <# Displa% te &epa!tment numbe!s alon. 4it te numbe! o( emplo%ees in it
8# Displa% te &epa!tment numbe!s 4ic a!e a;in. mo!e tan emplo%ees in tem
+2 7 a g e
># Displa Displa% % te ma'imum ma'imum sala!% sala!% (o! eac o( te ob e'clu&i e'clu&in. n. all te emplo%ees emplo%ees 4ose name en&s 4it 9S
# Displa Displa% % te &epa!tment &epa!tment numbe!s numbe!s 4ic a!e a;in. a;in. mo!e tan 111 as tei! &epa!tmental &epa!tmental total sala!%
NOTE : 0o 0o clear the screen! screen! the command used 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 J we get the notepad – after ma#ing the necessary changes – then clic# on the 9' i.e! 9' i.e! the close button at the top right corner – then clic# on %es when %es when a dialog bo% as#ing whether to overwrite the le comes – after this it comes to the oracle screen – in the ne%t line ! enter ;K ;K ; and hit on ente! button ente! button – another way of ending the ?uery is by typing ; K ; K ; in the ne%t line of the ?uery – this indicates the end of the ?uery.
CHAPTER &
STATEMENTS
+3 7 a g e
Statements 3 they help us to create the table and insert the data. 0here are are 2 types of statements! statements! DDL – Data Denition )anguage – the various commands in DD) are PJ >reate! Drop! 0runcate! 0runcate! Alter! Alter! ename ename DML L – Data ,anipulation )anguage – the various commands in D,) are PJ Insert! DM Bpdate! Delete TCL – 0ransaction >ontrol )anguage – the various commands in 0>) are PJ ollbac#! >ommit! &avepoint CREATE – CREATE – It creates the table. *efore we study the C!eate command! C!eate command! let us rst study the some of the basic &atat%pes we use in &). <# CHAR PJ CHAR PJ It stores the %ed length character data. It can store the alphanumeric data (i.e! numbers and characters. 8# ARCHAR It stores the variable length character data It can store alphanumeric alphanumeric data. Die!ence bet4een CHAR ARCHAR )et us consider an e%ample as shown below to e%plain the dierence. N#$e ch#r '() * Qere we are dening name which name which is of 5characters in length. ow! let us store ; To$< in the name eld. )et us understand how the memory is allocated for this!
Blan/ Space
T
O
M
-
-
-
Rese!;e& K Non-!eusable memo!% +4 7 a g e
"hen we declare anything of type ca!! ca!! the memory is allocated as of the siEe given and its %ed length – hence it cannot be altered. ow! when we give to$! it allocates 5 bytes for name ca! – ca! – only the 1 st 2bytes are used to store Tom – om – the rest becomes waste as it is a blan# space and it is reserved memory. 0he len.t"name# F F.. Name ;a!ca! "F# J Qere we are dening name which name which is of 5characters in length. ow! let us store ; To$< in the name eld. )et us understand how the memory is allocated for this! Null
T
O
M
$
$
$
Re-usable memo!% "hen we declare anything of type ;a!ca!! ;a!ca!! the memory is allocated as shown above and it is variable length "hen we give to$! it allocates 5bytes for name ;a!ca! – ;a!ca! – only the 1 st 2bytes are used to store tom – tom – the remaining 2 elds becomes null. null. As we #now the property of null – null – null does not occupy any memory space 3 space 3 tus te memo!% is not 4aste& e!e$ 0he len.t"name# > >.. Anote! &ie!ence is P is P J In ca!! ca!! ma%imum value we can store is +::: characters In ;a!ca!! ;a!ca!! ma%imum value we can store is 3::: characters. ># N)MBER J it stores numeric data. *o! e' 3 <# sal numbe!"# J Qere the ma%imum possible value is 9999. 8# sal numbe! "F+ 8# J Qere! + – scale (total number of decimal places 5 – precision (total number of digits including decimal places ,a%imum value is 9999.99 sal numbe! "+ ># J ma%imum value is 9.999 sal numbe! "8+ 8# ma%imum value is .99 # DATE J it stores date and time +5 7 a g e
J no need to specify any length for this type. *o! e'+
&) K orderVdt DA0C H
Date is always displayed in the default format PJ
&& 3 mont 3 %%
NOTE :;a!ca!8 – ;a!ca!8 – from 1:g! varchar @ varchar+ are the same. Carlie Carlier! r! varc varchar har was was suppor supportin ting g upto upto +::: +::: charac character ters s and varc varchar har+ + was supporting supporting upto 3::: characters.
=# BLOB &tands for – *inary )arge 'b$ect It stores binary data (images! movies! music les within the database. It stores upto 3=*. F# CLOB &tands for – >haracter )arge 'b$ect It stores plain character data li#e ;a!ca! eld ;a!ca! eld upto 3=*. C!eate te (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
+6 7 a g e
e can see tat te table as been c!eate&$ ow! let us verify if the table has really been created and also the description of the table!
0he new table table p!o&ucts has p!o&ucts has been added to the database.
0hus! we get get the description description of the table table p!o&ucts. p!o&ucts.
0he new table table o!&e!s has 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. !e(e!ences #eyword.
+8 7 a g e
0hus we can can verify that o!&e!s table o!&e!s table has ben created and added to the database.
0hus! we get get the description description of the o!&e!s table. o!&e!s table. C!eatin. a table (!om anote! table PJ table PJ 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. 0he &) ?uery ?uery for it is is as follows! follows!
0hus we can can see that we have have created created another table table temp from temp from the table &ept. &ept. "e can verify it as shown below!
0hus! we can can see that the table temp has temp has been created.
+9 7 a g e
0hus! we can see that the table temp has temp has copied the structure of the table &ept. &ept. Qere! we must observe that temp copies temp copies all the columns! rows and '0 B)) constraints only from the table &ept. &ept. It never copies ! -! >hec# constraints. Tus+ 4en in te inte!;ie4 somebo&% as/s %ou 5I a;e a table 4ic as about
0hus! from the above ?uery – we can see that all the records records of the table &ept has &ept has been copied into the table temp. 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. E' 3 S,L 0 DROP TABLE test J )et )et us unders understan tand d the the dier dierenc ence e betwee between n &!op &!op t!unc t!uncate ate using using the below below shown shown e%ample!
)et us create + tables 0est1 and 0est+ as shown above.
2: 7 a g e
0he above shows shows the description description of the the table test1.
0he above gives gives the description description of the the table 0est+. 0est+. ow! let us use the ow! the T!uncate 2ue!% on Test< Test< and D!op 2ue!% on Test8 Test8 and see the dierence.
21 7 a g e
0he above 2 ?ueries show show that – 1st ?uery has the table test1 truncated. +nd ?uery ?uery – it shows shows no !o4s selecte& – selecte& – thus only the records from the table has been rd removed. 2 ?uery – it shows that the structure of the table is still present. 'nly the records will be removed. 0hus! this e'plains te t!uncate 2ue!%$
0hus from the above ?ueries we can e%plain how &!op wor#s. &!op wor#s. 1st ?uery – it drops the table. 0hus – the entire entire structure structure and and records records of the table are dropped. dropped. nd rd + and 2 ?uery – since! there is no table – select &esc ?uery &esc ?uery for test8 will test8 will throw an error. 0hus! this e'plains te &!op 2ue!%$ Qence! we have seen the dierence between &!op t!uncate ?uery. t!uncate ?uery. <1. Rec%cle Bin
TABLE DROP
RECGC LE BIN at to &o
*LASHBAC
RESTORE IT
P)RE
PERMANENTLG REMOE
2+ 7 a g e
0he functionality functionality of ecycle ecycle *in was introduced introduced in 'racle 1:= version only. only. 0hus even though the table has been dropped! we can still restore it using asbac/ comman& or we can permanently remove it using the pu!.e command. 0his concept concept of ecycle ecycle bin was was not there there in the earlier versions of 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 2?ueries – we have created a table temp which temp which copies table &ept – &ept – we see the records records of the table temp – and also chec# if the table has really been created. created. ow let us !ename temp to temp8> as temp8> as shown below!
0he above ?uery ?uery is used to rename rename a table. ow let us verify the contents of the table and chec# if it has really been modied! &ee ne%t page!
22 7 a g e
0hus the table table has been renamed renamed and its contents are are veried. ALTER J this ?uery alters / changes the structure of the table (i.e! J adding columns! removing columns! renaming columns etc . ow let us alte! the table p!o&ucts (which p!o&ucts (which we have created earlier. <# Let us a&& a ne4 column +$o,el%o to te table$
0hus! a new column has been added. )ets verify verify it with with the ?uery shown below! below!
8# No4 let us &!op te column mo&el@no (!om p!o&ucts$ 23 7 a g e
0hus! the column column has been been dropped. dropped.
0hus! we can see from the description description of the table – the column mo&el@no mo&el@no has been dropped. ># Let us !ename te column .ty to to .ty#"#il#ble.
)et us verify if it has been renamed!
NOTE : SE/ECT is neite! DML no! DDL$ It &oes not belon. to an% .!oup because it &oes not alte! an%tin.+ it ust &ispla%s te &ata as !e2ui!e& b% te use! .
DML 24 7 a g e
INSERT It inserts a record to a table. )et us observe how it is done!
0his is how we insert values into a table. All characters and alphaJnumeric characters(e% – 1::+2sdf68 must be enclosed in single ?uotes (; ; 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 o!&e!s in which a foreign #ey is referencing primary #ey!
Qere! we see that 1::1 is the same prodid as of the earlier table. &ysdate – it displays the current date set in the system .
ow! let us see the table!
Another way of inserting data into the table is shown below! 25 7 a g e
ow! let us see the table!
)PDATE PJ )PDATE PJ It updates one or more records. *o! e' 3 <# )et <# )et us update salary by increasing it by s+:: and also give commission of s1:: where empno G 6259.
ow! let us up&ate the said record as shown below!
)et us verify if the record has been updated! 26 7 a g e
0hus! the record(em record(empno pno – 6259 has been updated. 8# Inc!ease all sala!% b% <1?
)et us verify it!
DELETE 28 7 a g e
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!
0hus! we have have created created the table test.
0hus 1 row! row! ;miller< has been deleted. deleted.
0hus! the deletion deletion has been been conrmed. conrmed.
TCL Any D,) change on a table is not a permanent one. 29 7 a g e
"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. 0he DD) changes changes cannot be be undone as they are are implicitly saved. ROLLBAC It undoes the D,) changes performed on a table. )et us see in the below e%ample how !ollbac/ wor#s! wor#s!
)et us delete the employee table. "hen we perform select operation select operation on emp! we can see that all the rows have been deleted. "e now perform the !ollbac/ operation! operation!
ow let us perform the select operation! select operation!
0hus performing performing the !ollbac/ operation! operation! we can retrieve all the records which had been deleted. COMMIT It saves the D,) changes permanently to the database. 3: 7 a g e
Committin. a(te! !ollbac/ ;ice ;e!sa 4ill not a;e an% eect )et us e%plain the above statement with an e%ample!
"e can see that commit has commit has no eect after !ollbac/ operation. operation.
0hus! from from above – we we can see that !ollbac/ has has no eect after commit operation. commit operation. During an abnormal e%it – i.e! shutdown or if the &) window is closed by mouse clic# – then all the D,)
During a normal e%it – e'it J J J J all the D,) "hen we perform the following operations in the same order for a table – then I&C0! BDA0C will be committed – because A)0C is a DD) – and thus all the D,) Qere! all are rolled bac#. SAEPOINT P SAEPOINT P It is li#e a pointer (brea#Jpoint till where a D,) will be rolled bac#. E' :Insert W &ave point % H Bpdate W Delete .. ollbac# to % H W W Qere! only DC)C0C @ BDA0C are rolled bac#. I&C0 is neither rolled bac# nor committed.
Assi.nments <# C!eate te (ollo4in. tables a 0able name PJ &0BDC0& regno ( name ( 3+ 7 a g e
semester D'* hone b 0able name PJ *''& boo#no ( bname author c 0able name PJ )I*AN regno (- from students boo#no (- from boo#s D'I –date of issue D' – date of return 8# Inse!t = !eco!&s to eac o( tese tables ># Die!entiate bet4een+ a# Delete an& T!uncate b# T!uncate an& D!op c# Ca! an& a!ca! D!op an& Delete Delete and 0runcate 0runcate a Delete – deletes whichever records we want to delete from the table 0runcate 0runcate – deletes deletes all the records records whether whether we want it it or not b
Delete – can be undone 0runcate 0runcate – cannot cannot be undone.
NOTE – 0he 0he rim rimar ary y ey crea create ted d usin using g mor more than than 1 colu column mn is call called ed as co$posite pri$#ry 0ey . C% – alte! table lib A&& p!ima!% /e% "!e.no+ boo/no+ DOI# H DOI# H
CHAPTER (
S)B - ,)ERIES
A subJ?uery is also called as a nested ?uery. 32 7 a g e
S%nta' o( a sub-2ue!% Select *!om e!e
O)TER ,)ERG
" select *!om e!e # INNER ,)ERG
Qere! the inne! 2ue!% will 2ue!% will be e%ecuted rst. 0he output of inne! 2ue!% is 2ue!% is passed as input to the oute! 2ue!% 2u e!%$$ 0o 0o write a subJ?uery! subJ?uery! atleast atleast 1 common common column should should be e%isting e%isting between between the tables. *o! e' :<# List te emplo%ees 4o!/in. in 9Resea!c &epa!tment$
8# List te &epa!tment names tat a!e a;in. anal%sts
># List te emplo%ees in Resea!c an& Sales &epa!tment
33 7 a g e
Assi.nment <# List te &epa!tment names 4ic a!e a;in. salesmen salesmen in it$
8# Displa% te emplo%ees 4ose 4ose location is a;in. atleast one 9O in it$
># List te &epa!tment names tat a!e a;in. atleast < emplo%ee in it$ 34 7 a g e
# List te &epa!tment names tat a!e a;in. atleast emplo%ees in it
=# Displa% te &epa!tment names 4ic a!e a;in. atleast 8cle!/s in it
F# Disp D ispla% la% te t e 8 n& ma'imum sala!%
Q# Disp D ispla% la% te t e > !& ma'imum sala!%
# Disp D ispla% la% te t e t least sala!% 35 7 a g e
0his method is not eRcient to nd the ma%imum and minimum salary. salary. 0he limit is 2+. 0his th is not eRcient if you want to nd the 1:: ma%imum salary. e can a;e upto >8 le;els o( sub-2ue!ies onl%$ # List te &epa!tment names tat a!e a;in. no emplo%ees at all
CHAPTER
OIN 36 7 a g e
oins are used when we need to fetch the data from multiple tables T%pes o( OIN"s# >artesian Xoin (product Inner (C?ui Xoin -ull 'uter Xoin 'uter Xoin J )eft 'uter Xoin! ight 'uter Xoin! -ull &elf Xoin CARTESIAN OIN J It is based on >artesian product theory. Ca!tesian P!o&uct Teo!% in Teo!% in ,athematics states that PJ )et there be two sets – A Y1! +! 2Z @ * Y3! 4Z 0hus the >artesian >artesian product product (A* will will be! A * G Y (1!3! (1!4! (+!3! (+!4! (2!3! (2!4 Z 0hus there are 5 sets – order of A is 2 @ order of * is +. 0herefore! 0herefore! +2 G 5 is the >artesian product.
Qere! each and every record of the 1 st table will combine with each and every record of the +nd table. If a table A is having 1: records @ * is having 3 records – the >artesian $oin will return 1:3 G 3: records. *o! e'+ let us consider the following ?uery Displa% emplo%ee name alon. 4it te &epa!tment name
38 7 a g e
-rom above – we can see that the above ?uery returns 45 records – but we are e%pecting 13 records. 0his is because each and every record of employee table will be combined with each @ every record of department table. 0hus! >artesian >artesian $oin should should not be used used in real time scenarios. 0he >artesian $oin contains both correct correct and incorrect incorrect sets of data. "e have to retain the correct ones @ eliminate the incorrect ones by using the inne! oin. oin. INNER OIN Inner $oin are also called as e2uioins. e2uioins. 0hey return return the matching matching records records between between the tables. tables. In the real time scenarios! this is the most fre?uently used Xoin. *o! e'+ consider the ?uery shown below! &elect A.ename! A.sal! *.dname -rom emp A! dept * "here A.deptno G *.deptno And A.sal K +::: 'rder by A.sal H
J OIN con&ition con&ition - *ILTER *ILTER con&ition co n&ition
)et us see the output shown below!
39 7 a g e
X'I condition condition is mandatory mandatory for removing removing the >artesian >artesian output. output. )et us consider the following + scenarios shown below! Scena!io < P
A ,
R
P
B S
T
P
C
G
P
e 4ant , S
Te S,L 2ue!% 4ill be+ Select A.! Select A.! A.! *.&! >.[ -rom A! *! > "here A. G *. Numbe! o( oins 8 And A. G >. Te! Te!e( e(o! o!e+ e+ Numb Numbe! e!
o( OIN OINS S
Numb Numbe! e!
o(
Scena!io 8 A
4: 7 a g e
P
,
R
B P
,
S
P
C
G
,
e 4ant R
P
T
S
0he S,L 2ue!% is + &elect A.! A.! A.! *.&! >.[ -rom A! *! > "here A. G *. And A. G *. Numbe! o( oins > And A. G >. H
Te!e( Te!e(o!e o!e++ Numbe Numbe!! o( OIN OINS S Numb Numbe! e! o( commo common n 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 dierent column names. *o! e' 3 customerid customerid @ cid Displa% emplo%ee name+ is ob+ is &name an& is location (o! all te mana.e!s li;in. in Ne4 Go!/ o! Cica.o
ANSI st%le OINS 0his was introduc introduced ed from 'racle 'racle 9i. It is another way of writing inner $oins with a few modications. 41 7 a g e
0hus we! can can see the changes changes ! nd In the + line J !(comma has been replaced by the word ;$oin< rd In the 2 line – ;where< has been replaced with ;on< Assi.nment <# Displa Displa% % emplo%ee emplo%ee name an& is &epa!tme &epa!tment nt name (o! te emplo%ees emplo%ees 4ose 4ose name sta!ts 4it 9S
O)TER OIN It returns both matching and nonJmatching records 'uter $oin G inner $oin F nonJmatching records onJmatching records means data present in one table! but absent in another table w.r.to common columns. *o! e'+ 3: e'+ 3: is there in deptno of dept table! but not there in deptno of emp table. Displa% all te &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$ 4+ 7 a g e
si%! ri!ht oi%
si%! left oi%
si%! full oi%
A
B
<1
F
>
>
Q > A C B F1!eco!&s A I B >!eco!&s"> matcin.# A L B <1!eco!&s ">matcin. U Qnon matcin. o( A# A R B F!eco!&s ">matcin. U >non matcin. o( B# A * B <>!eco!&s ">matcin. o( A B U Qnonmatcin. o( A U >nonmatcin. o( B# Assi.nment <# Displa Displa% % emplo%ee emplo%ee name an& is &epa!tme &epa!tment nt name (o! te emplo%ees emplo%ees 4ose 4ose name sta!ts 4it 9S 42 7 a g e
8# Displa% emplo%ee name an& is &epa!tment name nam e 4o is ea!nin. ea!ni n. < st ma'imum sala!%
SEL* OIN Xoining a table table to itself is called self $oin 0he *ROM clause *ROM clause loo#s li#e this! -', emp A! emp * 'r -', -', emp emp A $oin $oin emp emp * J ANSI style -or e%! J Displa% emplo%ee name alon. 4it tei! mana.e! name
No4+ let us see o4 tis i$e te lo.ic "te abo;e 2ue!%# 4o!/s+ 43 7 a g e
Emp "B# EmpNo 1:1 1:+ 1:2 1:3 1:4
Ename &cott *la#e ing &mith Xones
M.! 1:+ 1:2 J 1:2 1:3
ow! when we give the above ?uery – in 'racle – it starts matching the ; m.!< m.!< column of emp A with A with the ;empno ; empno<< of emp b – b – we get two tables because in sel( oin – oin – a duplicate of the table re?uired is created. ow let us conside ow considerr the the V!st emplo%ee Scott – it star starts ts the the m.!i& of Scott Scott with the empno of all the recor records ds in emp B – when when two two i&s match match!! then the empno in emp B becomes the m.! of m.! of the empno in empno in emp A. A. 0hus! we can see that – m.! i& 1:+ i& 1:+ is matching with empno 1:+ empno 1:+ Bla/e in Bla/e in emp B. B. 0herefore! *la#e is the manager of &cott. &imilarly we do the same for all the other records of emp A and A and thus nd the employees and their respective managers. Displa% te emplo%ees 4o a!e .ettin. te same sala!%
Co 3 !elate& ,ue!ies : → → → →
0hey are are special type of sub – ?ueries ?ueries Qere! both outer @ inner ?ueries are interJdependent -or each @ every record of outer ?uery! the entire inner ?uery will be e%ecuted 0hey wor# on on the principles principles of both sub 3 2ue!ies OIN"s#. OIN"s# .
*o! e'+ Displa% te emplo%ee 4o is ea!nin. te i.est sala!%
44 7 a g e
0hus! if an outer ?uery column is being accessed inside the inner ?uery! then that ?uery is said to be coJrelated. )et us see the logic i.e! how we get the 1 st ma% salary PJ Emp "A# EmpNo
Ename
1:1
&cott
1:+
*la#e
1:2
ing
1:3
&mith
1:4
Xones
Sal 2:: : 3:: : 4:: : +:: : 1:: :
Emp "B# EmpNo Ename 1:1
&cott
1:+
*la#e
1:2
ing
1:3
&mith
Sal 2:: : 3:: : 4:: : +:: : 1:: :
&ince coJrelated ?ueries are a combination of Xoins and subJ?ueries. 1:4 Xones It follows the concept of Xoins and creates multiple copies of the same table. 0hen it ta#es 1 st record i.e! J *la#e – sal is 2:::. It starts comparing with the sal in the emp table! 2::: G 2::: J count starts from : – thus! : G : 2::: S 3::: – thus! : T G 1 2::: S 4::: – thus! : T G + 2::: K +::: – thus ! :T G + 2::: K 1::: – thus! : T G + if the condition becomes false! then the count increments by 1. Qere 2::: is less than 3::: @ 4:::! thus : T G +. 0hus ! *la#e does not have the highest salary. &imilarly! it does for the ne%t records! *la#e – salary of 3::: – but 3::: S 4::: – thus! : T G 1. 0his is also false. ing – salary of 4::: – it is greater than everything – thus! : G :. 0hus! ing has the highest salary. *ut the ?uery doesn !& ma'imum sala!% 3 a(te! %ou 4!ite te 2ue!% 3 te% 4ill as/ %ou to e'plain te lo.ic as to o4 it .ets te same 3 &!a4 te table an& e'plain it to tem ust as so4n abo;e$ 45 7 a g e
Assi.nment <# Displa% te least sala!% (!om te emplo%ee table$
8# Displa% top > pe!sons sala!ies (!om te emplo%ee table$
># !ite a 2ue!% to &ispla% bottom > sala!ies
# Displa% Dis pla%
46 7 a g e
=# Displa% Dis pla%
48 7 a g e
CHAPTER 4
*)NCTIONS
-unctions – it is a reJusable program that returns a value. 0here are are 8 t%pes! t%pes! re – dened • Bser dened • P!e 3 &eVne& → ='B functions → >QAA>0C functions → B,CI> functions → DA0C functions → &C>IA) functions 0hese are used both in &) and )/&). ) – rocedural rocedural )anguage (it
49 7 a g e
ow! let us study the various >QAA>0C functions. CHARACTER (unctions a Bpper b )ower c )ength *o! e' :-
In the 1st ?uery! we see something called as &ual. &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
5: 7 a g e
0his gives gives the system date.
+
2
"e use dual – when the data is not present in any of the e%isting tables. 0hen we use dual. Len.t – Len.t – it returns the length of a given string. *o! e'+ <#
51 7 a g e
8#
># Displa% all te emplo%ees 4ose name ob is a;in. e'actl% = ca!acte!s
REPLACE It replaces the old value with a new value in the given string. *o! e'+
5+ 7 a g e
Qere! a 3 is the old value to be replaced with p – which is the new value.
0his ?uery ?uery replaces all the names names which has ;A< in it with with ;*<. )et us see the output as shown below!
52 7 a g e
S)BSTR 0his is called called subst!in.. subst!in. . It e%tracts ;n< characters from %(th position of a given string. *o! e'+
53 7 a g e
Qere + "ob+ 9< + 9># – 9># – means from ob from ob – – e%tract (!om ca!acte!s. ca!acte!s . <# Displa% te emplo%ees 4ose ob sta!ts 4it 9man
8# Displa% te emplo%ees 4ose ob en&s 4it 9man
54 7 a g e
INSTR 0his is also 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
Displa% all te t e emplo%ees 4ose name is i s a;in. 9L 9 L
List te emplo%ees 4ose ob is a;in. atleast 8 As in it 55 7 a g e
CONCAT It concatenates any two values or columns. It is represented by J WW *o! e'+
N)MERIC *)NCTIONS 1 Mo& PJ Mo& PJ it returns the remainder when 1 number is divided by the other.
Displa% te emplo%ees ea!nin. o&& numbe!e& sala!ies$ 56 7 a g e
Roun& It rounds o a given number to the nearest decimal place. T!unc It trunc truncate ates s the given given number number to the given given decima decimall place place.. 0runcat runcate e does does not do any rounding. *o! e'+
Qere! ;< ;<< indicates the number of positions. DATE DATE *)NCTIONS <# S%s&ate &tands for &ystem date. It returns both date @ time! but by default – only date is displayed. 0he default format format is! && 3 mon 3 %%
8# S%stimestamp Introduced from 'racle 9i eturns date! time and timeEone.
Qere! $<111 – $<111 – gives the fraction of millisecond which #eeps changing as shown below!
58 7 a g e
co%t#i%s fr#ctio%s fr#ctio%s of # seco%, 7 In inte!;ie4 3 i( te% as/ %ou 3 7 which fu%ctio% co%t#i%s 3 ten ans4e! is 5SGSTIMESTAMP7$ OR 7how to see the syste$ ti$e 7 3
SPECIAL *)NCTIONS <# TO 3 CHAR Bsed for displaying the date in dierent formats. *o! e'+
59 7 a g e
No4+ let us see o4 to a&& = !s to te e'istin. time+
"e can see that 4 hrs has been added to the current time.
NL 6: 7 a g e
It substitutes a value for a null. *o! e'+
0he above ?uery means – if the employee has commission! commission! then add sal F comm. 0o get total salary – else add : to the sal and display total salary. DECODE It wor#s li#e ;i( ;i( 3 ten 3 else< else < statement. *o! e'+
0he above ?uery states that – in $ob! if cler# is there! replace with > – else if salesman is there! replace it with & – else replace with ;'<. Displa% emplo%ee name+ ob+ sala!% an& commission$ I( te commission is N)LL+ ten &ispla% -<11 61 7 a g e
Displa% all emplo%ees 4ose name is a;in. a; in. e'actl% < 9L in it
CHAPTER 8
NORMALIXATION 6+ 7 a g e
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 ormali orm aliEat Eation ion is a stepJ stepJby byJs Jstep tep proce process ss and and in each each step! step! we have have to perfor perform m some some activities. STEPS IN NORMALIXATION 1 1- – 1st ormal form + +- – +nd ormal form 2 2- – 2rd ormal form
8N* 0o 0o perform +-! J 0he tables have to be in 1J Qere! we identify all the complete dependencies and move them separately into dierent tables. At the end of +-! our data loo#s li#e this! ST)DENTS ego J
BOOS *oo#o J
62 7 a g e
&name &emester D'* ,ailID hone
ego J - *name Author D'I D' -ine
>N* 0he table will will have to be in in +Qere! we identify all the partial dependencies and move such columns to a separate table. ST)DENTS
BOOS
LIBRARG
ego J
*oo#o J *name Author
*oo#o J - ego J - D'I D' -ine
&name &emester D'* ,ailID hone
Disa&;anta.e o( No!mali6ation 0he only minor disadvantage disadvantage is we may have to write comple% ?ueries as we have more number of tables to be accessed. Deno!mali6ation is Deno!mali6ation is the process of combining more than 1 smaller table to form 1 bigger table is called as denormaliEation. CODD !ules ( !ules ( Die!entiates bet4een DBMS RDBMS 1 should support B)) values + should support creation of relationship between tables 2 should support DD)! D,)! 0>) 3 should support constraints li#e ! Bni?ue! >Q 4 should support ?uery techni?ues li#e sub – ?ueries! $oins! grouping etc. O!acle O!acl e i *eatu *eatu!es !es "i means inte!net# inte! net# J 0I,C&0A, datatype J &N&0I,C&0A, function J A&I style $oins J enaming a column O!acle <1. (eatu!es ". means .!i J ecycle *in ERD - Entit% Relationsip Dia.!am It is the pictorial representation of all the entities and their relationships (tables. ST)DENTS ego J &name &emester D'* ,ailID hone
63 7 a g e
ST)DENTS @ INTERNALS ego J - &id ,ar#s
BOOS *oo#o J *ame Author
LIBRARG *oo#o J - ego J - D'I D' -ine
YY THE END YYYYY
ERG IMPORTANT
64 7 a g e