1
OOrraaccllee DDaattaabbaassee AAddmmiinniissttrraattiioonn
CCoonncceeppttss && IImmpplleemmeennttaattiioonn
MMaaddee SSi...
2
Copyright © 2005 Takveen, Inc. P.O. Box 1, South River, NJ
08882. All rights reserved. No part of this publication may
b...
3
TToo AArrsshhiiaa aanndd MMaatteeeenn ……
4
5
About the Author
Mr. Abbasi is President and CEO of
Takveen, Inc. NJ, which is firm
providing information technology
rel...
6
7
Acknowledgements
First, I am really thankful to God and I always remember Him as
“Supreme Programmer”. The only One who’...
8
9
Table of Contents
Chapter 1: Visualizing Complete Oracle Environment.. 11
Chapter 2: SQL: Structured Query Language .......
10
11
CChhaapptteerr 11
Visualizing The Complete
Oracle Environment
12
13
Oracle is such a complex system that
without analogies it’s really very hard to
comprehend and grasp the concept of
Ora...
14
system, Oracle Instance gets alive and
waits for users information/data related
commands to fulfill, as it is a magnifi...
15
notebook to make things permanent
otherwise we will forget.
16
Oracle Database physically composed of
three different types of files: Control file,
Redo log files & Data files. We wi...
17
database. That’s why anything going into
the database or coming out from the
database has to be through Oracle
Instance...
18
The communication between Oracle and
user takes place in a fashion that first user
has to establish a connection with O...
19
easy to master, as it is comprised of all
full-length English words with no or very
little abbreviations. For example l...
20
Session: Each connected User with
Oracle Instance is considered as one
Session.
Instance: All users interact with Insta...
21
Users from all over can connect to Oracle
Server provided they have access. Based
on the privileges they have, users ca...
22
Instance as if they are in the same room
or on the same machine running Oracle.
Fourth, Backup & Recovery or in other
w...
23
We Did It!
In this chapter, we learnt about complete Oracle environment
architecture and also visualized it using Genie...
24
25
CChhaapptteerr 22
SQL: Structured Query
Language
26
27
Like I said in the previous chapter that
SQL is the language that we will be using
to communicate with the Instance. It...
28
SQL*Plus is basically the environment
where we write SQL or PL/SQL
commands. In other words it’s a front end
tool we us...
29
Large Organization/Enterprise :: Oracle
Once you see a database product saying
its RDBMS it means it uses SQL as a
lang...
30
will learn this stuff in great detail when
we learn about CREATE TABLE
statement.
There is one more thing that we can d...
31
TCL COMMIT, ROLLBACK,
SAVEPOINT
DCL GRANT, REVOKE
Table 2.1 0
Once we finish up with SQL you will say
to yourself, “Oh!...
32
The SELECT statement as the name says
is used to extract data from Oracle
Database. The syntax for the simplest
SELECT ...
33
Example:
SELECT *
FROM emp;
This command will display all the fields
of the table emp and all of the records.
Example:
...
34
Just like we used the greater than (>)
operator in the previous examples, there
are other SQL operator too. They are
mo...
35
the records rather than executing the
following query.
SELECT *
FROM ssa
WHERE ssn = ‘123-455-6677’;
The way we have us...
36
you want to perform some arithmetic
operation. The thing to remember over
her is, although there is some thing “order
o...
37
The output of the query will be only one
column i.e. sal and only those records
will be displayed where department
numb...
38
SELECT *
FROM emp
WHERE sal NOT IN (SELECT sal
FROM emp
WHERE deptno
= 30);
Example:
SELECT *
FROM emp
WHERE sal BETWEE...
39
(employee name) begins with “SM”.
Another variation of above query is as
follows.
ename LIKE 'SMITH_'
The output will b...
40
SQL language like all the other computer
languages comes with many pre-built
functions. These functions can be
categori...
41
Character Functions:
Following are the functions that fall under
this category.
CHR LTRIM INSTR
ASCII RTRIM INSTRB
CONC...
42
Example:
SELECT CONCAT(ename, ' is a
good boy') "Result"
FROM emp
WHERE empno = 7900;
Output:
Result
-----------------
...
43
Similarly we can use the UPPER function.
Example:
SELECT LPAD('Page 1',15,'*+')
"LPAD example"
FROM DUAL;
Output:
LPAD ...
44
Output:
Result
--------
1234567
SELECT TRIM (LEADING 0
FROM
001234567000) Result"
FROM DUAL;
Output:
Result
--------
12...
45
Example:
SELECT ename
FROM emp
WHERE SOUNDEX(ename) =
SOUNDEX('SMYTHE');
Output:
ENAME
----------
SMITH
This function a...
46
Output:
Result
---------
MAN
Similarly we can use SUBSTRB; for a
single-byte database character set,
SUBSTRB is equival...
47
SELECT INSTRB('CORPORATE
FLOOR','OR',5,2)
"Result"
FROM DUAL;
Output:
Result
--------
27
Example:
SELECT
LENGTH('SPIDER...
48
Output:
Result
--------
14
Date Functions:
Following functions fall under this
category.
ADD_MONTHS MONTHS_BETWEEN
LAST...
49
Example:
SELECT
MONTHS_BETWEEN(SYSDAT
E, hiredate) “Months of Service"
FROM DUAL;
Example:
SELECT ROUND (TO_DATE
('27-O...
50
Numeric Functions:
The following functions fall under this
category.
ABS ROUND
SIGN TRUNC
CEIL SQRT
FLOOR MOD
Example:
...
51
Output:
Result
----------
26
Example:
SELECT FLOOR(25.7) "Result"
FROM DUAL;
Output:
Result
----------
25
Example:
SELE...
52
Example:
SELECT TRUNC(25.29,1)
"Truncate"
FROM DUAL;
Output:
Truncate
----------
25.2
SELECT TRUNC(25.29,-1)
"Truncate"...
53
Example:
SELECT SQRT(25) "Square root"
FROM DUAL;
Output:
Square root
-----------
5
Conversion Functions:
The following...
54
Example:
SELECT TO_CHAR(-
10000,'L99G999D99MI') "Result"
FROM DUAL;
Output:
Result
--------------
$10,000.00-
Example:
...
55
Other Single Row Functions:
The following functions fall under this
category.
NVL
VSIZE
Example:
SELECT ename,
NVL(TO_C...
56
Example:
SELECT ename, VSIZE (ename)
"BYTES"
FROM emp
WHERE deptno = 10;
Output:
ENAME BYTES
---------- ----------
CLAR...
57
Example:
SELECT COUNT(*) "Total"
FROM emp;
Output:
Total
----------
18
Example:
SELECT MAX(sal) "Maximum"
FROM emp;
Out...
58
Query inside another query is called a
Sub-Query. Sub-Queries are mostly used
in the WHERE clause but you can use
them ...
59
This concept will get further clarified once
we start looking at the following real
world examples.
Example
SELECT *
FR...
60
Joins help in extracting data from two or
more tables based on some condition
specified in the WHERE clause. The very
i...
61
SELECT statements containing Joins
should not be confused with
“Primary/Foreign” key relationship
between the tables co...
62
TURNER works for BLAKE
ADAMS works for SCOTT
JAMES works for BLAKE
MILLER works for CLARK
Cartesian Product
If in the j...
63
In the word Equijoin, Equi comes
because we use Equal sign (=) in the join
condition. The query containing Equijoin
wil...
64
Or if you want to further reduce the
number of records in the output you can
extend the filter in the WHERE clause
just...
65
If you ask me what is the most important
thing in SQL and my response will
always be “Outer Join”. This is because
it h...
66
join is very simple. First create a Equijoin
query and then place the positive sign (+)
with the column of the table ha...
67
UPDATE statement is used to edit the
information already existing in the table.
If you want to insert a new record in t...
68
Another version,
INSERT INTO emp (empno,
ename, job, sal, comm, deptno)
VALUES (7890, 'JINKS',
'CLERK', 1.2E3, NULL, 40...
69
Before explaining how to create table I
would like to give you slight explanation
about the word “Schema”, what it is?
...
70
Figure: Organizational Chart. Showing Chief’s
Schema.
Each user we create in Oracle database is
a “Schema”. All the obj...
71
columns names which will be the names
of the columns that you want to be in the
table. While creating table you also ha...
72
is that the time is stored
as part of the date.
RAW (size)
A variable-sized field of
raw binary data. Max
2000 bytes.
L...
73
No one else beside DBA can have access
to them unless you or DBA grant access
explicitly.
Example:
CREATE TABLE emp_dep...
74
Once you have created a table you can
alter its structure using the ALTER
TABLE statement. You can add column,
modify t...
75
Example:
ALTER TABLE customers
RENAME COLUMN
limit TO amount;
One thing I would like to mention over
here, if you want ...
76
While creating tables besides mentioning
about data types of columns we can
assign constraints on each column
wherever ...
77
Similarly with UNIQUE once defined on
any column we would not be able to
insert any record in the table with a value
th...
78
Example:
ALTER TABLE dept
DROP CONSTRAINT unq_dname;
This statement will drop the constraint
only from the table altoge...
79
ways: enable NOVALIDATE or enable
VALIDATE. The former does not check
existing data for constraint violation.
ALTER TAB...
80
constraint on any column, you would not
able to insert duplicate and NULL value
i.e. each value in that will be a uniqu...
81
table already along with some data.
That’s the reason in examples above I use
the dept_test name for table otherwise I
...
82
• Keeping in focus PRIMARY
KEY constraint column value(s)
of parent table, if someone tries to
delete a record from the...
83
Developing a PRIMARY KEY and
FOREIGN KEY relationship between
two or more tables has one another name,
its called Refer...
84
Whenever you come across “Data
Integrity” just say in your mind that the
author or speaker is referring to all
differen...
85
In short all these constrains available in
Oracle helps attaining maximum data
integrity.
Another term that is used wid...
86
Like I said before, all the joins techniques
we have learnt before viz., Outer Join,
Equijoin etc. are at the query lev...
87
They think that joins statements are only
executed on tables linked through
primary and foreign key relationship but
it...
88
Besides tables that we create within our
schema, there are other logical structures
called database objects. One of tho...
89
Example:
CREATE VIEW emp_view AS
SELECT *
FROM employees
WHERE department_id = 20;
Dropping a view will not drop the
un...
90
column of a table, implicit. We call it an
implicit index because you haven’t
executed any index creation statement but...
91
Each time you create a index on any
column of a table Oracle creates a
implicit table that can help it in locating
the ...
92
Example:
ALTER INDEX m1_idx
RENAME TO m2_idx;
This statement will rename the index to
m2_idx. There are lot other stuff...
93
new value from this sequence it will give
you a number 1 higher than the previous
one. Maximum value would be 99999
and...
94
using the ALTER SEQUENCE
statement.
Example:
DROP SEQUENCE emp_seq;
We can also drop a sequence from the
database using...
95
Example:
CREATE PUBLIC SYNONYM
employees
FOR
hr.employees@sales;
Public synonym are accessible to all the
users provide...
96
To install Oracle software on the machine
you have to be the member of OS
(Operating System) SYSOPER or
SYSDBA group. O...
97
To create a new user (schema) you should
login to Oracle Instance using one of the
DBA’s account and then user the
CREA...
98
IDENTIFIED EXTERNALLY;
Example:
ALTER USER sophia
IDENTIFIED BY black123;
Or,
ALTER USER sophia
DEFAULT TABLESPACE
hr_d...
99
a month change of business rule comes
up and its described that those 35 HR
would only be having SELECT privilege
on Pa...
100
application.
ALTER Table, Sequence
DELETE Table, View
INDEX Table
INSERT Table, View
READ Dictionary
REFERENCE Table
S...
101
INSERT ANY TABLE
LOCK ANY TABLE
CREATE SEQUENCE
CREATE ANY
SEQUENCE
ALTER ANY
SEQUENCE
DROP ANY
SEQUENCE
Sequence
SELE...
102
Besides these are system privileges for
PL/SQL functionalities like CREATE
PROCEDURE, CREATE ANY
PROCEDURE, EXECUTE AN...
103
In this example we have first created the
role hr_emps and next we assign certain
privileges to it and finally we have...
104
Example:
CREATE USER marion
IDENTIFIED mateena
PROFILE paramod;
Or,
ALTER USER marion
PROFILE paramod;
Here mateena is...
105
Or,
CREATE PROFILE hr_dept
LIMIT
FAILED_LOGIN_ATTEMPTS 5;
I think this is self-explanatory. Besides
these, the other r...
106
We Did It!
In this chapter we basically learnt the “grammar” of communication
language (SQL); language that we will us...
107
CChhaapptteerr 33
Oracle Database Concepts
• Physical Architecture
• Logical Architecture
• Relationship between Physi...
108
109
Like I said before, the complete Oracle
system consists of two things viz., Oracle
Instance and Oracle Database. To be...
110
questions like this and many more will
get resolved.
Oracle database has a logical architecture
as well as physical ar...
111
We can look at Oracle Database through
two angles viz., logically and physically.
We will talk about logical architect...
112
If you keep inserting records in your
tables using the INSERT statement, the
size of your control file will not change...
113
called redo log file group. Redo log files
gets utilized in a circular fashion i.e.
when Oracle Instance finishes writ...
114
oracle system, the first thing that gets
erected is Oracle Instance. How the
memory structure would be for that
instan...
115
Physically the data inside the database
resides in the data files located on hard
drives and if you want you can copy ...
116
composed of Extents and What are
Extents? Each extent is a group of
contiguous DB Blocks. Now what are DB
Blocks? A DB...
117
This is a side by side relationship
development between logical and
physical architecture of Oracle database.
The data...
118
be more than the Operating System
maximum files size. But you can always
add another data file to the tablespace
using...
119
When we talk about the relationship
between physical and logical architecture
of oracle database, we are actually talk...
120
Each tablespace can have one or more
data files associated with it but each data
file can never belong to more than on...
121
With this slide you can easily visualize
the physical and logical architecture of
Oracle Database. For some people thi...
122
is distributed among two data files.
Tablespace 2 is comprised of only one
data file so all the objects created by the...
123
Just a slight revision, we said the
database is comprised of five different
types of files and we have learnt the
purp...
124
Whatever data changes are happening in
the database, all gets written to the Redo
Log files. In other words you can sa...
125
We Did It!
In this chapter we have learnt about “physical” as well as “logical”
architecture about Oracle Database. Ph...
126
127
CChhaapptteerr 44
Oracle Instance Concepts
128
129
Oracle system or more commonly we use
the word Oracle server or Oracle
Database, whatever name you use, just
keep one ...
130
The thing I want you to memorize if you
haven’t memorize it yet, the definition of
Oracle Instance i.e. the background...
131
Oracle Instance can be defined as, the
background processes and memory
architecture constitute the instance. There
are...
132
The last thing I have discussed in this
article is, how to optimize the working of
human brain and is available at
(ht...
133
last met 15 or 25
years ago. You saw
him and he saw you
in a shopping mall.
Both of you will stop
and say in
astonishm...
134
RAM inside the computer if we already
have hard drives? Its because the speed
with which Microprocessor (CPU)
communic...
135
Oracle System Human System
Oracle Instance +
Oracle Database
Human Brain +
Note Books
(Papers etc.)
Oracle Instance is...
136
By saying, memory architecture of Oracle
Instance we mean how RAM is utilized
by Oracle Instance or more precisely par...
137
Similarly Oracle utilizes RAM too for the
same purpose what other programs does
i.e. speedy processing. How that RAM i...
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Oracle db ebook
Upcoming SlideShare
Loading in …5
×

Oracle db ebook

1,209 views

Published on

Published in: Technology, News & Politics
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,209
On SlideShare
0
From Embeds
0
Number of Embeds
50
Actions
Shares
0
Downloads
64
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Oracle db ebook

  1. 1. 1 OOrraaccllee DDaattaabbaassee AAddmmiinniissttrraattiioonn CCoonncceeppttss && IImmpplleemmeennttaattiioonn MMaaddee SSiimmppllee BBYY AASSIIMM AABBBBAASSII ..::||::.. TTaakkvveeeenn,, IInncc.. SSoouutthh RRiivveerr,, NNJJ
  2. 2. 2 Copyright © 2005 Takveen, Inc. P.O. Box 1, South River, NJ 08882. All rights reserved. No part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photography, magnetic, or other record, without the prior agreement and written permission of the publisher and author. ISBN: 0-9770739-0-4 Takveen and the Takveen logo are either registered trademarks or trademarks of Takveen, Inc. in the United States and/or other countries. The author and publisher have made their best effort to prepare this book, and the content is based upon final release software whenever possible. Portion of the manuscript may be based upon pre-release versions supplied by the software manufacturer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept no liability of ANY KIND including but no limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of ANY KIND caused or alleged to be caused directly or indirectly from this book. Manufactured in the United States of America.
  3. 3. 3 TToo AArrsshhiiaa aanndd MMaatteeeenn ……
  4. 4. 4
  5. 5. 5 About the Author Mr. Abbasi is President and CEO of Takveen, Inc. NJ, which is firm providing information technology related ‘Optimal Solutions’ to industry. He is also attached with three top-notch computer schools of NJ teaching Oracle Database Administration in Unix/Windows Server environments. Before coming to NJ, he used to teach Oracle in heart of NC, Raleigh while working as Chief Technologist with a business solutions development firm. Mr. Abbasi has been attached intensely with the IT field for past 13 years and has written dozens of softwares and tons of code from programming microcontrollers using Assembly language to writing 3-tier multi-language web applications. He did B.Sc. Electrical Engineering from University of Engineering & Technology, Lahore, Pakistan (www.uet.edu.pk). He is Oracle Certified Professional Database Administrator (OCP), Microsoft Certified Professional (VB) and lots of other computer certifications. Besides certifications, he has lots of publications and has filed 1 patent with United States Patent & Trade Mark Office. When asked Mr. Abbasi, he said that it all erupted with a saying of my Advanced Engineering Mathematics professor, “Think yourself ….”
  6. 6. 6
  7. 7. 7 Acknowledgements First, I am really thankful to God and I always remember Him as “Supreme Programmer”. The only One who’s every release is a final release and no upgrades, version releases or service packs after words. I salute your sea of computational and engineering skills my Lord and your graciousness for letting me have a droplet from it. I really want to thank my father and mother for their wonderful support. Although my father is no more living but his exceptional sacrifices will never be forgotten … I like to thank my wife Arshia and son Mateen for their encouragement to let me work on this book even during the time which I should had spent with them. I also want to thank my brother Atif Abbasi for providing support, suggestions & technical help whenever I needed. My special thanks for Maryann Master, Margorie Michele, Daisy Maxwell, Carol Taylor, Baber & Assiya Wasti and William Branch. Finally, I am thankful to all the wonderful instructors, professors, scholars, students and friends I had for their support and encouragement.
  8. 8. 8
  9. 9. 9 Table of Contents Chapter 1: Visualizing Complete Oracle Environment.. 11 Chapter 2: SQL: Structured Query Language ................ 25 Chapter 3: Oracle Database Concepts ......................... 107 Chapter 4: Oracle Instance Concepts ........................... 127 Chapter 5: Oracle In Action ......................................... 147 Chapter 6: Steps Of Implementation (Oracle Sys.) ..... 161 Chapter 7: Oracle Database Design ............................. 179 Chapter 8: Oracle Network Administration ................. 231 Chapter 9: Oracle Database Management ................... 267 Chapter 10: Oracle Backup & Recovery ..................... 291 Chapter 11: Oracle Performance Tuning ..................... 329
  10. 10. 10
  11. 11. 11 CChhaapptteerr 11 Visualizing The Complete Oracle Environment
  12. 12. 12
  13. 13. 13 Oracle is such a complex system that without analogies it’s really very hard to comprehend and grasp the concept of Oracle architecture and its working. If you are new to Oracle or an experienced DBA, understanding of concepts is the key to success not only in Oracle Certifications but in real world. Also once you understand the concepts then there is nothing left for cramming. Oracle System is basically divided into two things namely Oracle Instance and Oracle Database. We have taken the analogy of a Genie (Ghost/Djin): just like the one you might have seen in the movie/story of “Aladdin & the Magic Lamp”. When Aladdin rubbed the lamp; Genie became available and fulfilled all his commands. Similarly when you double click “Oracle” icon in your Key Concepts 1) Oracle Server is comprised of two things o Instance o Database 2) Anything that is going into the database or coming out of the database has to be through Oracle Instance. 3) To communicate with Oracle Instance we need to learn SQL.
  14. 14. 14 system, Oracle Instance gets alive and waits for users information/data related commands to fulfill, as it is a magnificent “Data Management Genie”. Oracle Instance is something with which users interact in terms of storing and retrieving information. There are no physical files like in case of COBOL or MS Access for user database interaction. Anything that is going into the database or coming out of the database has to be through Oracle Instance and to communicate with Oracle Instance we need to learn Genie’s language: SQL. It stands for Structured Query Language and pronounced as See-Qual. Just imagine as if Aladdin is from France and knows only “French” language but when he came to US he found this magic lamp. When he rubbed the lamp Genie came out. Now even though Genie wants to help Aladdin and fulfill his commands but he cannot do anything due to language barrier. Aladdin has only two options either to teach Genie “French” or teach himself “English”. As Aladdin is depending on Genie to gets his commands fulfilled so ethically it’s his job to go to school or buy a book entitled “English” or in Oracle Instance case “SQL”. So after learning SQL, Aladdin will be fully capable to command the Instance. The Oracle Database is basically Genie’s area to write information and to make the changes permanent on the hard disk. Just like we can remember something in our brain but when it comes to remembering lots of stuff we have to take the help of
  15. 15. 15 notebook to make things permanent otherwise we will forget.
  16. 16. 16 Oracle Database physically composed of three different types of files: Control file, Redo log files & Data files. We will be discussing each of these files in great detail in the chapters ahead but just for a brief introduction, Oracle Instance writes the information about the structure (tables’, views’ etc. structure but not data) of the database in Control file. All the changes (data related like Update, Inserts etc) gets written to Redo log files. Data files are basically the files that contain users data. If user wants to write some information into the database, Oracle instance will actually make that change permanent by writing it to the data files. The Oracle Database is encrypted or in other words we cannot read the data files through any text editor like MS Word. Only Oracle Server knows how to Decrypt the information residing in the Key Concepts 1) Oracle Database is encrypted and we cannot read it through any Text Editor like MS Word. 2) SQL commands are used to store and retrieve information.
  17. 17. 17 database. That’s why anything going into the database or coming out from the database has to be through Oracle Instance. Each connected user sends requests in the form of SQL commands to Oracle Instance to retrieve information from Oracle Database or to store information into the database.
  18. 18. 18 The communication between Oracle and user takes place in a fashion that first user has to establish a connection with Oracle server or more precisely oracle instance by providing his/her credentials (Username and password). Once verified Oracle accepts the connection otherwise the connection request will get rejected. In Oracle world each connected user with oracle server is considered as session. If there are three connected users with oracle server, we can say that there are three sessions with oracle server. If one person logs off then the number of sessions drops to two. The connected users use SQL commands like SELECT, UPDATE, INSERT etc. (which we will learn in detail in chapter ahead) to communicate with Oracle server. SQL commands are very simple and very Key Concepts 1) Each connected user with Oracle Instance is considered as “Session” 2) Never forget the concept of following three terms o Instance o Database o Session 3) Following analogies help you in building concept Instance = Genie Database = Notebook Session = Aladdin (or connected Users
  19. 19. 19 easy to master, as it is comprised of all full-length English words with no or very little abbreviations. For example lets have a look on following SQL command SELECT name, phone FROM address_book; Once Oracle Instance will receive this command, it will retrieve all the “name” and “phone” information from the address_book table and send it to the user who had asked for it. If there are 1000 records or rows in that table; all of them gets sent to user computer. If the user wants to see all those people having name beginning with letter “A”. To make this to happen we have to use the “WHERE” clause of SELECT Statement. SELECT name, phone FROM address_book WHERE name LIKE “A*”; Thus you have seen how simple the SQL language is. Let me put it this way anyone who can read and understand English, can learn SQL with very small efforts. Understanding of Instance, Database and Session are considered as the foundation. You should not forget the concept and meaning of these three terms as we are going to build the Oracle Architecture concept over it and we will be using these terms in the upcoming discussion. So let me define these three terms one by one.
  20. 20. 20 Session: Each connected User with Oracle Instance is considered as one Session. Instance: All users interact with Instance to retrieve or store information. Database: Is like the notebook where instance writes the information and is encrypted.
  21. 21. 21 Users from all over can connect to Oracle Server provided they have access. Based on the privileges they have, users can store, retrieve information, and create new tables etc. from any part of the world whether they are on wired network or wireless network. The slide above shows the complete Oracle Environment. Now we can line up stuff that we will be learning. First we will learn about SQL or in other words how to communicate with Oracle Instance. Second, Oracle Database Administration (DBA) or in other words how to create/manage Oracle Instance as well as Oracle Database. Third, Oracle Network Administration or in other words how to develop/manage Oracle Network so that users from all parts of the world can communicate with Oracle Key Concepts 1) Users can connect to Oracle server independent of their location. 2) Oracle Server: When we talk about Oracle Instance & Oracle Database collectively we use the word Oracle Server. 3) Steps to Master Oracle o SQL o DBA o Network Admin o Bkup & Recov. o Performance Tuning
  22. 22. 22 Instance as if they are in the same room or on the same machine running Oracle. Fourth, Backup & Recovery or in other words how to backup Oracle Database and recover information in case of all different types of failure and lastly, Oracle Performance Tuning or in other words once we have Oracle system up and running, how to monitor & enhance its performance in order to get maximum efficiency.
  23. 23. 23 We Did It! In this chapter, we learnt about complete Oracle environment architecture and also visualized it using Genie and Genie’s Notebook analogy. Oracle Instance ~ Genie Oracle Database ~ Genie’s Notebook Connected users with Oracle Instance (Genie) are called sessions. Oracle Data files are encrypted and only Oracle Instance knows how to decrypt it. People from all over the world can connect to Oracle Instance and retrieve/store information from Oracle Instance. To communicate with Oracle Instance, we need to learn Genie’s language i.e. SQL
  24. 24. 24
  25. 25. 25 CChhaapptteerr 22 SQL: Structured Query Language
  26. 26. 26
  27. 27. 27 Like I said in the previous chapter that SQL is the language that we will be using to communicate with the Instance. It’s just like I am right now using “English” as a way of communication because you guys understand it. Similarly to communicate with Oracle Instance we use SQL (Seeqal). Before we proceed with the language I want to clarify three terms that is used wide and sometimes few people gets confused. These are SQL, PL/SQL and SQL*Plus. SQL as I already told you are the language to communicate with Oracle Instance whereas PL/SQL is the superset of SQL i.e. we use PL/SQL instead of SQL when our target/goal requires multiple SQL commands to be executed based on certain logic, event or condition then we take the benefit of this language. Key Concepts 1) Understanding the difference between three terms: SQL, PL/SQL, SQL*Plus 2) Horizontal goes the Records/Rows and vertical goes the Fields/Columns. 3) We will write SQL commands in SQL*Plus software.
  28. 28. 28 SQL*Plus is basically the environment where we write SQL or PL/SQL commands. In other words it’s a front end tool we use to communicate with Oracle Instance. There are lots of SQL front-end tools available but it’s the one that gets installed once you install Oracle whether its 8i or 9i or 10g. In Oracle 9i and 10g they have introduced iSQL*Plus which is a web-interface for executing SQL and Pl/SQL code. If you are good in programming you can develop one on your own using Visual Basic or Visual C++ or even JAVA. Next thing I would to discuss over here is few important concepts about RDBMS or Relational Database Management System. There is a long old history about “RDBMS standard” but it all started with Dr. E.F. Codd in 1969. Making a long story short there are lot other database beside Oracle that claim to be RDBMS e.g. MS SQL Server, MS Access, MySQL etc. If I want to create my own database product named “Takveen” and I have big solid team of programmers; we all first have to read and understand that RDBMS standard and then we can start writing the code otherwise we cannot claim in the market that it’s a RDBMS database. The way I categorize the RDBMS database products available in the market keeping in mind their strength to handle data & handle concurrent user requests is as follows. Small Companies :: MS Access Mid Size Companies :: MS SQL Server
  29. 29. 29 Large Organization/Enterprise :: Oracle Once you see a database product saying its RDBMS it means it uses SQL as a language and Data inside it is written always in table form i.e. rows/records & columns/fields. Moreover there may or may not be relationship in-between those tables. Each of the RDBMS Database manufacture has their own version of SQL. But they all are more than 90% alike. If it takes you to learn Oracle SQL in a week after that you can learn SQL for MS SQL server in less than an hour. There is one SQL standard defined by ANSI (American National Standard Institute) and is called ANSI SQL. Nearly all RDBMS database manufacture incorporates this ANSI SQL and then builds a layer of some new stuff on top of it to provide added functionality in the language. The SQL that we will be learning in this book will be more precisely Oracle SQL. Concept of arranging the data in the form of table is very simple. We have been doing it on the papers for years and the concept is still the same. There are two terms that we will be using a lot. One is called “Record(s)” or “Row(s)” and other one is called “Field(s)” or “Column(s)”. Like shown in the figure below, there are 5 records in the table and 3 fields. Each field in Oracle table has been assigned a “Data type”. While creating a table if you have assigned Last Name field character data type, you cannot insert date in it or you cannot insert numeric value in it. We
  30. 30. 30 will learn this stuff in great detail when we learn about CREATE TABLE statement. There is one more thing that we can do with fields, we can assign constraints to them e.g. If you assign UNIQUE constraint to any column then you would not be able to insert any value in it which is already their in the same column. Constraints help in maintaining the data integrity of the system. Figure 2.1 Table Showing Records/Rows And Fields/Columns SQL is nothing but a set of command statements and are categorized into following five groups viz., DQL: Data Query Language, DML: Data Manipulation Language, DDL: Data Definition Language, TCL: Transaction Control Language, DCL: Data Control Language. The commands following in each of these categories are shown in the following table. DQL SELECT DML DELETE, INSERT, UPDATE DDL CREATE, DROP, TRUNCATE, ALTER
  31. 31. 31 TCL COMMIT, ROLLBACK, SAVEPOINT DCL GRANT, REVOKE Table 2.1 0 Once we finish up with SQL you will say to yourself, “Oh! That was all”. Lets that the following example. SELECT name, phone, city FROM address_book; Anyone knowing English language can easily imagine what the output of this statement would look like. The output will be three fields with all the records from address_book table. So you completed your first SQL statement.
  32. 32. 32 The SELECT statement as the name says is used to extract data from Oracle Database. The syntax for the simplest SELECT statement is as follows. SELECT column_name1, column_name2, … FROM table_name1; The examples we are going to present over here are only for you to understand and go through the whole chapter. The actual time of implementation comes after we teach you how to install Oracle software and how to login using SQL*Plus then if you like you can come back to this chapter and start implanting those statements. So following are some examples Key Concepts 1) SELECT statement used for retrieval of information from Oracle Database through Oracle Instance. 2) Oracle Instance receives these commands from connected users.
  33. 33. 33 Example: SELECT * FROM emp; This command will display all the fields of the table emp and all of the records. Example: SELECT ename, sal FROM emp WHERE sal > 2000; The result of this statement will be only two columns of emp table and only those records where salary is greater than 2000. Example: SELECT ename, salary FROM emp WHERE sal > 2000 ORDER BY ename; The output of this statement will be exactly the same as the one above except that the output will be sorted based on ename column.
  34. 34. 34 Just like we used the greater than (>) operator in the previous examples, there are other SQL operator too. They are mostly used in the WHERE clause to filter certain records or to reduce the number of records in the output. “Reduce the number of records”, what this means? Why we need to reduce the number of records in the output. Imagine a SSA (Social Security Administration) office. The database they are having must be having millions of records in it. You can well realize the drawback if someone would execute the following statement. SELECT * FROM ssa; One other aspect is, why to look for something you don’t need. If you are looking one person’s information why to execute the query that will give you all Key Concepts 1) Operators help in filtering the number of records 2) Use parenthesis rather than utilizing “order of precedence” among operators.
  35. 35. 35 the records rather than executing the following query. SELECT * FROM ssa WHERE ssn = ‘123-455-6677’; The way we have used the “greater than” operator on the same lines we can use the “less than” (<), “equal to” (=), “less than equal to” (<=) & “greater than equal to” (>=). ANY/SOME and ALL can be best understood by first looking at their respective real world example. Example: SELECT * FROM emp WHERE sal = ANY (SELECT sal FROM emp WHERE deptno = 30); Compares a value to each value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. Evaluates to FALSE if the query returns no rows. Example: SELECT * FROM emp WHERE sal >= ALL ( 1400, 3000); Compares a value to every value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. Evaluates to TRUE if the query returns no rows. The next category of SQL operator is called Arithmetic operators and used if
  36. 36. 36 you want to perform some arithmetic operation. The thing to remember over her is, although there is some thing “order of precedence” but its always recommended to use parenthesis whenever your statement involves two or more arithmetic operators. Parenthesis over rides the “order of precedence”. Now the question is, what is order of precedence? It means if you are not using any parenthesis and you calculation involves two or more arithmetic operators so which operations should Oracle perform first. Multiplication and Division will be preferred over Subtraction and Addition. Moving from left to right, if Multiplication comes first than it will be handled first otherwise division, it applies to subtraction and addition too. Example: SELECT ename, sal, sal + sal*5/100 “Next Year Sal” FROM emp; Logical Operators and the operators in the Other category can be best understood by looking at their respective real world example. Example: SELECT sal FROM emp WHERE deptno = 30 AND sal > 2000;
  37. 37. 37 The output of the query will be only one column i.e. sal and only those records will be displayed where department number is 30 and the salary is greater than 2000. So when you use AND operator it means both conditions needs to satisfy for the record to appear in the output but in case of OR, either first condition needs to be true or the second one e.g. SELECT sal FROM emp WHERE deptno = 30 OR sal > 2000; Example: SELECT * FROM emp WHERE job IN ('CLERK','ANALYST'); The output of the query will be all the coulums of emp table but only those records where job column contains either “CLERK” or “ANALYST”. You can also use IN operator with as follows. SELECT * FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30); By having NOT before IN can complete invert the results like in the following example. Such types of queries fall under the category called “Sub-Queries” which we will discuss in the article ahead in this chapter. There is a special technique to interpret them.
  38. 38. 38 SELECT * FROM emp WHERE sal NOT IN (SELECT sal FROM emp WHERE deptno = 30); Example: SELECT * FROM emp WHERE sal BETWEEN 2000 AND 3000; Only those records will be displayed where the salary is between 2000 and 3000 including both 2000 and 3000. Example: SELECT ename, deptno FROM dept WHERE EXISTS (SELECT * FROM emp WHERE dept.deptno = emp.deptno); TRUE if a sub-query returns at least one row. In other words the output will be two columns from dept table, all the records only if the query after EXISTS results in at least one record. Example: SELECT sal FROM emp WHERE ename LIKE 'SM%'; The output will be only those salaries from emp (employee) table where ename
  39. 39. 39 (employee name) begins with “SM”. Another variation of above query is as follows. ename LIKE 'SMITH_' The output will be only those records where ename begins with “SMITH” and there should not be more than one character after it. Example: SELECT ename, deptno FROM emp WHERE comm IS NULL; The output will be ename and deptno but only those records where comm field has NULL value. NULL is a special value and just keep in mind that its not Zero. It can be visualized as empty field occupying zero byte.
  40. 40. 40 SQL language like all the other computer languages comes with many pre-built functions. These functions can be categorized into two major groups. One is called “Single Row” functions and the other one is called “Group” functions. Single Row function as the name says gets implemented on single records whereas Group functions get implemented on the multiple records. These functions will get clarified in your mind once we start discussing one by one. Single Row Functions Single Row functions are further subdivided into five categories viz., Character, Data, Numeric, Conversion & other functions. First we will start with Character Functions or more precisely “Single Row Character Functions.” Key Concepts 1) Single Row functions will result in same number of records as were there in the output of the query without them e.g. TOCHAR, INITCAP etc. 2) Group functions will usually result in lesser number of records as were there in the output of the query without them e.g., AVG, SUM, COUNT etc.
  41. 41. 41 Character Functions: Following are the functions that fall under this category. CHR LTRIM INSTR ASCII RTRIM INSTRB CONCAT TRIM LENGTH INITCAP REPLACE LENGTHB LOWER SOUNDEX UPPER SUBSTR LPAD SUBSTRB RPAD Example: SELECT CHR(67)||CHR(65)||CHR(84) "Pet" FROM DUAL; Output: Pet --- CAT Example: SELECT ASCII('Q') FROM DUAL; Output: ASCII('Q') ---------- 81
  42. 42. 42 Example: SELECT CONCAT(ename, ' is a good boy') "Result" FROM emp WHERE empno = 7900; Output: Result ----------------- JAMES is a good boy Example: SELECT INITCAP('the king') "Capitals" FROM DUAL; Output: Capitals --------- The King Example: SELECT LOWER('THE KING') "Lowercase" FROM DUAL; Output: Lowercase ------------- the king
  43. 43. 43 Similarly we can use the UPPER function. Example: SELECT LPAD('Page 1',15,'*+') "LPAD example" FROM DUAL; Output: LPAD example --------------- *+*+*+*+*Page 1 Similarly we can use RPAD. Example: SELECT LTRIM('121SPIDERMAN','12') "Result" FROM DUAL; Output: Result -------- SPIDERMAN Similarly we can use RTRIM. Example: SELECT TRIM (0 FROM 001234567000) Result" FROM DUAL;
  44. 44. 44 Output: Result -------- 1234567 SELECT TRIM (LEADING 0 FROM 001234567000) Result" FROM DUAL; Output: Result -------- 1234567000 Similarly we can replace LEADING with TRAILING to omit trailing zeros in 001234567000 and the output will then be 001234567. Example: SELECT REPLACE('KING KONG','KI','HO') Result" FROM DUAL; Output: Changes -------------- HONG KONG
  45. 45. 45 Example: SELECT ename FROM emp WHERE SOUNDEX(ename) = SOUNDEX('SMYTHE'); Output: ENAME ---------- SMITH This function allows you to compare words that are spelled differently, but sound alike in English. You must have noticed that if you do a search in google (www.google.com) using wrong spelling e.g. as shown in the following figure I made a wrong spelled word “Neus” search on google and it came up with, “Did you mean News?”. That is basically the beauty of this function. Example: SELECT SUBSTR('SPIDERMAN',7,3) "Result" FROM DUAL;
  46. 46. 46 Output: Result --------- MAN Similarly we can use SUBSTRB; for a single-byte database character set, SUBSTRB is equivalent to SUBSTR. Floating-point numbers passed as arguments to SUBSTRB are automatically converted to integers. Assume a double- byte database character set: SELECT SUBSTRB(' SPIDERMAN',7,4.3) "Result" FROM DUAL; Output: Result -------- DE Example: SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL; Output: Result ---------- 14 Similarly we can use INSTRB; for a single-byte database character set, INSTRB is equivalent to INSTR. Lets suppose a double-byte database character set.
  47. 47. 47 SELECT INSTRB('CORPORATE FLOOR','OR',5,2) "Result" FROM DUAL; Output: Result -------- 27 Example: SELECT LENGTH('SPIDERMAN') "Result" FROM DUAL; Output: Result -------- 9 Similarly we can use LENGTHB; for a single-byte database character set, LENGTHB is equivalent to LENGTH. Lets suppose a double-byte database character set. SELECT LENGTHB ('SPIDERMAN') "Result" FROM DUAL;
  48. 48. 48 Output: Result -------- 14 Date Functions: Following functions fall under this category. ADD_MONTHS MONTHS_BETWEEN LAST_DAY ROUND SYSDATE TRUNC Example: SELECT ADD_MONTHS(hiredate,1) FROM emp WHERE ename = 'SMITH'; Example: SELECT SYSDATE, LAST_DAY(SYSDATE) "Last", LAST_DAY(SYSDATE) - SYSDATE "Days Left" FROM DUAL; Output: SYSDATE Last Days Left --------- --------- ---------- 23-OCT-97 31-OCT-97 8
  49. 49. 49 Example: SELECT MONTHS_BETWEEN(SYSDAT E, hiredate) “Months of Service" FROM DUAL; Example: SELECT ROUND (TO_DATE ('27-OCT-92'),'YEAR') "New Year" FROM DUAL; Output: New Year --------- 01-JAN-93 Example: SELECT TRUNC(TO_DATE('27- OCT-92','DD-MON-YY'), 'YEAR') "New Year" FROM DUAL; Output: New Year --------- 01-JAN-92
  50. 50. 50 Numeric Functions: The following functions fall under this category. ABS ROUND SIGN TRUNC CEIL SQRT FLOOR MOD Example: SELECT ABS(-25) "Result" FROM DUAL; Output: Result ---------- 25 Example: SELECT SIGN(-15) "Result" FROM DUAL; Output: Result ---------- -1 Example: SELECT CEIL(25.7) "Result" FROM DUAL;
  51. 51. 51 Output: Result ---------- 26 Example: SELECT FLOOR(25.7) "Result" FROM DUAL; Output: Result ---------- 25 Example: SELECT ROUND(25.29,1) "Round" FROM DUAL; Output: Round ---------- 25.3 SELECT ROUND(25.29,-1) "Round" FROM DUAL; Output: Round ---------- 30
  52. 52. 52 Example: SELECT TRUNC(25.29,1) "Truncate" FROM DUAL; Output: Truncate ---------- 25.2 SELECT TRUNC(25.29,-1) "Truncate" FROM DUAL; Output: Truncate ---------- 20 -1 will truncate (make zero) first digit left of the decimal point of 25.29 Example: SELECT MOD(11,4) "Modulus" FROM DUAL; Output: Modulus ---------- 3
  53. 53. 53 Example: SELECT SQRT(25) "Square root" FROM DUAL; Output: Square root ----------- 5 Conversion Functions: The following functions fall under this category TO_CHAR TO_DATE TO_NUMBER Example: SELECT TO_CHAR(HIREDATE, 'Month DD, YYYY') "Result" FROM emp WHERE ename = 'BLAKE'; Output: Result ------------------ May 01, 1981
  54. 54. 54 Example: SELECT TO_CHAR(- 10000,'L99G999D99MI') "Result" FROM DUAL; Output: Result -------------- $10,000.00- Example: SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.', 'NLS_DATE_LANGUAGE = American') FROM DUAL; Example: SELECT TO_NUMBER('$10,000.00-', 'L99G999D99MI') "Result" FROM DUAL; Output: Result --------- -1000
  55. 55. 55 Other Single Row Functions: The following functions fall under this category. NVL VSIZE Example: SELECT ename, NVL(TO_CHAR(COMM), 'NOT APPLICABLE') "COMMISSION" FROM emp WHERE deptno = 30; Output: ENAME COMMISSION ---------- ------------------------- ALLEN 300 WARD 500 MARTIN 1400 BLAKE NOT APPLICABLE TURNER 0 JAMES NOT APPLICABLE
  56. 56. 56 Example: SELECT ename, VSIZE (ename) "BYTES" FROM emp WHERE deptno = 10; Output: ENAME BYTES ---------- ---------- CLARK 5 KING 4 MILLER 6 Group Functions A group function as the same says gets implemented on more than one record within a column. They can be better understood by looking at their real world examples. There are five very important group functions AVG COUNT MAX MIN SUM Example: SELECT AVG(sal) "Average" FROM emp; Output: Average ---------- 2077.21429
  57. 57. 57 Example: SELECT COUNT(*) "Total" FROM emp; Output: Total ---------- 18 Example: SELECT MAX(sal) "Maximum" FROM emp; Output: Maximum ---------- 5000 On the same line we can find out minimum value using the MIN group function. Example: SELECT SUM(sal) "Total" FROM emp; Output: Total ---------- 29081
  58. 58. 58 Query inside another query is called a Sub-Query. Sub-Queries are mostly used in the WHERE clause but you can use them in the FROM or even in the SELECT clause. The important thing is to understand the technique, how to interpret such queries or in other words how Oracle instance will interpret such queries. The technique is, start from the bottom query first or the one within parenthesis, imagine what’s its output will be, replace that query with its imagined output and move to the next higher one. Keep on doing this unless you end up with the main query. Key Concepts 1) Technique for Sub- Query Interpretation: Start from the bottom query first, imagine what its output is would be, replace that query with its imagined output and move to the next higher one.
  59. 59. 59 This concept will get further clarified once we start looking at the following real world examples. Example SELECT * FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30); Based of the technique that we have defined, we will first imagine the output of the bottom most query. It will give us all the salary values from department number 30. Now replace this query with those imagined values. Even if multiple values appear as a result of bottom query we can still use them with IN operator. But the following query will result in an error if the bottom SELECT statement results in multiple values. SELECT * FROM emp WHERE sal = (SELECT sal FROM emp WHERE deptno = 30); So be careful when you use operators with sub-queries. The syntax of the function, clause or Operator should justify under all circumstances then you are allowed to use sub-queries wherever you like.
  60. 60. 60 Joins help in extracting data from two or more tables based on some condition specified in the WHERE clause. The very important point to note over here is that Joins are only at the query level. It means the output that you see as a result of statement containing any form of “Join”, is only for that instance and its in the volatile memory (RAM). There are following different kinds of Joins and each having its own application. Out of these, two are having extremely high importance viz., Equi-Join and Outer-Join. Self Joins Cartesian Products Equijoins Outer Joins Key Concepts 1) Sole purpose of Join statement is to extract data from more than one table based on some condition specified in the WHERE clause. 2) Primary/Foreign key relationship needs not to be present among tables for making SELECT statement containing “joins” to run.
  61. 61. 61 SELECT statements containing Joins should not be confused with “Primary/Foreign” key relationship between the tables commonly known as Linking Tables which we will discuss later in this chapter. Just keep in mind whether you have established a primary/foreign key relationship between the tables or not, you can still run the SELECT statements containing joins against those tables. Self Join A self join is a join of a table to itself. The same table appear twice after the FROM clause. We have used e1 and e2 as two different aliases for the same table. It can be visualized by looking at the following example. Example: SELECT e1.ename||' works for '||e2.ename "Result" FROM emp e1, emp e2 WHERE e1.mgr = e2.empno; Output: Result --------------------- BLAKE works for KING CLARK works for KING JONES works for KING FORD works for JONES SMITH works for FORD ALLEN works for BLAKE WARD works for BLAKE MARTIN works for BLAKE SCOTT works for JONES
  62. 62. 62 TURNER works for BLAKE ADAMS works for SCOTT JAMES works for BLAKE MILLER works for CLARK Cartesian Product If in the joins statement you forget to put the WHERE condition or intentionally don’t write the WHERE clause at all, the result will be Cartesian product. Such type of output will be very rarely useful. If one table had five records and other one had six records; in the output you will get thirty records (5x6=30). That’s why we use the word product with such type of join.
  63. 63. 63 In the word Equijoin, Equi comes because we use Equal sign (=) in the join condition. The query containing Equijoin will give you total number of records equal to or less than the number of records of the one table among all the tables we have used in the query having least number of records in it. Lets take a example of two table Equijoin query like the one shown in the slide, only those records will be displayed from either of two tables where there is an exact match between the columns used in the WHERE clause. Example: SELECT ename, job, dept.deptno, dname FROM emp, dept WHERE emp.deptno = dept.deptno; Key Concepts 1) Only those records will be displayed from either of the two tables where there is an exact match between the columns used in the WHERE clause. 2) Primary & Foreign Key has nothing to do with Joins statements. 3) All different forms Joins are at the query level. The output exists in the RAM and is volatile.
  64. 64. 64 Or if you want to further reduce the number of records in the output you can extend the filter in the WHERE clause just like the example mentioned below. In the WHERE clause there are two conditions on both sides of AND operator, only those records will be displayed that satisfy both of these conditions. Example: SELECT ename, job, dept.deptno, dname FROM emp, dept WHERE emp.deptno = dept.deptno AND job = 'CLERK'; Output: ENAME JOB DEPTNO DNAME ---------- --------- ---------- -------------- MILLER CLERK 10 ACCOUNTING SMITH CLERK 20 RESEARCH ADAMS CLERK 20 RESEARCH JAMES CLERK 30 SALES 4) We can run Join queries on tables having Primary & Foreign Key relationship established or not having this relationship.
  65. 65. 65 If you ask me what is the most important thing in SQL and my response will always be “Outer Join”. This is because it has very high practical value. It has been used a lot in the real world wherever SQL is utilized. I want you to cram/memorize its definition word by word. I will first give you its definition and explanation will follow afterwards. Outer Join will give you all the records from the first table and only those records from the second table where there is a join. It means that the total number of in the result will be equal to the number of records of the one table among the two having no positive sign (+) attached with its column in the WHERE clause. In other words, the way you create an Outer Key Concepts 1) Outer join will give you all the records from the first table and only those records from the second table where there is a join. 2) Positive sign (+) will be placed with the column of the table having least number of records, in the WHERE clause.
  66. 66. 66 join is very simple. First create a Equijoin query and then place the positive sign (+) with the column of the table having least number of records, in the WHERE clause. I would like to have your focus on the NULL (empty) values in the slide; the one shown in the output table. These order dates are NULL because there were no supplier ids 10002 & 10003 in the orders table.
  67. 67. 67 UPDATE statement is used to edit the information already existing in the table. If you want to insert a new record in the table then we user the INSERT statement and if you want to delete any record or more than one record we use the DELETE statement. Example: UPDATE emp SET comm = NULL WHERE job = 'TRAINEE'; Example: INSERT INTO dept VALUES (50, 'PRODUCTION', 'SAN FRANCISCO'); Key Concepts 1) If you forget to mention the WHERE clause in the UPDATE statement, all the values in that column will get update. 2) While inserting new values in the table the order of columns should be kept in mind otherwise you may get a type mismatch error. To avoid this try using the INSERT syntax where you have to specify the column names.
  68. 68. 68 Another version, INSERT INTO emp (empno, ename, job, sal, comm, deptno) VALUES (7890, 'JINKS', 'CLERK', 1.2E3, NULL, 40); Example: DELETE FROM emp WHERE JOB = 'SALESMAN' AND COMM < 100;
  69. 69. 69 Before explaining how to create table I would like to give you slight explanation about the word “Schema”, what it is? And what it means in Oracle Jargon. Schema is basically has a Latin word and it means, a diagrammatic representation; an outline or model. Schema can be visualized by looking at the organization chart of a company e.g., the one shown below. Key Concepts 1) Each user we create in Oracle is considered as a Schema. 2) Each object created by user lies under his/her schema. 3) DBA is the owner of all the schemas and hence all the objects within each of these schemas.
  70. 70. 70 Figure: Organizational Chart. Showing Chief’s Schema. Each user we create in Oracle database is a “Schema”. All the objects (tables, Views, Sequences etc.) created by that user fall under his schema. Oracle DBA (Database Administrator) is the owner of all the schemas and the objects under each. He is just like the “Chief” in the above figure. To create table first you have to decide which schema you want this table to be in. Then log into Oracle system (usually SQL*Plus) using that schema’s (or User’s) credentials i.e. username/password. Upon successful login, execute the CREATE TABLE command to create required table under that schema. If you look in the slide, especially on the syntax of CREATE TABLE statement, there is something mentioned “data type” besides table name which will be name of the table that you want to create and the
  71. 71. 71 columns names which will be the names of the columns that you want to be in the table. While creating table you also have to tell Oracle what type of data goes in which column or in other words data type of each column e.g., if you tell oracle that I want to store date type of information in first column and text type of information in second column then while inserting data into this table using the INSERT statement you cannot insert number or currency like information in first column. If you do so, you will get “type miss- match” like error. Now lets see what different types of “Data Types” are available in Oracle so we can utilize them in the data type assignment of each column within a table in the CREATE TABLE statement. CHAR (size) A fixed-sized field of characters. Max 2000 bytes/characters. VARCHAR2 (size) A variable-sized field of characters. Max 4000 bytes/characters. LONG A variable-sized field of characters. Max 2GB. NUMBER (precision, scale) A variable-sized number. A NUMBER datatype with only one parameter is NUMBER (precision), where the parameter specifies the precision of the number. The precision can range from 1 to 38 and the scale can range from -84 to 127. A NUMBER datatype with no parameters is set to its maximum size. DATE A fixed-sized 7 bit field that is used to store dates. One thing to note
  72. 72. 72 is that the time is stored as part of the date. RAW (size) A variable-sized field of raw binary data. Max 2000 bytes. LONG RAW A variable-sized field of raw binary data. Max 2 GB. BLOB The Binary Large Object is a field that holds unstructured binary data. Max 4 GB. CLOB The Character Large Object is a field that holds single byte character data. Max 4 GB. BFILE An external binary file. The maximum size for this file is 4 GB. The size is also limited by the operating system. Example: CREATE TABLE album( id NUMBER(6), title VARCHAR2(100), artist VARCHAR2(100), activity DATE ); Once you write this statement in SQL*Plus or iSQL after logging in, a table with the name “album” will get created having four columns viz., id, title, artist and activity. In the last column we will insert the date when the record got submitted. You can create as many tables you want and they all will be under your schema.
  73. 73. 73 No one else beside DBA can have access to them unless you or DBA grant access explicitly. Example: CREATE TABLE emp_dept AS SELECT * FROM scott.emp WHERE deptno = 10; This is another way of creating table. Not only the structure but the data will get copied too in the emp_dept table.
  74. 74. 74 Once you have created a table you can alter its structure using the ALTER TABLE statement. You can add column, modify the attributes of columns e.g. data type, attach a constraint, rename a column or even drop it. All these tasks can be performed with an ALTER TABLE statement as shown in the slide. Do keep in the back of your mind that these modifications are 100% possible when you are not having any data inside the table but for cases where you already have data you cannot perform certain task e.g if the NUMBER column already contains data you cannot decrease its size etc. Key Concepts 1) Certain modifications using ALTER TABLE statement are not possible if you are already having the data inside that table. 2) One way of getting rid of unwanted column or unwanted data is to utilize the power of CREATE TABLE AS statement.
  75. 75. 75 Example: ALTER TABLE customers RENAME COLUMN limit TO amount; One thing I would like to mention over here, if you want to get rid of unwanted data is to utilize the beauty of CREATE TABLE …. AS SELECT statement.
  76. 76. 76 While creating tables besides mentioning about data types of columns we can assign constraints on each column wherever we feel necessary. Constraints help in achieving data integrity. In other words, before inserting or updating any information in database Oracle instance makes sure that none of the constraints get violated. For example if you have implemented UNIQUE constraint on one column and if you try to insert a record with a duplicate value that was already there in the column having UNIQUE constraint, you will a “constraint violation” error. Let’s study all of these constraints and their applications one by one. NOT NULL is a type of constraint once implemented on any column; you would not be able to insert NULL values in it. Key Concepts 1) Each value in the Primary Key column is a unique identifier for the whole record/row or in other words, no duplicate or NULL values are allowed in Primary key constraint column. 2) Oracle creates a implicit index for a column having Primary key constraint on it. 3) Index helps in speeding up the search process just like the index at the end of a book.
  77. 77. 77 Similarly with UNIQUE once defined on any column we would not be able to insert any record in the table with a value that was already there in UNIQUE constraint column. Example: CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9) CONSTRAINT unq_dname UNIQUE, loc VARCHAR2(10) ); In this example we have assigned a unique constraint on dname column. We have also used the CONSTRAINT clause to assign this constraint a name. We can also achieve the same result using the following statement. CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9) UNIQUE, loc VARCHAR2(10) ); The difference between this statement and the one mentioned above, we haven’t used the CONSTRAINT clause. So what is the benefit of using this clause? The benefit is, we can disable/enable this constraint using the ALTER TABLE statement. 4) Referential Integrity constraint also known as PRIMARY/FOREIGN KEY relationship between two or more tables results in two thing • Cannot delete any record from parent table with related PRIMARY KEY column value in child table’s FOREIGN KEY column unless we use ON DELETE CASCADE clause. • Cannot update/insert anything in child’s table FOREIGN KEY column with no corresponding value in parent table PRIMARY KEY column
  78. 78. 78 Example: ALTER TABLE dept DROP CONSTRAINT unq_dname; This statement will drop the constraint only from the table altogether. But if you would like to disable the constraint momentarily its better to use the DISABLE clause instead of DROP it. Example: ALTER TABLE dept DISABLE CONSTRAINT unq_dname; Once disabled this constraint will not be checked each and every time whenever there is a new insertion or update of record. Now the next question will popup in your mind, why there is a need to disable a constraint? One of the application of disabling a constraint comes at times when we do data migration from one oracle system to another or in other words bulk data loading into tables using SQL*Loader, we will this later in this book. If we are already sure that this data is already checked for uniqueness as its coming from table already having UNIQUE constraint on the column under discussion so there is no need for Oracle to perform this step while uploading bulk records and in this way we can save time of bulk data transfer. Once done we can enable the constraint using the following statement and this will bring the table back to its original state. A constraint that is currently disabled can be enabled in one of the two
  79. 79. 79 ways: enable NOVALIDATE or enable VALIDATE. The former does not check existing data for constraint violation. ALTER TABLE dept ENABLE VALIDATE CONSTRAINT unq_dname; Or, ALTER TABLE dept ENABLE NOVALIDATE CONSTRAINT unq_dname; On the other hand, CHECK constraint is called custom constraint. You have given the liberty to create or define the constraint according your needs. Example: CREATE TABLE suppliers ( supplier_id numeric(4), supplier_name varchar2(50), CONSTRAINT check_supplier_id CHECK (supplier_id BETWEEN 100 and 9999) ); Similarly in this case too Oracle Instance will make sure before inserting or updating any information into this suppliers table that the supplier_id lies between 100 and 9999. If it doesn’t then the user will get a “constraint violation” error and the request will not get processed. Lets now talk about Primary Key constraint. Once you implement this
  80. 80. 80 constraint on any column, you would not able to insert duplicate and NULL value i.e. each value in that will be a unique identifier for that whole record/row. Moreover Oracle creates a implicit index on that column. Index created by Oracle for any column of a table is having the same analogy of index we are having at the end of each book. Indexes created by Oracle serve the same purpose as the indexes at the end of books i.e. helps in speeding up the search process. Example: CREATE TABLE dept_test (deptno NUMBER(3) CONSTRAINT pk_dept_test PRIMARY KEY, dname VARCHAR2(15), loc VARCHAR2(10) ); Once you have created this table dept_test start inserting values in it. Remember since you have created a PRIMARY KEY constraint on deptno, column you would not be able to insert NULL value or any thing that was already there in deptno but can insert NULL or duplicate values in rest of the columns. Also Oracle will create a implicit index on this primary key column because Oracle presumes that you would be using this column a lot in your search criteria (WHERE caluse) and there are bringht chances that you may link this table with some other table using FOREIGN KEY constraint. Once you have installed Oracle with all the default options, Oracle Universal Installer will create a general purpose Oracle database by default. That database will be having dept and emp
  81. 81. 81 table already along with some data. That’s the reason in examples above I use the dept_test name for table otherwise I would have used the word dept only. Next we will create another table emp_test and link it with the dept_test table using FOREIGN KEY constraint. Once such a table gets created, the table having PRIMARY KEY is called the “Parent Table” and the one having the FOREIGN KEY is called the “Child Table”. A patent table can have as many child tables as you like or in other words a primary key constraint column can be linked to one or more tables using FOREIGN KEY constraint. No value can be inserted in the FOREIGN KEY constraint column having no exactly similar value in the referenced PRIMANARY KEY constraint column of parent table. Example: CREATE TABLE emp_test (empno NUMBER(4) CONSTRAINT pk_dept_test PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(10), deptno NUMBER(3), CONSTRAINT fk_emp_test FOREIGN KEY (deptno) REFERENCES dept_test(deptno) ); Once this table gets created you can say that you have developed a “link” between the two tables and this link will be permanent. The two beauties of PRIMARY/FOREIGN KEY relationship are as follows.
  82. 82. 82 • Keeping in focus PRIMARY KEY constraint column value(s) of parent table, if someone tries to delete a record from the parent table and there are corresponding value(s) in one or more child table(s) FOREIGN KEY constraint column, this task with result in Referential Integrity constraint violation error. But we can override this clause if we add ON DELETE CASCADE clause as shown in the example below. CREATE TABLE emp_test (empno NUMBER(4) CONSTRAINT pk_dept_test PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(10), deptno NUMBER(3), CONSTRAINT fk_emp_test FOREIGN KEY (deptno) REFERENCES dept_test(deptno) ON DELETE CASCADE ); Because of the cascade delete, when a record in the dept_test table is deleted, all records in the emp_test table will also be deleted that have the same deptno value. • If someone tries to Update/Insert a value in the FOREIGN KEY constraint column of child table and there is no such value in the parent table PRIMARY KEY column, this task will result again in Referential Integrity constraint violation error.
  83. 83. 83 Developing a PRIMARY KEY and FOREIGN KEY relationship between two or more tables has one another name, its called Referential Integrity (RI) constraint. So instead of saying that you have developed and implemted PRIMARY/FOREIGN KEY relationship between dept_test and emp_test tables, you can say that you have implemented RI constraint between dept_test and emp_test.
  84. 84. 84 Whenever you come across “Data Integrity” just say in your mind that the author or speaker is referring to all different sorts of constraints. Being a DBA, it will be one of your jobs to take all possible steps for having data integrity in the database because its is enterprise wide system users from all over the world may be interacting with the system. For any given instance some request would be coming to Oracle instance to insert new records others would be to update certain records and just think for a moment if would not be having all these different kinds of constraints, then there would be lots of redundancy of information, lots of errors etc. Its like filling a form online and you are allowed to enter date of birth in the zip code field. Key Concepts 1. Having a clear concept about the following two terms is really essential because these two terms are widely used in all RDBMS. 2. Many author uses these terms a lot keeping in their mind that the read knows it’s meaning already.
  85. 85. 85 In short all these constrains available in Oracle helps attaining maximum data integrity. Another term that is used widely in all sorts of RDBMS (Relational Database Management Systems) not only just Oracle is “Data Consistency”. It means that every one connected to Oracle Instance will see the consistent view of information. Oracle has very beautiful built-in locking mechanism. Above all Oracle takes care of this by default magnificently but if you want you can configure and override the default configuration. Transactional changes will only made visible to everyone once committed by executing the COMMIT command.
  86. 86. 86 Like I said before, all the joins techniques we have learnt before viz., Outer Join, Equijoin etc. are at the query level can be implement on tables having Primary/Foreign Key relationship or not. Implementing Primary/Foreign key relationship between two or more tables is also known as implementing Referential Integrity (RI) constraint between tose two or more tables. The reason of bringing this topic up is, most beginners often get confused when they read about joins and then primary key and foreign key. Key Concepts 1) Joins statements can be executed on tables having Referential Integrity constraint or not. 2) The word “Join” should not be confused with as I if you are joining the two tables permanently.
  87. 87. 87 They think that joins statements are only executed on tables linked through primary and foreign key relationship but it’s not true. The word “joins” sometimes gives the feeling as if we are about to join two or more tables permanently but no, its just you are querying data from two or more tables using of the techniques that fall under the title called “Joins”.
  88. 88. 88 Besides tables that we create within our schema, there are other logical structures called database objects. One of those objects is called a View. Like the name says, it’s a view, a window through which we can see only the data we need or in other words we can create a view and grant users to view the information. While creating the view we will include only those information that we want others to have access. Views are comprised of one or more tables or views and they themselves contain no data and the underlying tables are called based tables. Creating views is exactly similar creating tables, the only difference is we use CREATE VIEW statement instead of CREATE TABLE statement. Key Concepts 1) Once you drop a VIEW, base tables and views will not get deleted. 2) For each index you create Oracle creates an implicit table based on that particular column in a manner that will help it in locating records easier. 3) Sequences are like auto- number objects. You can always get the next number and insert it in any number datatye column, usually id kind of field e.g. emp_id.
  89. 89. 89 Example: CREATE VIEW emp_view AS SELECT * FROM employees WHERE department_id = 20; Dropping a view will not drop the underlying base tables or views. Also you can insert and update the base tables through the view provided the constraints implemented on the based tables won’t get violated. We can use any of the form of Join-based SELECT statement to have the view based on more than one table. We can also create a read only view using the WITH READ ONLY clause and grant access to users so that then they would not be able to modify the base tables. Example: CREATE VIEW emp_view AS SELECT * FROM employees WHERE department_id = 20 WITH READ ONLY; Example: DROP VIEW emp_view; Dropping view neither drops base tables or views nor the data residing in each of those base tables. Next we would to talk about are the Indexes. We have seen previously that an index gets created whenever you create a PRIMARY KEY constraint on any
  90. 90. 90 column of a table, implicit. We call it an implicit index because you haven’t executed any index creation statement but it gets created as a result of something else we wanted to do or in other words you can say the term it’s a “by product” of PRIMARY KEY constraint. There are certain pros and corns associated with index. The sole purpose or you can say the benefit of index is, it speeds up the search process. Just like the index available to you at the end of book. Imagine a book having no index and comprised of 1000 pages and 30 likes per page. I hope you got the essence, the beauty, and the power of having an index. Now the next question comes in mind. What’s the criterion of selecting a column for index purpose? or in other words which columns should we create index on? And what’s wrong with having indexes created on all the columns of all the tables? Do think for a while at least before reading below the reasons. The criterion of selecting a column for index purpose is, the column we would be using a lot in there WHERE clause. The emphasis is on “a lot”. How to figure out which columns will be used a lot? Some columns are apparent e.g. in SSA (Social Security Administration) office, its obvious that most of the time they would be pulling up the information using ssn or most of times requests coming to SSA to look up for something would be through ssn. It doesn’t mean that you cannot make a search based on other columns.
  91. 91. 91 Each time you create a index on any column of a table Oracle creates a implicit table that can help it in locating the records much faster. That table size depends on the size of column on which you have created the index but both these quantities are in direct relationship with each other i.e. more the number of values in column, on which you have created the index, more would be size of implicit table that Oracle will create. So creating indexes on all the columns of all the table inside the database will to do much rather it will tremendously increase the size of the database and its growing rate. Moreover, you would not be using them all in your search criteria. Example: CREATE INDEX emp_test_idx ON emp_tests (empno); Where emp_test_idx is the name that we have given to this index and its created on empno column of emp_test table. Example: CREATE INDEX m1_idx ON m1 (id1, id2); Where m1_idx is the name of the index, which is created on two columns id1, and id2 of m1 table. Such type of index is called composite index as they gets created on two or more than two columns.
  92. 92. 92 Example: ALTER INDEX m1_idx RENAME TO m2_idx; This statement will rename the index to m2_idx. There are lot other stuff that we can do with ALTER INDEX command but we will it later in this book when we talk about different forms of indexes that are available. Example: DROP INDEX m2_idx; This statement will drop the index on that particular column all together. Sequence is also a logical structure in the database. Just like tables and views, they are also called as objects. Basically Sequence generates sequence number so you would have to remember what id number should we give to newly hired employee. Just ask the sequence for next value and it provide you one. How the sequence generates numbers, it all depends on the way you create them. Example: CREATE SEQUENCE emp_seq START WITH 1000 MAXVALUE 99999 INCREMENT BY 1 NOCYCLE; This statement will create sequence emp_seq which will start with 1000 and increment by 1 i.e. each time you ask for
  93. 93. 93 new value from this sequence it will give you a number 1 higher than the previous one. Maximum value would be 99999 and if you want you can use NOMAXVALUE. CYCLE clause we use if you want to force the sequence to start all over again once it hits the maximum value otherwise use NOCYCLE. Example: SELECT emp_seq.NEXTVAL FROM dual; We use NEXTVAL method to retrieve the next value from the sequence so that we don’t have to worry about what id to allot to a newly hired employee. INSERT INTO emp_info (id, name, email) VALUES (emp_seq.NEXTVAL, 'Gregory', ‘gregory@oracle.com' ); Example: SELECT emp_seq.CURRVAL FROM dual; You can also find out the current value of the sequence using CURRVAL method. Example: ALTER SEQUENCE emp_seq MAXVALUE 1500; We can also alter the structure of the already exisiting sequence in the database
  94. 94. 94 using the ALTER SEQUENCE statement. Example: DROP SEQUENCE emp_seq; We can also drop a sequence from the database using the DROP SEQUENCE statement. Lastly, we create synonym using CREATE SYNONYM statement. Synonym is basically an alias or another name given to already existing database object e.g. table, view, sequence, stored procedure, stored function, package etc. The last three names you just read are also object of oracle database but the fall under the category of PL/SQL language. It can be further clarified by looking at the following real world example. Example: CREATE SYNONYM offices FOR hr.locations; So instead of typing the full name for the object i.e. schema.object_name, you have to just type the synonym name. If you want to grant access to other users, the users need not to know which schema this object is in. Moreover, if you drop this synonym all users will not be having access to hr.locations table any more. Remember dropping the synonym will not drop the underlying table or object.
  95. 95. 95 Example: CREATE PUBLIC SYNONYM employees FOR hr.employees@sales; Public synonym are accessible to all the users provided they have access to underlying object. The above statement will create a employee synonym for a employees table in hr schema in a remote sales database. Example: DROP SYNONYM offices; We use DROP SYNONYM statement to drop the synonym completely from the database. The underlying object will not get removed. I thing you must be looking that I haven’t discussed something like ALTER SYNONYM. So just keep in your mind there is no such statement. If you want to alter synonym just recreate it by first dropping it and then using CREATE SYNONYM statement.
  96. 96. 96 To install Oracle software on the machine you have to be the member of OS (Operating System) SYSOPER or SYSDBA group. Once you install Oracle software and have default database created by Oracle Universal Installer. There will be two users created at the end of creation of database. One is “sys” with the password “change_on_install” and other one “system” with the password “manger”. It’s highly recommended that you change these passwords since these are standard accounts and everywhere is the same. Its also recommended that you should create at least one more dba level account. We will learn in more detail regarding the purpose of having a sys and system accounts later in this book. Key Concepts 1. Users can be authenticated by the database or the OS. 2. Privileges can be assigned to users and roles.
  97. 97. 97 To create a new user (schema) you should login to Oracle Instance using one of the DBA’s account and then user the CREATE USER statement to create new user. Example: CREATE USER sophia IDENTIFIED BY evergreen DEFAULT TABLESPACE user_demo; This statement will create a new user with the login as sophia and password as evergreen and whatever objects (tables, views etc.) that user sophia will create will reside in the user_demo tablespace. Such types of accounts are called “Database-Authenticated User Accounts” where users get verified by the database. There is another form of authentication which is called “Externally Authenticated User Accounts” or also known as OPS$ accounts. Such users get verified by OS once they log in. When Oracle 6 was introduced such category of accounts were to be prefixed with OPS$ and that’s why we call them OPS$ user accounts. If os_authent_prefix init.ora paramenter is left as default i.e. OPS$, then the Externally Authenticated User Account can be created as follows. CREATE USER ops$sophia IDENTIFIED EXTERNALLY; On the other hand if its set to blank (os_authent_prefix = “ ”) then no prefix is required as shown in the following example. CREATE USER sophia
  98. 98. 98 IDENTIFIED EXTERNALLY; Example: ALTER USER sophia IDENTIFIED BY black123; Or, ALTER USER sophia DEFAULT TABLESPACE hr_data; To change the password of sophia or anything else related to user, use the ALTER USER statement. Once you have created the user and assigned him/her default tablespace then the next thing is to grant that user is ready to go. He can now create database objects (tables, views etc) under his schema. You can also assign him access to objects under your schema using GRANT statement and you can also take that privilege back using the REVOKE statement. Next very important concept I would like to give you is the “role”. Role in database jargon means the group of privileges bundled together and given a name or alias. So what is the benefit of creating roles? For example, let say Human Resources (HR) department of a company has 65 people and out of those 65 people, 35 were having SELECT, INSERT, UPDATE, DELETE privileges on Payroll department tables and we are assuming a scenario where you have assigned each of these 35 people privileges not role. After
  99. 99. 99 a month change of business rule comes up and its described that those 35 HR would only be having SELECT privilege on Payroll tables. Without using role you have to run REVOKE statement 35 times and if you would go by “role” technique one statement can implement that change no matter whether there are 35 people or 3500 people. Privileges can be granted to users as well as roles. Example: CREATE ROLE hr_emps IDENTIFIED BY evergreen; By default a role is created with the password and is enabled. One that is created with the password is disabled by default and can be enabled using SET ROLE statement. SET ROLE hr_emps IDENTIFIED BY evergreen; SET ROLE statement can be used to enable or disable a gole. Once we have created the role, next thing is to assign this role, privileges. GRANT SELECT, UPDATE ON emp_test TO hr_emps; There are two kinds of privileges, one is called “Object Privileges” and the other one is called “System Privileges”. The complete list of each of these object privileges is given below along with their
  100. 100. 100 application. ALTER Table, Sequence DELETE Table, View INDEX Table INSERT Table, View READ Dictionary REFERENCE Table SELECT Table, Sequence, View UPDATE Table, View EXECUTE PL/SQL Objects e.g. Functions, Package etc. The way to interpret this table is, if you keep the above example in your mind, you can grant ALTER, DELETE object privilege on any table but you cannot grant READ on any table. This implies to EXECUTE, one cannot grant EXECUTE privilege on any table, view etc. its only meant for PL/SQL objects. On the other hand, System privileges allow the ability to create, alter, drop and manage database objects or features. There is a long list of system privileges and for ease of study we have categorized them in the following categories. CREATE CLUSTER CREATE ANY CLUSTER ALTER ANY CLUSTER Cluster DROP ANY CLUSTER ALTER DATABASE ALTER SYSTEMDatabase AUDIT SYSTEM CREATE TABLE CREATE ANY TABLE ALTER ANY TABLE DROP ANY TABLE SELECT ANY TABLE UPDATE ANY TABLE Table DELETE ANY TABLE
  101. 101. 101 INSERT ANY TABLE LOCK ANY TABLE CREATE SEQUENCE CREATE ANY SEQUENCE ALTER ANY SEQUENCE DROP ANY SEQUENCE Sequence SELECT ANY SEQUENCE CREATE SYNONYM CREATE ANY SYNONYM CREATE PUBLIC SYNONYM DROP ANY SYNONYM Synonym DROP PUBLIC SYNONYM CREATE SESSION Session ALTER SESSION CREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE MANAGE TABLESPACE Tablespace UNLIMITED TABLESPACE CREATE USER ALTER USER BECOME USER User DROP USER CREATE VIEW CREATE ANY VIEWView DROP ANY VIEW CREATE ANY INDEX ALTER ANY INDEXIndex DROP ANY INDEX CREATE ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT Rollback Segment DROP ROLLBACK SEGMENT
  102. 102. 102 Besides these are system privileges for PL/SQL functionalities like CREATE PROCEDURE, CREATE ANY PROCEDURE, EXECUTE ANY PROCEDURE etc. Two very special and important system privileges are SYSDBA and SYSOPER. That’s why I want to discuss them separately. Following table describes the power lies beneath these two system privileges. Create new database Startup, Shut down database Alter database with the OPEN, MOUNT, BACKUP, CHANGE CHARACTER SET, ARCHIVELOG and RECOVER options SYSDBA Create SP file Startup, Shut down database Alter database with the OPEN, MOUNT, BACKUP, ARCHIVELOG and RECOVER options SYSOPER Create SP file Example: CREATE ROLE hr_emps; GRANT SELECT, UPDATE ON emp_test TO hr_emps; GRANT hr_emps TO margorie, daisy, jessie, semper;
  103. 103. 103 In this example we have first created the role hr_emps and next we assign certain privileges to it and finally we have assigned it to all the employees of hr (Human Resources department). After a month, new business rule comes up which says that all the hr employees should only be having SELECT privilege on emp_test table. To implement this rule all you have to do is to revoke the privilege from the role e.g. REVOKE UPDATE ON emp_test FROM hr_emps; Lastly, there is one more thing just like role, its called profile. Profiles allow you to assign resource consumption limit or setting password policies on user accounts. All user accounts have profile assigned to them. If you don’t assign it explicitly while creating or altering the user account explicitly, a default one gets assigned automatically. You can assign profile to a user account at the time of creation of account or you can use ALTER USER command to assign it later. Let’s have a look on the following example.
  104. 104. 104 Example: CREATE USER marion IDENTIFIED mateena PROFILE paramod; Or, ALTER USER marion PROFILE paramod; Here mateena is a password for username marion and paramod is the name of a profile we created earlier, it could be any name. Now its see how we can create profile. Example: CREATE PROFILE paramod LIMIT CONNECT_TIME UNLIMITED; Or, ALTER PROFILE sidney LIMIT CONNECT_TIME 240; When the CONNECT_TIME value is exceeded Oracle rolls back the current transaction and ends the session. Example: CREATE PROFILE hr_dept LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED;
  105. 105. 105 Or, CREATE PROFILE hr_dept LIMIT FAILED_LOGIN_ATTEMPTS 5; I think this is self-explanatory. Besides these, the other resource consumption and password settings are, LOGICAL_READS_PER_CALL, SESSIONS_PER_USER, PASSWORD_LIFE_TIME, PASSWORD_GRACE_TIME, PASSWORD_LOCK_TIME, PASSWORD_REUSE_TIME, PASSWORD_REUSE_MAX etc.
  106. 106. 106 We Did It! In this chapter we basically learnt the “grammar” of communication language (SQL); language that we will use to communicate with Genie (Oracle Instance). We learnt all different types of statements like SELECT, INSERT, UPDATE, CREATE etc. and concepts of “joins” and “referential integrity” constraints. We also talked about privileges, roles and profiles. In short we learnt all ins and outs about SQL: Structured Query Language.
  107. 107. 107 CChhaapptteerr 33 Oracle Database Concepts • Physical Architecture • Logical Architecture • Relationship between Physical and Logical Architecture of Oracle database • Redo Log Files utilization
  108. 108. 108
  109. 109. 109 Like I said before, the complete Oracle system consists of two things viz., Oracle Instance and Oracle Database. To better understand and visualize the system you can thing of Oracle Instance as Genie and the Oracle Database as Genie’s Notebook. This is a data management genie and it has some magical powers. It utilizes its notebook to remember data or information and fulfill users’ requests coming from all over the world. This chapter basically deals with the Oracle database and its architecture. When you were learning SQL and executing quires in SQL*Plus environment, you must be thinking where this stuff is actually coming form. In which physical file emp table is residing and in which file you created emp_test table. After reading this chapter all your Key Concepts 1) Oracle Server is comprised of two things o Instance o Database 2) Visualize Oracle Instance as Genie and Database as Genie’s Notebook, which he uses to remember information for longer period of time. 3) Oracle database has a logical architecture and a physical architecture.
  110. 110. 110 questions like this and many more will get resolved. Oracle database has a logical architecture as well as physical architecture. When I first time read this thing I got confused. While reading this chapter, many such things will come up, don’t stop just keep reading till the end of the chapter. You will see that everything will get clear. When we talk about database objects, we are actually talking about logical architecture and when are talking about physical files like control file, data files etc., we are actually talking about physical architecture of Oracle database.
  111. 111. 111 We can look at Oracle Database through two angles viz., logically and physically. We will talk about logical architecture of Oracle Database in the next article. Physical architecture of Oracle Database is comprised of five different types of files. Those five files along with their brief description are given below. Control File Data Files Main Oracle Database Files. Redo Log Files Oracle Instance reads it at startup. Parameter File (init.ora) Archiving of Redo Log Files Archived Redo Log Files Control File: Every database has one control file and it basically contains the information regarding the structure of database. Control file doesn’t contain any records. Key Concepts 1) Oracle Instance updates the control file whenever the physical structure of database is changed by DBA. 2) Data Files holds the actual data and if you keeping added records to your database tables, the sizes of these data files increase along with the size of redo Log files. 3) Redo Log files get utilized in a circular fashion.
  112. 112. 112 If you keep inserting records in your tables using the INSERT statement, the size of your control file will not change. Oracle Instance reads control file at the time of startup to find out database name, location of data files and redo log files. You can tell Oracle Instance to “Multiplex” control file or in other words having a exact mirror copy of control file sitting at some other disk. In case media failure occurs you would always be having another copy available on the other disk. Never place the mirror copy on the same disk. Data Files: Data files are the files where the actual database’s data resides. If you keep inserting the records using the INSERT statement the size of these files increases. Oracle database can have one or more data files. The size of each data file is limited to OS (operating system) maximum file size. But the size of the Oracle Database can be whatever you like. There is no limit on the maximum size of the database. If you are running out of space you can always add more data files to the database by bringing in hard drives into your system. Redo Log Files & Archived Redo Log Files: Redo Log files are the files that maintains the changes happening in data. To visualize this keep Microsoft Word in mind, it also keeps the changes you make in data so that you can revert back as required. Every Oracle Database has set of two or more redo log files. Each set is 4) It is recommended that Oracle should be run under “Archived Log Mode” so that Redo Log files get copied before getting overwritten. 5) Redo Log files along with Archived Redo Log files plays a major role in the database recovery process.
  113. 113. 113 called redo log file group. Redo log files gets utilized in a circular fashion i.e. when Oracle Instance finishes writing the last redo log file then it starts overwriting the first one unless you archived that redo log file or in other words unless you order Oracle Instance (Giene) to make sure redo log files gets archived before they get over written. We will study in great detail in the last slide of this chapter. The way we can protect overwriting of Redo Log files is to run the Oracle Instance in Archive Log Mode. If Oracle is running in this mode than redo log files will get archived to the destination you specify in the parameter file before getting overwritten. Parameter File (PFILE): Parameter file contains the name of the database, location of control file, memory structure of Oracle Instance and certain other necessary Oracle system configuration parameters. PFILE is read by Oracle Instance while starting up the database or even before that i.e. when the Instance creates itself. We will talk about instance in the next chapter but let me give you a brief image what instance is. The background processes and memory architecture constitute an instance. You may find it difficult to understand it at this spot. Do not stop. Keep reading and everything will be fine. Since Instance is the combination of “Memory Architecture” and “Background Processes” so when you double click oracle icon or runs
  114. 114. 114 oracle system, the first thing that gets erected is Oracle Instance. How the memory structure would be for that instance, that’s why we define in parameter file.
  115. 115. 115 Physically the data inside the database resides in the data files located on hard drives and if you want you can copy them to different location but remember you cannot read those files by yourself. The data in data files are encrypted and can only be understandable to Oracle Instance, so if you want to take anything out from those data files you first have to make the Oracle Instance alive and then you have to present your credential (username/password) to the Instance and based on your access level you data related wishes will get fulfilled. Logically the data inside the database resides inside the tablespaces. Each tablespace is comprised of segments. Oracle Instance allocates a segment each time you create a object (table, view etc) inside the database. Each segment is Key Concepts 1) Logically database is composed of tablespaces. Each table space can be visualized as a department level database e.g for each department of a company you would be having one tablespace. 2) Each tablespace is composed of segments and Oracle allots a segment each time you create a database object e.g. tables, views etc using CREATE statement 3) Each Segment is composed of Extents and extents are nothing but contiguous DB Blocks.
  116. 116. 116 composed of Extents and What are Extents? Each extent is a group of contiguous DB Blocks. Now what are DB Blocks? A DB Block is the smallest building block of the database and is usually the even multiple of OS Block e.g. DB Block can be (2 * OS Block) but not (1.37 * OS Block). The size of the DB Block can be specified using DB_BLOCK_SIZE init.ora parameter. You can assign values like 2KB (2 Kilo Byes) and if the OS permits you can have 4KB, 8KB etc. 4) DB Block is usually the even multiple of OS Block and its value is specified in parameter file (init.ora)
  117. 117. 117 This is a side by side relationship development between logical and physical architecture of Oracle database. The database is the same but you can look at it through two angles. You can talk about its files (data files, control file etc.) or you can talk about its tablespaces, segments (objects) etc. Tablespaces are like small departmental level databases with a bigger umbrella of company’s database. Data inside these tablespaces within the database resides in the data a file. You insert data into the segments (tables) using INSERT statement so the segment grows. When the segment grows, tablespace within which its residing grows and the size of data file(s) associated with the tablespace grows. If there is only one data file associated with the tablespace then the maximum size of the tablespace cannot Key Concepts 1) Data inside the tablespace reside in the data files which are physical files like all other files located on your computer. 2) Size of the tablespace and hence the size of database is not limited to the OS marked limit on the file size.
  118. 118. 118 be more than the Operating System maximum files size. But you can always add another data file to the tablespace using the ALTER TABLESPACE statement. In this way the maximum size of tablespace is not limited to the OS marked limit on file size. When we talk about the relationship between logical and physical architecture of database, we mean that we are talking about how tablespaces are related to the data files.
  119. 119. 119 When we talk about the relationship between physical and logical architecture of oracle database, we are actually talking about the relationship between data files and tablespaces or vice versa. Data file is the physical quantity. Its physical because you can see the actual data files sitting in your computer just like the other files sitting in the computer whereas the tablespaces (as well as segments, extents and DB Blocks) you cannot see it or point at it or in other words cannot copy using OS copy command like you can with data files or other files in your computer. After having this concept, I would like to define the relationship between logical and physical architecture of Oracle Database in the following lines. It’s very important and I want you to memorize it word by word. First understand it then memorize it. Key Concepts 1) Each tablespace can have one or more data files associated with it but each data file can never be associated with more than one table space. 2) Segments can be sitting under two or more data files under the same tablespace.
  120. 120. 120 Each tablespace can have one or more data files associated with it but each data file can never belong to more than one tablespace. Segments (database objects) can lie in more than one data file within the table space. This can be better visualized by looking at the next slide. Whenever you create a database object, Oracle Instance allocates a segment in the tablespace assigned to your schema at the time of creation of user account using CREATE USER statement.
  121. 121. 121 With this slide you can easily visualize the physical and logical architecture of Oracle Database. For some people this figure would be self-explanatory and how truly someone has said, “A Picture is better than thousand words”. As shown in the slide, this Oracle Database is comprised of two tablespaces namely Tablespace 1 and Tablespace 2. Tablespace 1 is comprised of two data files whereas Tablespace 2 is comprised of one data files. So we can say that this oracle database has three data files. Tablespace 1 has total of six segments or database objects (tables, views, synonym etc.) and some segments are totally residing in one data file whereas some are residing partially in one data file and partially in other data file e.g. keep in focus Tablespace 1, the data inside segment 2 (SG 2) and segment 5 (SG 5) Key Concepts 1) Data inside the segment can reside in two or more data files with the same tablespace. 2) Tablespace is nothing but just an alias given to the group of data files or data file.
  122. 122. 122 is distributed among two data files. Tablespace 2 is comprised of only one data file so all the objects created by the user will reside in this one data file. The major purpose of adding more data files to the tablespace is to remove the limit of OS defined maximum limit of file size e.g. those are familiar with MS Access know very well that the size of MS Access “database” can never be more than OS defined maximum file size.
  123. 123. 123 Just a slight revision, we said the database is comprised of five different types of files and we have learnt the purpose of each. Among those five different types of files one is Redo log file. We have learnt earlier in this chapter that a database should have two or more redo log groups. Each redo log group should have at least two or more redo log files called members. Within one Redo log group, all redo log files are mirror copies of each other and its recommend that they all should reside on different physical hard drives or tape drives to increase the fault tolerance factor. Having mirror copies of the original Redo Log file within a group is called Multiplexing of Redo Log files. Its DBA’s job to select how many Redo Log files mirroring is required and where to place each mirrored copy. Key Concepts 1) A database should have at least two Redo Log groups. 2) Each Redo Log group should have two or more redo log files called “members” 3) Redo Log files get utilized by Oracle Instance in a circular fashion. 4) Redo Log files and Archived Redo Log files play a great role in Oracle Database recovery in times of any kind of failure.
  124. 124. 124 Whatever data changes are happening in the database, all gets written to the Redo Log files. In other words you can say it’s the “Undo” copy of the original database. Keeping in focus the above slide, Oracle Instance (or more precisely, the Log Writer process) will start writing these changes in data from Redo Log group 1, once it gets filled up, Oracle instance will move to group 2 and finally group 3. Once group 3 finishes up, Oracle instance will start all over gain from group 1. That’s the reason we say that Redo Log files get utilized in a circular fashion. To avoid overwriting of Redo Log files, you should run the Oracle Instance in Archive Log Mode. Whenever Oracle is running in this mode, redo log files gets archived well before they get overwritten. This Redo Log mechanism and Archived Redo Log files play a great role in Oracle database recovery in times of disaster of any kind. We will learn about Oracle Backup & Recovery later in this book in great detail.
  125. 125. 125 We Did It! In this chapter we have learnt about “physical” as well as “logical” architecture about Oracle Database. Physically a database is comprised of Control file, Data files, Redo Log files, Parameter file and Archived Redo Log files. But the actual users’ data resides in the data files. Whereas logically, a database is comprised of tablespaces, segments, extents and DB Blocks or database blocks. Moreover, we also talked in detail regarding the utilization of Redo Log files.
  126. 126. 126
  127. 127. 127 CChhaapptteerr 44 Oracle Instance Concepts
  128. 128. 128
  129. 129. 129 Oracle system or more commonly we use the word Oracle server or Oracle Database, whatever name you use, just keep one thing in mind that Oracle has two pieces. Once is called Oracle Instance and the other one is Oracle Database. User sends commands to the Oracle Instance (Genie) and Oracle Instance after interacting with the database will send the result back to the original user. In this chapter we will only talk about Oracle Instance and you can visualize it as a genie. You cannot retrieve the data directly from the database. You have to send the request to Oracle Instance and it can fulfill your request. Key Concepts 1) The background processes and memory architecture constitute the Oracle Instance.
  130. 130. 130 The thing I want you to memorize if you haven’t memorize it yet, the definition of Oracle Instance i.e. the background processes and memory architecture constitute the Oracle Instance.
  131. 131. 131 Oracle Instance can be defined as, the background processes and memory architecture constitute the instance. There are very few things in this whole book that I will request you to memorize and this definition is one of them. Now the question is what is a “background process”? And what is “memory architecture”? To better understand these two thing I want to give you the analogy of the way human brain works. Human brains works pretty much the same way Oracle Instance works. Human brain also has a memory architecture and background processes. I am giving you the link to the article “Reducing The Factor Of Making Wrong Decisions”. Key Concepts 1) The background processes and memory architecture constitute the Instance. 2) Human brain works pretty much the same way Oracle Instance works.
  132. 132. 132 The last thing I have discussed in this article is, how to optimize the working of human brain and is available at (http://www.selfgrowth.com/ articles/Abbasi1.html). So the brief study of Human Brain working can really help us in visualizing Oracle Instance and how it works. How background processes interacts with the memory architecture to get things done faster and efficiently. The sources of input to the Brain are our five senses similarly the sources of input Figure Background Processes & Memory Architecture Inside Brain to the Oracle Instance are connected users and their requests. Human brain interacts with the external world utilizing those five senses. Background processes receive inputs from these five senses and based on the request, interacts with the memory and sends the output or the “decision”. For example, you must have noticed, if you come across a very old friend that you
  133. 133. 133 last met 15 or 25 years ago. You saw him and he saw you in a shopping mall. Both of you will stop and say in astonishment, “I am feeling difficult in recalling but I must have seen you some where”. That’s the point where one of the background processes in brain is busy searching the memory/dictionary/library (or whatever you name it) to pull up the record/information about that person. And after few seconds you say, “David, my old Kindergarten friend”. He says, “Wait a minute …”. “Julie, good to see you after a long time”. Did you notice one thing, David said wait a minute. So the search that was being performed by one of the background processes in David’s brain came up with the result little late than Julie’s brain. With some people, results come out mush faster but for others very slow. That’s the reason; the article explains how to optimize the working of human brain. Physically all human brains are similar i.e. two hemispheres but it’s the way you build the logical architecture on top of physically architecture which makes one “Einstein” and other me. Whenever we use the word memory we usually are referring to RAM (Random Access Memory) inside the computer. Why we need another kind of memory:
  134. 134. 134 RAM inside the computer if we already have hard drives? Its because the speed with which Microprocessor (CPU) communicates with the RAM is much faster (Electric Speed, speed with which electric current travels from one point to another or in other words speed of light) compared to the speed with which CPU interacts with the hard drive (Hard Drives involves a mechanical movement of motors inside the hard drive). If you ask me regarding my life 15 years back, day by day e.g. what I did everyday in January, similarly in February and so on up till today. I would never be able to tell you that. But what I can tell, are the major events that happened in my life in the past fifteen years e.g. I got my BS in Electrical Engineering July 2000 or my father bought a brand new PC for me in 1993 etc. If you start utilizing the Note Books (Papers) and start writing the story about your life each and everyday then you can tell everything regarding your past day by day. Similarly Oracle Instance has to utilize the data files to make the data/information permanent.
  135. 135. 135 Oracle System Human System Oracle Instance + Oracle Database Human Brain + Note Books (Papers etc.) Oracle Instance is composed of background processes & memory architecture Human brain is composed of background processes & memory architecture. Human brain is far more complex than what I explained. The sole purpose is to develop the analogy, which helps in understanding and leaves fewer burdens on brain to swallow the principles.
  136. 136. 136 By saying, memory architecture of Oracle Instance we mean how RAM is utilized by Oracle Instance or more precisely part of RAM is dedicated for Oracle purpose, since its not only Oracle that is utilizing the RAM in your computer. Every program that you run under any OS (Windows, Linux etc.) occupies certain amount of RAM. For example, if your computer has 256MB of RAM and lets suppose MS Word occupies 50 MB. If you keep on opening MS Word instances your system will turn slower and slower and eventually will halt. Every software that you run, utilizes RAM for speedy processing and when it comes to making changes permanent (when you press the save button etc.) that software writes the stuff in the hard disk. Key Concepts 1) Every software that you run under any OS occupies RAM (or Memory), so does Oracle. 2) SGA is the most important piece and it stands for System Global Area. 3) Non-shared memory is not shared among all the users whereas shared is shared among all. 4) Database Buffer Cache has three sub-caches. o KEEP o RECYCLE o DEFAULT
  137. 137. 137 Similarly Oracle utilizes RAM too for the same purpose what other programs does i.e. speedy processing. How that RAM is categorized or what’s its architecture, that’s exactly what, is shown in the slide. The RAM or simply memory, occupied by Oracle is divided into two major categories. One is called Shared Memory and the other one is called Non Shared Memory. Oracle allocates SGA (System Global Area) whenever Instance starts and deallocates it when the Instance ends. In OracleRAC (Oracle Real Application Cluster, used to be called as Oracle Parallel Server) multiple Instances can access the same database and we can achieve performance using load balancing etc, each instance has its own SGA. The study of OracleRAC (multiple instances and one database) is beyond the scope of this book but you cannot jump on to that topic without mastering Oracle system with one instance and one database. If you have full mastery over the topics discussed in this book then learning and implementing OracleRAC will be piece a cake. Shared Memory is shared among all connected users with the Oracle Instance i.e. if one user has submitted the SQL statement from Canada and another user in Japan has submitted the same SQL statement, if its parsed version is available in SGA, Oracle uses that instead of reparsing. 5) Three different states of buffers within Database Buffer Cache. o Dirty Buffers o Free Buffers o Pinned Buffers 6) Non-Shared part of Oracle memory architecture is also called PGA or Program Global Area. 7) The utilization of PGA depends how you configure the Oracle Server. 8) Oracle Server can be configured to run as Dedicated Server mode or Shared Server mode. 9) Unlike SGA where RAM is shared by all the background process, PGA is utilized by server process for sorting, session information and as stack space.

×