Oracle 10g Made Simple

384
In the name of God; the most gracious, the most compassionate, the knower of all. Oracle 10g Database Administration Concepts and Implementation Made Simple

Transcript of Oracle 10g Made Simple

Page 1: Oracle 10g Made Simple

In the name of God; the most gracious, the most compassionate, the knower of all.

OOrraaccllee 1100gg DDaattaabbaassee AAddmmiinniissttrraattiioonn CCoonncceeppttss aanndd IImmpplleemmeennttaattiioonn

MMaaddee SSiimmppllee

Page 2: Oracle 10g Made Simple

2

Page 3: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

3

OOrraaccllee 1100gg DDaattaabbaassee AAddmmiinniissttrraattiioonn

CCoonncceeppttss && IImmpplleemmeennttaattiioonn

MMaaddee SSiimmppllee

BBYY

AASSIIMM AABBBBAASSII

Page 4: Oracle 10g Made Simple

4

Copyright © Asim Abbasi. 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-8-X Takveen and the Takveen logo are either registered trademarks or trademarks of Takveen 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. 100% manufactured in the United States of America.

Page 5: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

5

DDeeddiiccaatteedd TToo tthhee oonnllyy OOnnee ……

TToo tthhee oonnllyy OOnnee,,

WWhhoo sseeeess tthhrroouugghh oouurr eeyyeess,, WWhhoo lliisstteennss tthhrroouugghh oouurr eeaarrss,, WWhhoo hhaass nnoo ffeeaarr..

TToo tthhee oonnllyy OOnnee,,

WWhhoo kknnoowwss wwhhaatt’’ss iinnssiiddee oouurr hheeaarrtt,, WWhheetthheerr iitt’’ss ppuurree oorr JJaarrvviikk hheeaarrtt,,

TToo tthhee oonnllyy OOnnee,, WWhhoo gguuiiddeess,, WWhhoo gglliiddeess tthhee sshhiippss ttoo tthhee ssiiddee,, WWhhoo ffiinnddss tthhee ggrroooommss ffoorr tthhee bbrriiddeess..

TToo tthhee oonnllyy OOnnee,,

WWhhoo lleett yyoouu hhaavvee aa ddrroopplleett ffrroomm HHiiss sseeaa,, WWhhoo lleett yyoouu ddrriinnkk hhoonneeyy ffrroomm HHiiss bbeeee..

TToo tthhee oonnllyy OOnnee,,

WWhhoo wwaass tthhee bbeeggiinnnniinngg,, WWhhoo wwiillll bbee tthhee eenndd,, WWhhoo wwiillll ddeecciiddee wwhheetthheerr II wwiillll bbee iinn HHeeaavveenn oorr HHeellll,,

WWhhaatteevveerr nnaammee yyoouu ggiivvee HHiimm,, AAssiimm!! II kknnooww oonnee tthhiinngg ffoorr ssuurree,, HHee iiss tthhee oonnllyy OOnnee..

Page 6: Oracle 10g Made Simple

6

Page 7: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

7

About the Author Mr. Abbasi is President and CEO of Takveen: a 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 software and tons of code from programming microcontrollers using Assembly language to writing 3-tier multi-language web applications. He did M.S. in Biomedical Informatics from University of Medicine & Dentistry of New Jersey (www.umdnj.edu) and 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 engineering professor, “Think yourself ….”

Page 8: Oracle 10g Made Simple

8

Page 9: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

9

Acknowledgements First, I am really thankful to God and I always remember Him as “Supreme Programmer & Engineer”. 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 kids: Mateen & Abdul-Wadud for their encouragement to let me work on this book even during the time which I should have spent with them. I also want to thank my brother: Atif Abbasi and sister: Assiya Wasti for providing support, suggestions & technical help whenever I needed. Finally, I am thankful to all the wonderful instructors, professors, scholars, students and friends I had for their support and encouragement.

Page 10: Oracle 10g Made Simple

10

Page 11: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

11

Table of Contents Chapter 1: ................................................................................ 13 Visualizing the Complete Oracle Environment Chapter 2: ................................................................................ 21 SQL: Structured Query Language Chapter 3: ................................................................................ 89 Oracle Database Concepts Chapter 4: .............................................................................. 105 Oracle Instance Concepts Chapter 5: .............................................................................. 123 Oracle in Action Chapter 6: .............................................................................. 135 Complete Oracle System Design: Steps of Implementation Chapter 7: .............................................................................. 159 Oracle Database Design Chapter 8: .............................................................................. 211 Oracle Network Administration Chapter 9: .............................................................................. 241 Oracle Database Management Chapter 10: ............................................................................ 269 Oracle Backup & Recovery Techniques Chapter 11: ............................................................................ 349 Oracle Performance Tuning Index ..................................................................................... 377

Page 12: Oracle 10g Made Simple

12

Page 13: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

13

Chapter 1:

Visualizing the Complete Oracle Environment What is Oracle? 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 system, Oracle Instance gets alive and waits for users information/data related commands to fulfill, as it is a magnificent “Data Management Genie”.

Page 14: Oracle 10g Made Simple

14

Figure1-1: The complete Oracle system: Oracle Instance and Oracle

Database. The Oracle Database is basically Genie’s area to write information and to make the changes permanent on the hard disk.

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

Page 15: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

15

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 notebook to make things permanent otherwise we will forget. Physical Architecture of Oracle database 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) get 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.

Figure 1-2: Physical Architecture of Oracle database. Database consists

mainly of three different types of files.

Page 16: Oracle 10g Made Simple

16

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 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. How Oracle works? 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.

Figure 1-3: Oracle Instance ~ Users Interactions. Users send SQL

commands to the Genie. The Genie listens users from any corner of globe as long as the communication language is SQL.

In Oracle world each connected user with oracle server is considered as session. If there are three connected users with

Page 17: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

17

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 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. 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 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.

Page 18: Oracle 10g Made Simple

18

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 Oracle Instance writes the information and is encrypted. Users from all over the world 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. Things to Remember Before Moving Ahead

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.

4) Oracle Database is encrypted and we cannot read it through any Text Editor like MS Word.

5) SQL commands are used to store and retrieve information.

6) Each connected user with Oracle Instance is considered

as “Session”

Page 19: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

19

7) Never forget the concept of following three terms

o Instance o Database o Session

8) Following analogies help you in building concepts

Instance = Genie Database = Notebook Session = Aladdin (or connected Users)

9) Users can connect to Oracle server independent of their location.

10) Oracle Server: When we talk about Oracle Instance &

Oracle Database collectively we use the word Oracle Server.

Page 20: Oracle 10g Made Simple

20

Page 21: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

21

Chapter 2:

SQL: Structured Query Language What is SQL? 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 widely and sometimes few people gets confused. These are SQL, PL/SQL and SQL*Plus. SQL as I already told you is 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. 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

Page 22: Oracle 10g Made Simple

22

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.

Figure 2-1: Three important terms: SQL, PL/SQL and SQL*Plus.

How to access SQL*Plus? This application is available after you install the Oracle software. We will learn the installation of Oracle software later in this book. Once you have installed the software, you can start SQL*Plus by entering the following command: sqlplus username/password The application lies under $ORACLE_HOME/bin directory. What is iSQL*Plus? This application is available after you install the Oracle software. We will learn the installation of Oracle software later in this book. iSQL*Plus is the exact same product as that of SQL*Plus

Page 23: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

23

except that it’s the web version of SQL*Plus. It can be accessed with a URL having following pattern http://machine_name:5560/isqlplus Before accessing this URL, execute the following command which will start the iSQL*Plus application server. isqlplusctl start What is RDBMS? I would like to discuss over here are 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 databases 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. Once you see a RDBMS database product 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. 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 Large Organization/Enterprise :: Oracle 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

Page 24: Oracle 10g Made Simple

24

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 should not insert date or numeric value in it. We 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 on them e.g. If you assign UNIQUE constraint on any column then you would not be able to insert any value in it which is already there. Constraints help in maintaining the data integrity of the system.

Figure 2-2: Table Showing Records/Rows And Fields/Columns

Page 25: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

25

What are SQL Statements/Commands? SQL is nothing but a set of statements (commands) 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 falling in each of these categories are shown in the following table.

DQL SELECT DML DELETE, INSERT, UPDATE DDL CREATE, DROP, TRUNCATE, ALTER TCL COMMIT, ROLLBACK, SAVEPOINT DCL GRANT, REVOKE

Figure 2-3: SQL Statements/Commands categorization.

Once we finish up with SQL you will say to yourself, “Oh! That was all”. Let’s look at the following example. SELECT name, phone, city FROM address_book; Anyone knowing English language can easily imagine what the output of this statement will be. It will be three fields with all the records from address_book table. So you completed your first SQL statement. How to use the SELECT Statement/Command? 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;

Page 26: Oracle 10g Made Simple

26

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.

Figure 2-4: The SELECT statement. It’s used to query or retrieve

information from the database.

Page 27: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

27

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. 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.

Page 28: Oracle 10g Made Simple

28

Figure 2-5: SQL Operators grouped together into four groups.

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 the records rather 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

Page 29: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

29

ALL can be best understood by 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 you want to perform some arithmetic operation. The thing to remember over her is, although there is something “order of precedence” but it’s 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 your 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

Page 30: Oracle 10g Made Simple

30

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; 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 as follows.

Page 31: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

31

SELECT * FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30); By having NOT before IN can completely invert the result 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. 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 and all the records, only if the query after EXISTS results in at least one record.

Page 32: Oracle 10g Made Simple

32

Example: SELECT sal FROM emp WHERE ename LIKE 'SM%'; The output will be only those salaries from emp table where ename 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. That one character can be any alphanumeric literal. 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.

Page 33: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

33

SQL built-in functions 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 states 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.

Figure 2-6: SQL built-in functions are divided into two categories.

Page 34: Oracle 10g Made Simple

34

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.” Character Functions: Following are the functions that fall under this category.

CHR LTRIM INSTR ASCII RTRIM INSTRB CONCAT TRIM LENGTH INITCAP REPLACE LENGTHB LOWER SOUNDE

X

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:

Page 35: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

35

ASCII('Q') ---------- 81

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

Page 36: Oracle 10g Made Simple

36

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;

Output:

Result -------- 1234567

Page 37: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

37

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

Example:

SELECT ename FROM emp WHERE SOUNDEX(ename) = SOUNDEX('SMYTHE');

Output:

ENAME ---------- SMITH

Page 38: Oracle 10g Made Simple

38

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.

Figure 2-7: Google website with “Did you mean” feature.

Example:

SELECT SUBSTR('SPIDERMAN',7,3) "Result" FROM DUAL; 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;

Page 39: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

39

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.

SELECT INSTRB('CORPORATE FLOOR','OR',5,2) "Result" FROM DUAL; Output:

Result -------- 27

Example:

SELECT LENGTH('SPIDERMAN') "Result" FROM DUAL;

Page 40: Oracle 10g Made Simple

40

Output:

Result -------- 9

Similarly we can use LENGTHB; for a single-byte database character set, LENGTHB is equivalent to LENGTH. Let’s suppose a double-byte database character set.

SELECT LENGTHB ('SPIDERMAN') "Result" FROM DUAL; 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';

Page 41: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

41

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

Example:

SELECT MONTHS_BETWEEN(SYSDATE, 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;

Page 42: Oracle 10g Made Simple

42

Output:

New Year --------- 01-JAN-92

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

Page 43: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

43

Example:

SELECT CEIL(25.7) "Result" FROM DUAL;

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;

Page 44: Oracle 10g Made Simple

44

Output:

Round ---------- 30

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;

Page 45: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

45

Output:

Modulus ---------- 3

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

Page 46: Oracle 10g Made Simple

46

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

Page 47: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

47

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

Example:

SELECT ename, VSIZE (ename) "BYTES" FROM emp WHERE deptno = 10; Output:

ENAME BYTES ---------- ---------- CLARK 5 KING 4 MILLER 6

Page 48: Oracle 10g Made Simple

48

Group Functions A group function as the same states gets implemented on more than one record within a column. They can be better understood by looking at their real world examples. There are following five very important group functions.

AVG COUNT MAX MIN SUM

Example:

SELECT AVG(sal) "Average" FROM emp;

Output:

Average ---------- 2077.21429

Using AVG function you can get the average of “sal” (salary) column/field. Example:

SELECT COUNT(*) "Total" FROM emp;

Output:

Total ---------- 18

Page 49: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

49

Using the COUNT function you can count of number of records in the table. Example:

SELECT MAX(sal) "Maximum" FROM emp;

Output:

Maximum ---------- 5000

Using the MAX function we can get the maximum value within that column/field. 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

Page 50: Oracle 10g Made Simple

50

Sub-Query (also known as Nested Query) 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 the 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.

Figure 2-8: Query inside another query or Sub queries. 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.

Page 51: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

51

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 on 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.

Page 52: Oracle 10g Made Simple

52

What are SQL Joins? 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 it’s 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

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;

Page 53: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

53

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 TURNER works for BLAKE ADAMS works for SCOTT JAMES works for BLAKE MILLER works for CLARK

Cartesian Product If in the Join 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. Equijoin and Outer Join 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. Let’s take a example of two table Equijoin query like the one shown in the Figure 2-9, only those records will be displayed from either of two tables

Page 54: Oracle 10g Made Simple

54

where there is an exact match between the columns used in the WHERE clause.

Figure 2-9: Joining two or more tables. There are two very important

joins: Equijoin and Outer-join.

Example: SELECT ename, job, dept.deptno, dname FROM emp, dept WHERE emp.deptno = dept.deptno; 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.

Page 55: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

55

Figure 2-10: Equijoin/Simple Join/Inner Join. The equality sign is used

to join two tables.

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

Page 56: Oracle 10g Made Simple

56

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.

Figure 2-11: Outer join: The plus (+) sign is used to join two tables. 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. Positive sign (+) will be placed with the column of the table having least number of

records, in the WHERE clause.

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 records 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 join is very simple. First create a Equijoin query and then place the positive

Page 57: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

57

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 Figure 2-11; the one shown in the output table. These order dates are NULL because there were no supplier ids 10002 & 10003 in the orders table. UPDATE, INSERT & DELETE Statements 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 use the INSERT statement and if you want to delete any record or more than one record we use the DELETE statement.

Figure 2-12: Other DML Statements. If you forget to mention the WHERE clause in the UPDATE statement, all the values in that

column will get update. While inserting new values in the table the order of columns should be kept in mind otherwise you may get a type

mismatch error.

Page 58: Oracle 10g Made Simple

58

Example:

UPDATE emp SET comm = NULL WHERE job = 'TRAINEE';

Example:

INSERT INTO dept VALUES (50, 'PRODUCTION', 'SAN FRANCISCO');

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;

Page 59: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

59

CREATE TABLE, DROP TABLE Statements 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 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.

Figure 2-13: CREATE/DROP TABLE Statement.

Page 60: Oracle 10g Made Simple

60

Figure 2-14: Organizational Chart. Showing chief’s Schema. Each user we create in Oracle is considered as a Schema. Each object created by user lies under his/her schema. DBA is the owner of all the schemas

and hence all the objects within each of these schemas.

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.

Page 61: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

61

If you look in the Figure 2-13, especially on the syntax of CREATE TABLE statement, there is something mentioned “datatype” besides table name (which will be the name of the table that you want to create) and the 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 each 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 let’s 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 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.

Page 62: Oracle 10g Made Simple

62

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.

ROWID

Base 64 string representing the unique address of a record/row in the table.

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. 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.

Page 63: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

63

ALTER TABLE Statement 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 Figure 2-15.

Figure 2-15: Altering the table structure: The ALTER TABLE

statements. Certain modifications using ALTER TABLE statement are not possible if you are already having the data inside that table. One way of getting rid of unwanted column or unwanted data is to utilize

the power of CREATE TABLE AS statement.

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.

Page 64: Oracle 10g Made Simple

64

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 and then drop the original table. Constraints also known as Data Integrity Constraints While creating tables, besides mentioning about data types of columns we can also 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 get 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. 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) );

Page 65: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

65

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.

Figure 2-16: Data Integrity Constraints or simply Constraints. Oracle

Instance verifies constraints before accepting any value from user. 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. Oracle creates an implicit index for a column having Primary key constraint on it. Index helps in speeding up the search process just like the index at the end of a book. Referential

Integrity constraint also known as PRIMARY/FOREIGN KEY relationship between two or more tables results in two thing: (1)

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. (2) Cannot update/insert anything in child’s table FOREIGN KEY column with no corresponding value

in parent table PRIMARY KEY column

Page 66: Oracle 10g Made Simple

66

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 that we can disable/enable the constraint using the ALTER TABLE statement if the constraint name is created e.g. 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 it’s 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 learn this later in this book. If we are sure that this data is already checked for uniqueness as its coming from table already having UNIQUE constraint on the column so there is no need for Oracle to

Page 67: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

67

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 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 to 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 that before inserting or updating any information into this suppliers table, 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. Let’s now talk about Primary Key constraint. Once you implement this constraint on any column, you will not be able to insert duplicate and NULL value i.e. each value in that column

Page 68: Oracle 10g Made Simple

68

will be a unique identifier for that whole record/row. Moreover Oracle creates an implicit index on that column. Index created by Oracle on any column of a table is having the same analogy as that 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 anything 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 clause) and there are bright 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 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

Page 69: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

69

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.

• 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.

Page 70: Oracle 10g Made Simple

70

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.

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 also say that you have implemented RI constraint between dept_test and emp_test.

Page 71: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

71

Figure 2-17: Two beauties of Oracle i.e. Data Integrity and Data

Consistency. Having a clear concept about the following two terms is really essential because these two terms are widely used in all RDBMS.

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 if it is an enterprise wide system, users from all over the world will interact 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 you would not be having all these different kinds of constraints, then there would be lots of redundancy of information, lots of errors etc. It’s like filling a form online and you are allowed to enter date of birth in the zip code field. In short all these constraints available in Oracle, help 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 everyone 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

Page 72: Oracle 10g Made Simple

72

visible to everyone once committed by end users using the COMMIT command. What is the difference between Joining Tables & Linking Tables? Like I said before, all the joins techniques we have learnt before viz., Outer Join, Equijoin etc. are at the query level and can be implemented 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 those two or more tables.

Figure 2-18: Difference between Joining and Linking. Joining is at the

query level whereas linking is a physical link between tables. Joins statements can be executed on tables having Referential Integrity

constraint or not. The word “Join” should not be confused with as I if you are joining the two tables permanently.

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. 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

Page 73: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

73

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”. Other Database Objects: Views, Indexes, Sequences etc. 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 the information that we want others to have access.

Figure 2-19: Managing other database objects: Views, Indexes,

Sequences, Synonyms. Once you drop a VIEW, base tables and views comprising the dropped view will not get deleted. 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. Sequences are like auto-number objects. You can always get the next number and

insert it in any number data-type column, usually id kind of field e.g. emp_id.

Page 74: Oracle 10g Made Simple

74

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 to creating tables, the only difference is we use CREATE VIEW statement instead of CREATE TABLE statement. 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, 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.

Page 75: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

75

Next we would like to talk about the Indexes. We have seen previously that an index gets created whenever you create a PRIMARY KEY constraint on any column of a table, implicitly. 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 lines 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 that we will be using a lot in the 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 or NID (National Identity) Card office, it’s 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. 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 and both of 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 the size of implicit table that Oracle will create. So creating indexes on all the columns of all the table inside the database will tremendously increase the size of the database and

Page 76: Oracle 10g Made Simple

76

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. Example:

ALTER INDEX m1_idx RENAME TO m2_idx; This statement will rename the index to m2_idx. 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 do not have to remember what id number we should give to newly hired employee. Just ask the sequence for next value and it provide

Page 77: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

77

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 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', ‘[email protected]' );

Example:

SELECT emp_seq.CURRVAL FROM dual;

You can also find out the current value of the sequence using CURRVAL method.

Page 78: Oracle 10g Made Simple

78

Example:

ALTER SEQUENCE emp_seq MAXVALUE 1500;

We can also alter the structure of the already exisiting sequence in the database 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. Synonym 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. Example:

CREATE PUBLIC SYNONYM employees FOR hr.employees@sales;

Page 79: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

79

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 thinking that I haven’t discussed something like ALTER SYNONYM. Actually, there is no such statement. If you want to alter synonym just recreate it by first dropping it and then using CREATE SYNONYM statement. CREATE/ALTER USER, GRANT/REVOKE Statements 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. It’s 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. To create a new user (schema) you should login to Oracle Instance using one of the DBA’s account and then use the CREATE USER statement to create new user.

Page 80: Oracle 10g Made Simple

80

Figure 2-20: Security management: Managing users, privileges and

roles. Users can be authenticated by the database or the OS. Privileges can be assigned to users and roles.

Example: CREATE USER asim IDENTIFIED BY evergreen DEFAULT TABLESPACE user_demo; This statement will create a new user with the login as asim and password as evergreen and whatever objects (tables, views etc.) that user asim 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

Page 81: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

81

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$asim

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 asim

IDENTIFIED EXTERNALLY; Example:

ALTER USER asim IDENTIFIED BY black123;

Or,

ALTER USER asim DEFAULT TABLESPACE hr_data;

To change the password of asim 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 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

Page 82: Oracle 10g Made Simple

82

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 a month change of business rule comes up and it’s described that those 35 HR folks 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; A role is created with the password. It 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 role. Once we have created the role, next thing is to assign this role.

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 application.

Page 83: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

83

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. Figure 2-21: Object privileges and corresponding database objects.

The way to interpret this table is, if you keep the above example in your mind, you can grant ALTER, DELETE object privileges 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.

Cluster

CREATE CLUSTER CREATE ANY CLUSTER ALTER ANY CLUSTER DROP ANY CLUSTER

Database ALTER DATABASE ALTER SYSTEM AUDIT SYSTEM

Table

CREATE TABLE CREATE ANY TABLE ALTER ANY TABLE DROP ANY TABLE SELECT ANY TABLE UPDATE ANY TABLE DELETE ANY TABLE INSERT ANY TABLE LOCK ANY TABLE

Page 84: Oracle 10g Made Simple

84

Sequence

CREATE SEQUENCE CREATE ANY SEQUENCE ALTER ANY SEQUENCE DROP ANY SEQUENCE SELECT ANY SEQUENCE

Synonym

CREATE SYNONYM CREATE ANY SYNONYM CREATE PUBLIC SYNONYM DROP ANY SYNONYM DROP PUBLIC SYNONYM

Session CREATE SESSION ALTER SESSION

Tablespace

CREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE MANAGE TABLESPACE UNLIMITED TABLESPACE

User

CREATE USER ALTER USER BECOME USER DROP USER

View CREATE VIEW CREATE ANY VIEW DROP ANY VIEW

Index CREATE ANY INDEX ALTER ANY INDEX DROP ANY INDEX

Rollback Segment

CREATE ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT DROP ROLLBACK SEGMENT

Figure 2-22: System privileges with corresponding category.

Besides these are system privileges for PL/SQL functionalities like CREATE PROCEDURE, CREATE ANY PROCEDURE, EXECUTE ANY PROCEDURE etc.

Page 85: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

85

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.

SYSDBA

Create new database Startup, Shut down database Alter database with the OPEN, MOUNT, BACKUP, CHANGE CHARACTER SET, ARCHIVELOG and RECOVER options Create SP file

SYSOPER

Startup, Shut down database Alter database with the OPEN, MOUNT, BACKUP, ARCHIVELOG and RECOVER options Create SP file

Figure 2-23: Two very important system privileges with corresponding privileges.

Example:

CREATE ROLE hr_emps; GRANT SELECT, UPDATE ON emp_test TO hr_emps; GRANT hr_emps TO margorie, daisy, jessie, semper;

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.

Page 86: Oracle 10g Made Simple

86

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. 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 let’s see how we can create profile. Example:

CREATE PROFILE paramod LIMIT CONNECT_TIME UNLIMITED;

Or,

ALTER PROFILE sidney LIMIT CONNECT_TIME 240;

Page 87: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

87

When the CONNECT_TIME value will exceed Oracle will rollback the current transaction and then will end the session. Example:

CREATE PROFILE hr_dept LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED;

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. Administration User Accounts Provided by Oracle There are some users accounts built-in Oracle. The administrative accounts provided by Oracle are given below. These accounts are by default locked initially. Database administrators can unlock these accounts. Among all these accounts SYS and SYSTEM are necessary for basic functioning or Oracle database. CTXSYS: Oracle Text user DBSNMP: Enterprise Manager Management Agent MDDATA: Oracle Spatial account MDSYS: Oracle Spatial account

Page 88: Oracle 10g Made Simple

88

DMSYS: Oracle Data Mining account. DMSYS performs data mining operations. OLAPSYS: Oracle OLAP account. It owns the OLAP Catalog. ORDPLUGINS: Oracle interMedia account ORDSYS: Oracle interMedia administration account OUTLN: Perfomance tuning account to store information to support plan stability SCOTT: Sample database schema. SYS: This account is used to perform database administrative tasks. The default password of this account is CHANGE_ON_INSTALL. SYSMAN: This account is used to perform Oracle Enterprise Manger database administrative tasks. SYS and SYSTEM are having the same power to perform such tasks. The default password of this account is CHANGE_ON_INSTALL. SYSTEM: Another account for performing database administrative tasks. The default password of this account is MANAGER. Things to Remember Before Moving Ahead

1) Understanding the difference between three terms: SQL, PL/SQL, SQL*Plus.

2) Oracle Instance receives these commands from connected users.

Page 89: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

89

Chapter 3:

Oracle Database Concepts What is Physical & Logical Architecture of Oracle Database? 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.

Page 90: Oracle 10g Made Simple

90

Figure 3-1: The complete Oracle system i.e. Oracle Instance and Oracle Database. Visualize Oracle Instance as Genie and Database as Genie’s Notebook, which he uses to remember information for longer period of

time. Oracle database has a logical architecture and a physical architecture.

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 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

Page 91: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

91

when are talking about physical files like control file, data files etc., we are actually talking about physical architecture of Oracle database. Physical Architecture of Oracle Database 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.

Figure 3-2: Physical Architecture of Oracle database. Oracle database is composed of mainly three different types of files. Oracle Instance

updates the control file whenever the physical structure of database is changed by DBA. 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. Redo Log files get

utilized in a circular fashion. It is recommended that Oracle should be run under “Archived Log Mode” so that Redo Log files get copied

before getting overwritten. Redo Log files along with Archived Redo Log files plays a major role in the database recovery process.

Page 92: Oracle 10g Made Simple

92

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. 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.

Main Oracle Database Files. Control File Data Files Redo Log Files

Oracle Instance reads it at startup.

Parameter File (init.ora)

Archiving of Redo Log Files Archived Redo Log Files

Figure 3-3: Oracle physical files on the disk drive(s).

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.

Page 93: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

93

Redo Log Files & Archived Redo Log Files: Redo Log files are the files that maintain 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 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 this topic in great detail in the last article 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 oracle system, the first thing that gets erected is Oracle Instance. How the memory structure would be for that instance, that’s what we define in parameter file.

Page 94: Oracle 10g Made Simple

94

Logical Architecture of Oracle Database 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 your 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 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.

Page 95: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

95

Figure 3-4: Logical architecture of Oracle database. Tablespace is like small departmental level database. 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. 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. Each Segment is composed of

Extents and extents are nothing but contiguous DB Blocks. DB Block is usually the even multiple of OS Block and its value is specified in

parameter file (init.ora).

Page 96: Oracle 10g Made Simple

96

Physical & Logical Architecture Relationship Figure 3-5 gives a side by side relationship 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.

Figure 3-5: Relationship between Physical and Logical architecture of Oracle database. Tablespace is a name/alias given to a group of one or more data files. Data inside the tablespace reside in the data files which are physical files like all other files located on your computer. Size of the tablespace and hence the size of database is not limited to the OS

marked limit on the file size.

Tablespaces are like small departmental level databases within 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 be more than the Operating System maximum

Page 97: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

97

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.

Figure 3-6: Relationship between Physical and Logical architecture of

Oracle database. Tablespace relates of data files only.

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.

Page 98: Oracle 10g Made Simple

98

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. 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 Figure 3-7. Whenever you create a database object, Oracle Instance allocates a segment in the tablespace assigned to your schema. With the Figure 3-7, 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 Figure 3-7, 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) is distributed among two data files.

Page 99: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

99

Figure 3-7: Relationship between Physical and Logical architecture of

Oracle database. One object (e.g. table) can be in two or more data files but only under one tablespace. 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. Segments can be sitting under two or more data files under the same tablespace. Tablespace is nothing but

just an alias given to the group of data files or data file.

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.

Page 100: Oracle 10g Made Simple

100

Some Tablespaces in the Oracle Database Every Oracle database should have following tablespaces. SYSAUX This is an auxiliary tablespace to the SYSTEM tablespace. It is a mandatory tablespace and cannot be dropped or renamed. Components that use this tablespace as their default tablespace are Enterprise Manager Repository, Automatic Workload Repository, Oracle Streams, Oracle Text, XML DB, Recovery Catalog, Scheduler, Statspack etc. SYSTEM This tablespace is used by Oracle to manage the database. It’s always created at the time of creation of database. It contains data dictionary and other tables, views containing database administrative information e.g. dynamic performance base tables etc. UNDOTBS1 This tablespace is used by Oracle Instance to store undo information. Every database must have this tablespace and can be created at the time of creation of database. TEMP This tablespace holds the data for temporary period of time e.g. during processing sort operations. Every database should have TEMP tablespace and is assigned to database users. In a preconfigured Oracle database structure, TEMP tablespace is created as default temporary tablespace. It means that in case you do not assign any temporary tablespace to database users, Oracle Instance assign this as temporary tablespace. EXAMPLE This tablespace contains the sample schemas. These sample schemas contain tables and other objects used as examples in Oracle documentation and other educational material.

Page 101: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

101

USERS This tablespace is used to store users’ data permanently. Like TEMP tablespace, every database should have this tablespace otherwise users’ data will be saved in SYSTEM tablespace and this does not fall under Oracle best practices guidelines. Redo Log Files 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. 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 Figure 3-8, Oracle Instance (or more precisely, the Log Writer process) writes these changes in data in 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.

Page 102: Oracle 10g Made Simple

102

Figure 3-8: Redo log files’ utilization in action. Redo log files get

utilized in a circular fashion. A database should have at least two Redo Log groups. Each Redo Log group should have two or more redo log files called “members”. Redo Log files get utilized by Oracle Instance in a circular fashion. Redo Log files and Archived Redo Log files play a great role in Oracle Database recovery in times of any kind of failure.

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.

Page 103: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

103

Things to Remember Before Moving Ahead

1) Figure 3-2: Physical Architecture of Oracle database. Oracle database is composed of mainly three different types of files. Oracle Instance updates the control file whenever the physical structure of database is changed by DBA. 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. Redo Log files get utilized in a circular fashion. It is recommended that Oracle should be run under “Archived Log Mode” so that Redo Log files get copied before getting overwritten. Redo Log files along with Archived Redo Log files plays a major role in the database recovery process.

2) Figure 3-4: Logical architecture of Oracle database. Tablespace is like small departmental level database. 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. 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. Each Segment is composed of Extents and extents are nothing but contiguous DB Blocks. DB Block is usually the even multiple of OS Block and its value is specified in parameter file (init.ora).

3) Figure 3-7: Relationship between Physical and Logical architecture of Oracle database. One object (e.g. table) can be in two or more data files but only under one tablespace. 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. Segments can be sitting under two or more data files under the same tablespace. Tablespace is nothing but just an alias given to the group of data files or data file.

Page 104: Oracle 10g Made Simple

104

4) Figure 3-8: Redo log files’ utilization in action. Redo log

files get utilized in a circular fashion. A database should have at least two Redo Log groups. Each Redo Log group should have two or more redo log files called “members”. Redo Log files get utilized by Oracle Instance in a circular fashion. Redo Log files and Archived Redo Log files play a great role in Oracle Database recovery in times of any kind of failure.

Page 105: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

105

Chapter 4:

Oracle Instance Concepts What is Oracle Instance? 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 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.

Page 106: Oracle 10g Made Simple

106

Figure 4-1: The complete Oracle system i.e. Oracle Instance and Oracle

database. The background processes and memory architecture constitute the Oracle Instance.

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. 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 things I want to give you the analogy of the way human brain. Human brains works pretty much the same way Oracle Instance works.

Page 107: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

107

Figure 4-2: What is Oracle Instance? The memory architecture and

background processes constitute an instance. Human brain 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”. 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.

Page 108: Oracle 10g Made Simple

108

Figure 4-3: The logical architecture of Human brain. Working of

Oracle Instance resembles with the working of Human Brain.

The sources of input to the Brain are our five senses similarly the sources of input 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 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 somewhere”. 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”.

Page 109: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

109

Figure 4-4: Physical architecture of Human Brain.

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 much 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: RAM inside the computer if we already have hard drives? It’s because the speed with which

Page 110: Oracle 10g Made Simple

110

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 every day 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.

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.

Figure 4-5: Study of Human Brain working can really help us in visualizing Oracle Instance and how it works.

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.

Page 111: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

111

What is Oracle Instance Memory Architecture? 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 let’s 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.

Figure 4-6: Memory architecture of Oracle Instance. It’s the area of the

computer memory (RAM) occupied by Oracle Instance for requests processing. Every software that you run under any OS occupies RAM (or Memory), so does Oracle. SGA is the most important piece and it

stands for System Global Area. Non-shared memory is not shared among all the users whereas shared is shared among all. Database

Buffer Cache has three sub-caches: KEEP, RECYCLE, DEFAULT. Three different states of buffers within Database Buffer Cache: Dirty

Buffers, Free Buffers, Pinned Buffers. Non-Shared part of Oracle

Page 112: Oracle 10g Made Simple

112

memory architecture is also called PGA or Program Global Area. The utilization of PGA depends how you configure the Oracle Server.

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. Oracle Server can be configured to run as Dedicated

Server mode or Shared Server mode.

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 Figure 4-6. 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.

Page 113: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

113

Figure 4-6: Memory architecture of Oracle Instance. It’s the area of the

computer memory (RAM) occupied by Oracle Instance for requests processing.

Page 114: Oracle 10g Made Simple

114

SGA has three mandatory areas and two optional areas as shown in Figure 4-6. Optional area means you can have it if the requirement arises. In mandatory areas we have, Shared Pool, Database Buffer Cache and Redo Log Buffer Cache whereas in optional areas we have Large Pool and Java Pool. Shared Pool is utilizes for SQL requests coming from the connected users, PL/SQL objects execution, data dictionary views, locks and so on. But the main purpose is SQL, PL/SQL, locking & data dictionary that’s how you can remember. There is a special area inside Shared Pool that deals with SQL and PL/SQL, is called the Library Cache. If one user has executed the SQL statement that statement will get parsed and complied utilizing this area. If someone else has submitted the same SQL, it will be used from this area pre parsed and complied. So the time it takes to execute the second SQL statement will be much less compared to the first one. The “Data Dictionary Cache” holds the most recently used database dictionary information. Data Dictionary is basically the information about the data inside the database or in other words metadata in the form of tables and view about the database. Oracle uses it at the time of parsing of SQL statement. The size of shared pool can be adjusted dynamically using SHARED_POOL_SIZE of init.ora file. Database Buffer Cache holds the DB Blocks recently read from the data files. Database Buffer Cache has further three sub-caches. One is called KEEP, second one is RECYCLE and the third one is DEFAULT. In KEEP, DB blocks will be retained in the RAM and will not get aged out. Oracle Instance will remove stuff palced in RECYCLE from the RAM as soon as they are not needed. DB Blocks without any assigned attribute (KEEP or RECYCLE) are placed in the DEFAULT buffer pool. Two init.ora parameters I really like to mention over here that are related to KEEP and RECYCLE are DB_RECYCLE_CACHE_SIZE and DB_KEEP_CACHE_SIZE. We will see the init.ora file and specially its application in chapters ahead.

Page 115: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

115

Within whole Database Buffer Cache, there lie three different types of buffers or in other words three different states of buffers. These three states are, Dirty Buffers, Free Buffers and Pinned Buffers. Buffers that needs to be written to the data files are marked dirty and hence got the name Dirty Buffers. Once written to the data files they are available to be over-written or those, which never had any data, are called Free Buffers. Buffers that are currently being accessed or those that are explicitly marked for future use, are called Pinned Buffers e.g. KEEP buffer pool. Redo Log Buffer Cache holds the information about the changes that are being made to the database. Any change that you or connected users make using any DML (INSERT, UPDATE, DELETE) or DDL (CREATE, ALTER, DROP) statement will get recorded in this part of the RAM or in other words SGA. The parameter that determines the size of Redo Log Buffer is LOB_BUFFER. Large Pool is the optional area of SGA and can be requested as needed. Its size can be adjusted using LARGE_POOL_SIZE parameter inside init.ora file and can be dynamically altered using ALTER SYSTEM statement. Large Pool is optionally required for specific database operation like backup or restore to avoid contention with rest of the good stuff of SGA. Java Pool is another optional area and can be requested to provide memory for java objects within Oracle database. Ever since Sun Microsystems’s collaboration with Oracle, we can now create and store pre-complied Java programs as database objects within the Oracle database and are treated the way other objects are treated inside the database e.g. Java object created by you or in other words under you schema will not be accessible to anyone else unless you grant access. The Non-Shared part of memory is called PGA (Program Global Area) and contains the data and control information for a server process. The information in PGA depends on the server configuration. Oracle can be configured to run as dedicated

Page 116: Oracle 10g Made Simple

116

server process or shared server process. In dedicated server process we have one server process per session whereas we in a shared server process we have multiple sessions served by one server process. We will learn in detail regarding it later in this book. Stack space in the PGA is utilized by server process to hold variables, arrays and other useful information pertaining to connected session. Unlike SGA, which is shared by several background processes, PGA is an area for the server process utilization and utilized for sort operations, containing information pertaining to session and stack space for variables and arrays. Oracle Server can be configured to run under Shared Server mode or as Dedicated Server mode. The Figure 4-7 shows Oracle Instance working under Shared Server configuration. The beauty of shared server configuration is that a single server process handles multiple sessions and hence the idle time of server process reduces.

Figure 4-7: Background processes of Oracle Instance. Oracle Instance running under Shared Server Mode is shown. RECO, LGWR, SMON,

PMON, ARCn etc. are all background processes. SGA is the shared part of memory architecture of Oracle. Oracle can be configured to run

as dedicated server mode or shared server mode.

Page 117: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

117

Figure 4-7: Background processes of Oracle Instance. Oracle Instance

running under Shared Server Mode is shown.

Page 118: Oracle 10g Made Simple

118

We will talk in detail regarding Figure 4-7 in the next chapter as it literally shows Oracle in action under shared server mode. In Figure 4-7 you can see pictorially the sentence we used to define oracle instance i.e. the background processes and memory architecture constitute the instance. LGWR (Log Writer Process), PMON (Process Monitor), SMON (System Monitor), ARCn (Archiver Process) etc. are all Oracle background processes and SGA in the center is the memory architecture of Oracle. So all these background process utilize the memory architecture (shared area) to fulfill requests of all the connected users or in other words Oracle Instance fulfills the requests of all the connected users. The Figure 4-8 shows the same thing as the previous one but here you might have noticed that we have less number of blocks, especially there is no Dispatcher process and no Request and Response Queue. This is because; here we are showing Oracle working in Dedicated Server mode.

Page 119: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

119

Figure 4-8: Background processes of Oracle Instance. Oracle Instance running under Dedicated Server Mode is shown. There would not be

any Request and Response Queues in a dedicated server configuration. There would not be any dispatcher process in dedicated server mode.

For each connected user then there would one dedicated server process. The idle time of server will be more but this configuration has the

highest performance factor.

We will talk in detail regarding both of these modes (Dedicated and Shared) and how Oracle system works, in the next chapter. If you have a clear understanding of concepts so far, in the next chapters many mysteries about Oracle that you had in your mind will unfold, as you will see Oracle in Action. In dedicated server mode, each connected user would be having a separate server process. Although this configuration would be having high idle server time as most of the time Server process would be doing nothing after fulfilling the single connected user request and waiting for next SQL statement to arrive. This configuration has high performance factor but it should only be utilized when you have plenty of system resources available.

Page 120: Oracle 10g Made Simple

120

Figure 4-8: Background processes of Oracle Instance. Oracle Instance

running under Dedicated Server Mode is shown.

Page 121: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

121

Things to Remember Before Moving Ahead

1) Figure 4-6: Memory architecture of Oracle Instance. It’s the area of the computer memory (RAM) occupied by Oracle Instance for requests processing. Every software that you run under any OS occupies RAM (or Memory), so does Oracle. SGA is the most important piece and it stands for System Global Area. Non-shared memory is not shared among all the users whereas shared is shared among all. Database Buffer Cache has three sub-caches: KEEP, RECYCLE, DEFAULT. Three different states of buffers within Database Buffer Cache: Dirty Buffers, Free Buffers, Pinned Buffers. Non-Shared part of Oracle memory architecture is also called PGA or Program Global Area. The utilization of PGA depends how you configure the Oracle Server. 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. Oracle Server can be configured to run as Dedicated Server mode or Shared Server mode.

2) Figure 4-7: Background processes of Oracle Instance. Oracle Instance running under Shared Server Mode is shown. RECO, LGWR, SMON, PMON, ARCn etc. are all background processes. SGA is the shared part of memory architecture of Oracle. Oracle can be configured to run as dedicated server mode or shared server mode.

3) Figure 4-8: Background processes of Oracle Instance. Oracle Instance running under Dedicated Server Mode is shown. There would not be any Request and Response Queues in a dedicated server configuration. There would not be any dispatcher process in dedicated server mode. For each connected user then there would one dedicated server process. The idle time of server will be more but this configuration has the highest performance factor.

Page 122: Oracle 10g Made Simple

122

Page 123: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

123

Chapter 5:

Oracle in Action How Oracle works in Shared Server Mode? You can run Oracle system in two modes: Shared Server Mode or Dedicated Server Mode. The Figure 5-1 depicts how Oracle system (Instance as well as database) works in the shared server mode. The Shared Server mode can be best visualized if you imagine a restaurant as shown in the Figure 5-2. There are two waitresses serving more people. So two waitresses are being shared by let’s suppose 10 people. In this case the “idle time” for each waitress will be less compared to the situation where we will be having one waitress per person. Similarly in a shared server mode we would be having less Server Processes serving greater number of connected users.

Page 124: Oracle 10g Made Simple

124

Figure 5-1: Background processes of Oracle Instance. Oracle Instance

running under Shared Server Mode is shown. Oracle two modes of operations: Shared Server, Dedicated Server. Utilizing Shared Server mode you can have least Idle Time but performance would not be as that of Dedicated Server mode. If system resources are not a problem keeping in mind the connected users, then always go with dedicated

server mode. Software application (e.g. MS Word) has GUI whereas a Software Process is independent of GUI and requires no user

interaction (e.g. LGWR). Depends on the way you program a Process, usually a process runs when certain event happens and re-runs if the event happens again. DBWR writes the dirty buffers from Database

Buffer Cache to the data files. LGWR writes the redo log buffers from Redo Log Cache to the redo files. Log Switch happens whenever

LGWR process finishes writing one Redo Log file and moves to the next one. LGWR process will start new ARCn process whenever ARCn

gets overloaded. PMON frees up the resources from a failed user process. SMON is responsible for Instance recovery, if necessary.

Page 125: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

125

Figure 5-1: Background processes of Oracle Instance. Oracle Instance

running under Shared Server Mode is shown.

Page 126: Oracle 10g Made Simple

126

Figure 5-2: Restaurant running under shared waitress mode. It is similar

as Oracle Instance running under Shared Server Mode.

One more thing that I like to mention here, in a restaurant environment, if it’s really busy, then you may have to wait unless someone leaves and you get the place to sit. So there will be a “waiting list” maintained by someone, as soon as you enter the restaurant that person will note down your name in the list and whenever there is a vacant place to sit and provided its your turn on the list, you will be directed to that vacant place. Similarly in Shared Server mode there is a dispatcher process, which receives the users requests and places it in the “Request Queue”. Server process “when it’s free”’ picks up the request from the request queue, processes it and put the response back in response queue. Dispatcher process “when it’s free” picks up the response from the response queue and sends it to the specific user who submitted that request. The point to be noted over here is that request and response queues are not processes. They are part of SGA or in other words part of memory utilized by processes. Whereas Server process and Dispatcher process are processes and are not the part of

Page 127: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

127

SGA. Whenever the word SGA comes, imagine as if we are talking about a big sheet of paper for rough work or rough calculations and whenever the word “process” comes, imagine as if we are talking about a “live” person with a assigned job or in other words person who has being assigned a specific job. The difference between “process” (e.g. Oracle Background Process like Dispatcher, Server Process, DBWR etc.) and “software application” (e.g. like MS Word, Excel etc.) is that you can or users can interact with the “software application” whereas a process is also a software but it has a pre-assigned task set by the “process developer” or computer programmer. Software process never allows users to interact and more precisely certain environmental events result in the cause of its execution. It re-executes if that event happens gain or terminates itself after executing once just like in the movie “Mission Impossible”. The mission is described to the team through a “system” which after completion of mission description destroys itself. It all depends on the programmer who designed or wrote the software code for the process. Similarly, Oracle background processes have been assigned a specific job. Each process gets executed under certain circumstances. If those circumstances happen again, the process gets executed again. DBWn DBWn or Database Writer process writes the contents of dirty buffers of Database Buffer Cache to the data files. When you start the database, Oracle starts one Database Writer process (DBW0). For situations where we have multiple users accessing the Oracle system, we can add nine more (DBW1 to DBW9) Database Writer processes. DBWn writes the contents of Dirty buffers of the Database Buffer Cache to the Data files under following circumstances or events. When the checkpoint occurs. Checkpoint occurs periodically or when “log switch” occurs. A log switch occurs when Oracle finishes writing one redo log file and moves to the next one.

Page 128: Oracle 10g Made Simple

128

When we place tablespace offline. When we drop or truncate table. When we change the tablespace to read only. Whenever the threshold mark of free buffers reaches. It’s the mark when the quantity of free buffers in database buffer cache drops to a certain level. LGWR Like I said before, redo log files gets written by Log Writer process (LGWR) in a circular fashion i.e. when a Log Writer process finishes writing the last redo log file, it will start writing or rather overwriting the first one. Whenever the Log Writer process switches from one file to another, “Log Switch” happens. When Log Switch happens, checkpoint happens, when checkpoint happens, DBWn writes the dirty buffers to the data files. The Log Writer process writes the “Redo Log Buffers” from the Redo Log Cache to the Redo Log files under following circumstances or events. Whenever we issue COMMIT statement to complete the transaction. Every three seconds LGWR writes to all the Redo Log members or mirror images simultaneously even if one of the member is damaged, LGWR will continue to write on the good ones. ARCn If we don’t want the Redo Log files to be overwritten by LGWR process then we have to run the database in ARCHIVELOG mode and we have to enable automatic archiving by setting LOG_ARCHIVE_START = True.

Page 129: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

129

Under this mode Archiver process (ARCn) become alive. ARCn process makes sure that the Redo Log files gets archived to the archived location before it gets overwritten by LGWR process. We can have as many as ten Archiver processes (ARC0 to ARC9). The LGWR process will start new ARCn process whenever current number of ARCn processes is insufficient to handle the workload. CKPT (Checkpoint) CKPT process updates the header of data files and control file. It’s a event that happens automatically and kicks the DBWR process to write the dirty buffers to data files. It also happens when the Log Switch happens. SMON, PMON SMON or System Monitor performs instance recovery, if necessary on system startup whereas PMON or Process Monitor frees up all the resources held by a user process whenever it fails. RECO RECO or Recoverer Process is a background process and used with distributed database configuration. It automatically resolves failures involved in distributed transactions. LCKn LCKn or Lock processes (LCK0 to LCK9) are processes and available in Oracle Real Application Cluster environment for inter-instance locking. Oracle RAC ( or we use to it Oracle Parallel Server) gives you the ability to have multiple instances interacting with the same database.

Page 130: Oracle 10g Made Simple

130

QMNn QMNn or Queue Monitor processes (QMN0 to QMN9) is an optional background process for Oracle Advanced Queuing and monitor the message queues. The init,ora parameter AQ_TM_PROCESSES specifies the number of queue monitor processes. Oracle Advanced Queuing gives the ability to distributed applications to communicate asynchronously using messages. Dnnn or Dispatcher Process(es) Dnnn or Dispatcher process is only available if you run Oracle system in Shared Server mode. It is prime job is to take the request from the connected user and place in the in the Request Queue. Server process when its free picks up the request from the request queue and put the response back in the “Response Queue” after processing the request. Dispatcher process when it’s free picks that response from the response queue and sends it back to the user who submitted that request. You can have multiple Dnnn processes for single Database Instance. Snnn or Shared Server Process(es) Snnn process works exactly the same manner like the Dedicated Server process except that the Shared Server processes utilizing the beauty of Dispatcher process and Request and Response Queue can server more than one user. The number of Shared Server processes can be controlled using two init.ora parameters, SHARED_SERVERS and MAX_SHARED_SERVERS. MMAN (Memory Manager) is a background process that manages the dynamic resizing of overall SGA memory areas as the workload increases or decreases.

Page 131: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

131

How Oracle works in Dedicated Server Mode? After studying Shared Server Mode of Oracle System, Dedicated Sever Mode is just piece a cake. In Dedicated Server mode there is neither Request/Response Queues nor any Dispatcher process. Whenever a user connects to Oracle Instance, one new Server process gets created to serve him/her.

Figure 5-3: Background processes of Oracle Instance. Oracle Instance running under Dedicated Server Mode is shown. Oracle running under Dedicated Server mode works the same as Shared Server mode except that a new server process gets created to serve the new logged in user.

Idle Time of Server process(es) will be more compared to Shared Server environment. For unlimited resources, always go with Dedicated

Server Mode otherwise stick with Shared Server Mode.

To better visualize a Dedicated Server mode, think of a very luxurious restaurant where they have one waiter dedicated for each new customer entering the restaurant as shown in Figure 5-4 and will stay with them all the time (waiting for their request) unless they leave the restaurant or the husband say to him, “Can you let me have some private discussion with my wife”. This is called the restaurant running under Dedicated Waiter (Server) environment.

Page 132: Oracle 10g Made Simple

132

Figure 5-3: Background processes of Oracle Instance. Oracle Instance

running under Dedicated Server Mode is shown.

Page 133: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

133

Figure 5-4: Restaurant running under dedicated waiter mode. It is similar to running Oracle Instance under Dedicated Server Mode.

If you are having unlimited resources available then to achieve ultimate performance always go with Dedicated Waiter (Server) mode otherwise stick with the Shared Server Mode. In real world the word “Resources” means money whereas in computer world this term stands usually for “RAM/Memory”. Rest of the processes works the same way like in case of Shared Server mode. In Dedicated server mode we have more server “idle time” or in other words server process doing nothing waiting for user request. Let me give you an idea how to find out which will work best for you, Shared Server or Dedicated Server. Each Dedicated Server takes approximately of 20MB of memory. If your system running Oracle have 1 GB of RAM available and your Oracle system needs to support 10 users and on the average of 7 concurrent users. Under this scenario always go with Dedicated Server Mode otherwise stick with Shared Server Mode.

Page 134: Oracle 10g Made Simple

134

Things to Remember Before Moving Ahead

1) Figure 5-1: Background processes of Oracle Instance. Oracle Instance running under Shared Server Mode is shown. Oracle two modes of operations: Shared Server, Dedicated Server. Utilizing Shared Server mode you can have least Idle Time but performance would not be as that of Dedicated Server mode. If system resources are not a problem keeping in mind the connected users, then always go with dedicated server mode. Software application (e.g. MS Word) has GUI whereas a Software Process is independent of GUI and requires no user interaction (e.g. LGWR). Depends on the way you program a Process, usually a process runs when certain event happens and re-runs if the event happens again. DBWR writes the dirty buffers from Database Buffer Cache to the data files. LGWR writes the redo log buffers from Redo Log Cache to the redo files. Log Switch happens whenever LGWR process finishes writing one Redo Log file and moves to the next one. LGWR process will start new ARCn process whenever ARCn gets overloaded. PMON frees up the resources from a failed user process. SMON is responsible for Instance recovery, if necessary.

2) Figure 5-3: Background processes of Oracle Instance. Oracle Instance running under Dedicated Server Mode is shown. Oracle running under Dedicated Server mode works the same as Shared Server mode except that a new server process gets created to serve the new logged in user. Idle Time of Server process(es) will be more compared to Shared Server environment. For unlimited resources, always go with Dedicated Server Mode otherwise stick with Shared Server Mode.

Page 135: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

135

Chapter 6:

Complete Oracle System (Instance &

Database) Design: Steps of Implementation Oracle is a very large subject and there is so much information that one can easily get lost and goes off track. That’s what happened with me when I first started my journey reading books on Oracle. Over here we have described the complete step by step way on how to erect the Oracle System from scratch. Figure 6-1 lists all the steps to achieve this goal. In this chapter we will explain up till step 07. Next steps are covered in the chapters ahead.

Page 136: Oracle 10g Made Simple

136

Figure 6-1: How to proceed? From 0 to 100%. 11 Steps to keep you on

track as we proceed.

Page 137: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

137

Figure 6-2: Steps 1, 2 and 3. Analysis for estimating initial database

size, frequery of growth and connected users. The parameters estimated values are required before we start the process of actually creating

Oracle Database in computer. Developing Primary and Foreign Key relationship between the tables helps in reducing redundancy of

Page 138: Oracle 10g Made Simple

138

information. It is recommended to have at least one tablespace designed for each department. The sum of “initial” estimated sizes of all the

tables within that department will give us the initial estimated size for a tablespace. The sum of all the initial estimated sizes of all the

tablespaces will give us the initial estimated size of database. The sum of frequencies of growth of all the tablespace will give us the frequency of growth of database. If we know how to find out the estimated size of

a table and its frequency of growth then we can also find out the estimated size of tablespace and frequency of its growth. If we know

how to find out the “initial” estimated size of a tablespace and its frequency of growth then we can also find out the estimated size of

database and frequency of its growth. Maximum number of concurrent connected users parameter helps whether we go with Shared Server

mode or Dedicated Server mode.

The sole purpose of step 1 to step 3 is basically to figure out three parameters that we need before we start the process of creation of Oracle Database: initial size of database, frequency with which data will grow and maximum number of connected users to Oracle Database. We cannot find out the exact value of these three parameters but we can have estimated values after doing company’s analysis or in other words once we develop tables structure required for each department in that company on paper. The very first step is to analyze the company’s organizational chart. Organization chart will give you an idea regarding how many departments are there and who to contact within each department. Remember once you get hired you would be in the IS&T (Information System & Technology) department or in some companies it’s simply called as IS (Information System) department. Once you have analyzed the organizational chart of the company then start with one department. Go and meet with the department’s head and explain the purpose and mission of IS&T department that IS&T is developing a database for the company and we need to do analysis of your department’s processes or in other words how things work in the department. How you manage data (most probably on paper)? Once done you can start

Page 139: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

139

creating tables’ structure and assigning them data types and once you have all the tables required by that department then you can start implementing primary and foreign key relationships between those tables on paper (I mean not actually implementing using CREATE TABLE statement). Developing Primary/Foreign Key relationship helps in reducing redundancy of information or Data. Once we reach a level where we can say that no further relationship is required and redundancy of information has came to its minimum then we can estimate the size of each table. Let’s see how? I want to take your mind to the CREATE TABLE statement, when you described data types for each column. Let’s suppose we have a table named “address_book” where we are maintaining just the name and addresses of people. It has a “name” column and “address” column as shown below. Table: addres_book name VARCHAR2(20) address VARCHAR2(200) Keeping in mind that it takes one byte to store one character, usually. We can easily estimate the size of one record in this address_book table in terms of bytes. So the formula of finding out the estimated size of table is given below. Estimated Size Of Table (Bytes) = Size Of A Record (Bytes) X Total Number Of Records So in our scenario the size of record would be (200 + 20) 220 bytes and if initially we have to place 100 people information in it then the “initial” estimated size of table would be (220 X 100) 22,000 bytes or 22 KB. Following on the same lines we can find out the “initial” estimated size of all the tables for that particular department. It’s recommended to have at least one tablespace created for each department. So the sum of the initial estimated sizes of all the tables within that department will give us the initial estimated

Page 140: Oracle 10g Made Simple

140

size of a tablespace. Moreover, we can also estimate the frequency of data growth in each table e.g. while in analysis phase we can ask a worker in that department how many people you add or sign-up for service per month and if he/she say 10 then keeping in mind address_book table. The formula to find out estimated frequency of growth of table would be as follows. Table’s Estimated Frequency Of Growth (Bytes) Per Month = (Number Of New Records Insertion per Month) X (Size Of Record) In our scenario it will come out to be (10 X 220) 2200 bytes per month or in other words 2.2 KB (Kilo Bytes). The sum of all the estimated frequencies of growth of all the tables within a department will give us the estimated frequency of growth for a tablespace that we will create for that department. Following on the same lines the sum of all the frequencies of growth of all the tablespaces with the database will give us the frequency of growth of database. Same applies to figuring out the initial size of the database i.e. sum of initial estimated sizes (bytes) of all the tablespaces gives us the size of the database. Whereas the size of the tablespace is the sum of initial estimated sizes of all the tables within that tablespace or in other words department. We can very easily roughly estimate the maximum number of connected user at any given instance if we know the number of employees that the company has and the number of clients and/or customers, accessing the Oracle Database. The purpose of finding out the rough estimation of maximum number of concurrent users accessing the Oracle Database is to come up with the decision whether “Shared Server” mode is more preferable for us or “Dedicated Server” mode.

Page 141: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

141

Figure 6-3: Planning database files location and naming. OFA defines

standard directory architecture whereas OMF defines standard file naming convention. Oracle Flexible Architecture (OFA) defines the

standard directory architecture for Oracle physical files. Oracle Managed Files defines the naming conventions for Oracle physical

files. If use DBCA to create the Oracle database then you don’t have to worry about OFA and OMF. DBCA follows OFA and OMF

automatically.

Page 142: Oracle 10g Made Simple

142

OFA stands for Optimal Flexible Architecture and it’s not at all that scary as the same sounds. It’s just the stand directory architecture that Oracle recommends us to follow for the placement of Oracle physical files e.g. once you create Oracle database using DBCA (Database Configuration Assistant), it automatically follows OFA and will place your database related files in the pre-defined stand file locations. According to OFA, “bdump” folder contains the background processes traces or dump files, “udump” is for users session related trace information, “pfile” folder contains the init.ora file so on and so forth. Similarly data files will be under the folder oradata\SID. OMF stands for Oracle Managed Files and it defines the standard for names that we give to the Oracle physical files or in other words, it supplies us with the naming convention for Oracle physical files. According to OMF, all data files should be having .DBF extension, control file should be having .CTL and redo log files should be having .LOG extension. Again you don’t have to worry about OMF or OFA if you using DBCA as it follows these stands automatically.

Page 143: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

143

Step 5: Selecting appropriate Oracle Database Edition & Licensing Option Oracle database software is available in following different editions. The basic concept of having so many editions is why to hit a house-fly with Cannon e.g. Enterprise edition is full blown Oracle Database for large enterprises and Oracle Database Lite is database to run on mobile devices. Enterprise Edition This edition typically runs on servers with 4 or more processors and it has no limit on memory (RAM). Clustering feature is available in this edition using Oracle RAC (Real Application Cluster) software. Moreover, it has more features than Standard Edition. Oracle Corporation licenses this product on the basis of users or of processors. Standard Edition This edition is for servers having one to four processors and it has no limit on memory (RAM). It also ships with Oracle RAC for clustering purpose. Oracle Corporation licenses this product on the basis of users or of processors. Standard Edition One This edition is having fewer features than Standard Edition and it is optimized for servers having one or two processors. Moreover it has no memory limitation.

Page 144: Oracle 10g Made Simple

144

Express Edition This edition is FREE and it is optimized for servers having with one processer with memory limit of 1 GB. The database size is limited to 4 GB in this edition. Oracle Personal Edition This edition has all the functionalities of Enterprise Edition but licensed for single-user. This edition is for single processor workstations. Oracle Database Lite, This edition is designed for mobile devices. The database itself is located on the mobile device and is having the ability to synchronize with the main Oracle server. After making a decision regarding which edition you need, the next thing is to find out how you want to have the licensing of the software. You can buy the licenses based on the number of users using the Oracle Server or based on the number of processors you will be having in the server machine. Step 6: Purchasing OS and Hardware The computer systems (or machines) that we normally buy from the stores are more specifically called Desktop Machines. Desktop machine has one processor, one power-supply, one network card etc. and the fault tolerance is not that much compared to a server machine where we are having multiple processors, two or more power-supplies, two or more network cards, multiple hard disks (SCSI) etc., everything in a single box. The reason of having two or more power supply is that if one fails the second one jump in automatically. If one network card burns out, the other one jumps in automatically.

Page 145: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

145

Multiple processors in a single server machine increases the machines power to serve more users or in other word all the processors within one server machine work together based on the technique called Parallel Operation. I bought a used PIII Xeon Quad Server machine from eBay at a cost of $380. This machine is having 4 PIII Xeon processors, three power supplies, three hard disk (SCSI) drives which I have configured for mirroring. If one hard disk fails, the server will still be up and running. RAC in Oracle RAC stands for Real Application Cluster and its old name was Oracle Parallel Server. Oracle RAC is basically your next step after having command over Oracle System we are learning in this book. In normal Oracle system there is one Oracle Instance and one Oracle Database but in Oracle Real Application Cluster we have multiple Oracle Instances running and interacting with a single Oracle database to achieve high performance and to serve larger community of users. Learning and understanding of Oracle RAC will be piece a cake if you have full understanding of one Instance Oracle systems. For up to date information about pricing of different editions of Oracle software, visit www.oracle.com or www.cdw.com. Step 7: Downloading and Installing Oracle Software Good news for those who are learning Oracle software is that you can download complete Oracle software for free from oracle website (www.oracle.com) for learning purpose. You will require a broadband (Cable/DSL) internet connection as the download will be large files and will take a week if you try to do it using a dial-up internet connection. Once you download the Oracle software then you would need to unzip those downloaded files most probably before running the setup.exe file which will start the Oracle Universal Installer (OUI). Follow the instructions on the web page where the

Page 146: Oracle 10g Made Simple

146

hyperlinks to downloadable Oracle software files are mentioned. But most probably those files will be in zip or jar format and can be unzipped using WinZip software. The evaluation version of WinZip software can be downloaded for free from www.winzip.com website.

Figure 6-4: Downloading & Installing Oracle Software. Oracle

Universal Installer (OUI) facilitates this task. The Download link is now moved under OTN website; please see Figure 6-5.

Figure 6-5: Oracle Technology Network website:

http://www.oracle.com/technology/software/index.html

Once you run the setup.exe file OUI will start and then you will see the following window with default values.

Page 147: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

147

Oracle Software Installation: Step I

Figure 6-6: Unzipping the downloaded Oracle Database Software will take you directly to the Setup.exe file. Double click the file and Oracle

Universal Installer will get activated.

Page 148: Oracle 10g Made Simple

148

Oracle Software Installation: Step II

Figure 6-7: The first screen of Oracle Universal Installer (OUI) will give you two options for installation as shown. In Basic Installation option everything will be taken as default and no further questions asked whereas in case of Advanced Installation option you will be

having control to change the default settings.

Page 149: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

149

Figure 6-8: Select the “Advanced Installation” option and then click the

“Next Button.

Page 150: Oracle 10g Made Simple

150

Oracle Software Installation: Step III

Figure 6-9: In this window you will be asked about the type of

installation. Select the “Enterprise Edition” and click the “Next” button.

Page 151: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

151

Oracle Software Installation: Step IV

Figure 6-10: In this window we will provided the information regarding

Oracle Home: the place on your disk drive where all Oracle files will reside. The first one is the Name text box where you write the Oracle

Home name or go with what is default. The second one will ask you the location of Oracle software files that needs to be installed. Click the

“Next” button once done.

Page 152: Oracle 10g Made Simple

152

Oracle Software Installation: Step V

Figure 6-11: Here Oracle Universal Installer will perform certain

checks to make sure that your machine (server/hardware) meets all of the minimum requirements for installation.

Page 153: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

153

Oracle Software Installation: Step VI

Figure 6-12: In this window, select the option of ‘Software Only’. By default you will see ‘Create a database’ selected. OUI has the

ability not only to install the Oracle software but to create the database too after the installation process. In other words it has the ability of DBCA (Database Configuration Assistant) that we will learn in the next chapter. Once done click the “Next” button.

Page 154: Oracle 10g Made Simple

154

Oracle Software Installation: Step VII

Figure 6-13: In this window, Oracle will show you the list of items that

will get installed once you click the “Install” button.

Page 155: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

155

Oracle Software Installation: Step VIII

Figure 6-14: The installation process begins as soon as you click the

“Install” button as shown in Figure 6-13. Once it is complete successfully you will see the window with “End of Installation” title.

Page 156: Oracle 10g Made Simple

156

Oracle Software Installation: Step IX

Figure 6-15: This window will popup to mark the end of installation process and to inform you that the software installed successfully.

If you encounter any problem during the installation phase try to understand the error message. Most of the time these error messages are very explanatory otherwise re-run the OUI and select the option “Remove” installed products which will uninstalled all the previously installed products. Once done then do the fresh installation.

Page 157: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

157

Once you have installed the software successfully then next step would be to create the database which we would be studding in the next chapter. Things to Remember Before Moving Ahead

1) Different Editions of Oracle Software: Enterprise Edition, Standard Edition, Standard Edition One, Personal Edition, Oracle Lite.

2) Licensing based on Users or Number of Processors (CPUs: Central Processing Unit).

3) Oracle Universal Installer (OUI) works the same way both in Windows and UNIX environment as it’s a JAVA based application.

Page 158: Oracle 10g Made Simple

158

Page 159: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

159

Chapter 7:

Oracle Database Design

• Designing Using DBCA • Designing Using SQL statements

In the previous chapter we learnt about from step 1 to step 7. This chapter talks about step 8 only i.e. creating Oracle Database. When we are talking about creation of Oracle Database, it’s understood that we are referring not only to Oracle Database but Oracle Instance as well. There are two options for us to achieve this goal. We can create the Oracle database using a software wizard called DBCA (Database Configuration Assistant). Wizard is a special kind of software that takes you through step by step process to the completion of certain task.

Page 160: Oracle 10g Made Simple

160

Figure 7-1: This chapter will talk about Step 08 i.e. Creation of Oracle Database. We can create Oracle database either using DBCA or using

Manual technique i.e. using SQL statements.

All you have to do is to keep clicking ‘Next’ button or change the default values then click ‘Next’ button. The other option is Manual i.e. you have to create the database using SQL DDL (Data Definition Language) statements and everything you have to do by yourself. Before the development of DBCA, DBAs (Database Administrators) used to develop databases using this Manual technique. Now with DBCA life turned out to be very simple. In this chapter we will discuss both of these methods and then leave the rest on you to decide which one to choose. Let’s start our discussion with the first method i.e. developing database using DBCA.

Page 161: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

161

Figure 7-2: Oracle Database Design Using DBCA. Before using DBCA

we have to set certain OS environment variables. Those environment variables are ORACLE_BASE, ORACLE_HOME, ORALCE_SID

and, PATH.

Page 162: Oracle 10g Made Simple

162

Before even we start DBCA we have to set some of the OS environment variables. Those variables are mentioned below along with the brief description. ORACLE_BASE describes the top most directory where Oracle software will be installed. In Windows environment we can set it using the SET command. Let’s suppose the DOS prompt is C:\>. C:\> SET ORACLE_BASE C:\Oracle Whereas in Unix we write the command as shown below. % setenv ORACLE_BASE /Oracle ORACLE_HOME specifies the directory that lies beneath ORACLE_BASE and its here where Oracle products reside. According to OFA (Optimal Flexible Architecture), this environment variable should to set to ORACLE_BASE/product/release#. Lets suppose the DOS prompt is C:\>. C:\> SET ORACLE_HOME C:\Oracle\database\9_2 Whereas in Unix we write the command as shown below. % setenv ORACLE_HOME /Oracle/product/9_2 ORACLE_SID is the instance name or rather default instance name on the machine having Oracle installed. This should be the unique identifier of the Oracle Instance on the machine. A single machine can have more than one instance, so each should be having separate SID. Lets suppose the DOS prompt is C:\>. C:\> SET ORACLE_SID test Whereas in Unix we write the command as shown below. % setenv ORACLE_SID test

Page 163: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

163

PATH is the environment variable and it’s usually set to ORACLE_HOME/bin folder. The bin folder contains all the tools that shipped with Oracle. With this done, you can run programs in the bin directory from any DOS prompt. No need to go, each and every time to the folder containing that specific executable file. Once this being set, you can run any Oracle supplied took from any prompt of DOS or UNIX. After setting the above mentioned parameters the next step would be to run DBCA. Database Design Using DBCA This method is applicable to both Windows and Unix/Linux Platforms. DBCA can be invoked from the Windows operating system start menu as shown in Figure 7-3 or by entering the following Unix command. dbca DBCA is a standalone application and its started automatically by OUI (Oracle Universal Installer) as a last step in the installation process if you make the selection of General Purpose database. Once DBCA gets started you will see window as shown in Figure 7-4 which describes the power of DBCA in brief. Click ‘Next’. DBCA works exactly the same in Unix and Windows Operating Systems.

Page 164: Oracle 10g Made Simple

164

Figure 7-3: Windows Server 2003 running Oracle Database Enterprise Edition. The location of DBCA is shown in the figure. DBCA can be

run through the start menu in Windows or by entering the dbca command in Unix OS

Page 165: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

165

Figure 7-4: Oracle Database Configuration Assistant Welcome window

describes the purpose of the software. Click the “Next” button.

Page 166: Oracle 10g Made Simple

166

Oracle Database Design Using DBCA: Step 1 of 12 Using DBCA you can create a new database, configure already existing database, delete an already existing database, manage templates and configure Automatic Storage Management. In this window you will see the second and third option as gray since there was no previous database on that system. Once you have passed through all the steps of DBCA and you are at the final window, you would be provided the option of letting DBCA create the database and/or save the configurations you made in the form of template as well or later use.

Figure 7-5: DBCA helps in doing four things: we can create a new

database, configure database, delete a database, manage templates and configure Automatic Storage Management.

Page 167: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

167

Saving in the form of template can help in creating a clone database. You can also make changes to the saved template using DBCA. Template basically contains the structure of the database & instance. You can save it on the disk (floppy/USB Flash Drives etc.) and take it to some other PC having Oracle software on it. Run DBCA and create the exact same database you that template. Make sure that ‘Create a Database’ option is selected and then click ‘Next’ button. Oracle Database Design Using DBCA: Step 2 of 12 DBCA comes with four pre-built templates. These templates names are provided below. Custom Database Data Warehouse General Purpose Transaction Processing Each template has default settings for database configuration parameters but you have been given full access to change any according to your needs. Make sure that ‘General Purpose’ option is selected and then click ‘Next’ button.

Page 168: Oracle 10g Made Simple

168

Figure 7-6: Over here we will be using “General Purpose” database

template.

Page 169: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

169

Figure 7-7: Default values in case you select the General Purpose

option.

Page 170: Oracle 10g Made Simple

170

Figure 7-8: Default values in case you select the General Purpose

option. It will be a huge list which you can read using the vertical scroll bar. You can also save the settings as a HTML file. It will help you in

developing clone database.

Oracle Database Design Using DBCA: Step 3 of 12 Two parameters you have to input in this window: the Global Database Name and the SID (System Identifier). Oracle Database is uniquely identified by a Global Database name. It is usually having a form “name.domain”. SID is the name of the Oracle Instance.

Page 171: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

171

Figure 7-9: Global Database name is usually described in name.domain

format and is the unique identification of Oracle database. SID is the name of the instance on the machine. You can never have two or more

instance having the same name on the same machine.

In our case we have entered takveen as the Global Database Name and test will come up automatically as SID. Once done then click the ‘Next’ button.

Page 172: Oracle 10g Made Simple

172

Oracle Database Design Using DBCA: Step 4 of 12 Oracle Enterprise Manager 10g Grid Control is used to manage more than one database. It’s a web-based user interface that communicates with all the databases and enable us to manage them centrally whereas Oracle Enterprise Manager 10g Database Control is used to manage one Oracle database or single RAC (Real Application Cluster) environment. Just like grid control, it is a web-based administration environment. Since we are not using Grid Control, make sure “Configure the Database with Enterprise Manager” checked and other two are unchecked as shown in Figure 7-10 then click the “Next” button. Each Oracle database can be managed centrally using Oracle Enterprise Manager Grid Control or locally by Oracle Enterprise Manager Database Control.

Page 173: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

173

Figure 7-10: Since we are not using Grid Control, make sure

“Configure the Database with Enterprise Manager” checked and other two are unchecked as then click the “Next” button.

Page 174: Oracle 10g Made Simple

174

Oracle Database Design Using DBCA: Step 5 of 12 Here you have been provided with two options i.e. either to use the same password for SYS, SYSTEM, DBSNMP and SYSMAN accounts or use different passwords. We went with first option; if you like you can use the second option.

Figure 7-11: We choose to have same password for SYS, SYSTEM,

DBSNMP and SYSMAN accounts then click the “Next” button.

Page 175: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

175

Oracle Database Design Using DBCA: Step 6 of 12 Here we have selected the “File System” option. You can read about other two and then click the “Next” button.

Figure 7-12: In this window you will be provided with three storage

mechanisms for your database. We have selected the “File System” and then clicked “Next”.

Oracle Database Design Using DBCA: Step 7 of 12 Here we have selected “Use Database File Locations from Template”. Before clicking “Next” button you can click on “File Location Variables…” button to have a preview of 5 very important parameters: ORACLE_BASE, ORACLE_HOME,

Page 176: Oracle 10g Made Simple

176

DB_NAME, DB_UNIQUE_NAME and SID. DBCA follows OFA (Optimal Flexible Architecture) and OMF (Oracle Managed Files) stands. All the default locations and file names specified in this screen are according to these standards. So you don’t have to worry about it.

Figure 7-13: Here we have selected “Use Database File Locations from

Template”. Before clicking “Next” button you can click on “File Location Variables…”.

Page 177: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

177

Figure 7-14: Five very important parameters: ORACLE_BASE,

ORACLE_HOME, DB_NAME, DB_UNIQUE_NAME and SID.

Once done click the “OK” button as shown in Figure 7-14 and you will be back to the previous window. Click the “Next” button.

Page 178: Oracle 10g Made Simple

178

Oracle Database Design Using DBCA: Step 8 of 12 In this step select the “Specify Flash Recovery Area” in case it’s not already selected. The DBCA wizard also provides you the option to check “Enable Archiving” in case you want to run the database in ARCHIVELOG mode. You can run Oracle Server in ARCHIVELOG Mode or NOARCHIVELOG Mode. In the archive log mode, the Redo Log files will get archived before they get over written by LGWR (log writer process). In NOARCHIVELOG mode once Redo Log files get filled up, Oracle will start overwriting them. The Redo Log files get utilized in a circular fashion. By default it’s no archiving mode. If you select the archiving mode then all you have to specify is the destination or the path and location of folder where you want to place the archived Redo Log files. Make sure “Enable Archiving” is unchecked and finally click the “Next” button. This action will run our database in NOARCHIVELOG mode. Later in the book we will learn how to put the database back in ARCHIVELOG mode.

Page 179: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

179

Figure 7-15: Make sure “Specify Flash Recovery Area” is selected. We

will learn about this feature later in the book. For now we are going with NOARCHIVELOG mode by not checking the “Enable Archiving”

check-box. Finally click the “Next” button.

Page 180: Oracle 10g Made Simple

180

Oracle Database Design Using DBCA: Step 9 of 12 Here we have selected the “Sample Schema”. Once selected the DBCA Wizard will install sample schemas e.g. Human Resources, Order Entry, Online Catalog etc. in our database. The “Custom Scripts” tab gives the option in case you want to run some SQL code right after the creation of database. Click the “Next” button.

Figure 7-16: Select “Sample Schema” and click the “Next” button.

Page 181: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

181

Oracle Database Design Using DBCA: Step 10 of 12 Here you can either use the default values provided for memory architecture of Oracle or change them according to your needs. Click on each of the given tabs: Memory, Sizing, Character Sets and Connection Mode to make sure that the stuff in there is according to your requirement.

Figure 7-17: Memory architecture of Oracle can be configured through

this window of DBCA.

Page 182: Oracle 10g Made Simple

182

Figure 7-18: Set the database block size and the maximum number of

concurrent user connections.

Page 183: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

183

Figure 7-19: Unless you are planning to develop a database for China or other non-English speaking countries; use the default character set.

Page 184: Oracle 10g Made Simple

184

Figure 7-20: We will be running our oracle database server in

Dedicated Server Mode. Select the “Dedicated Server Mode” option.

You have been provided with two options whether you want to run the Oracle Server in Dedicated Server Mode or Shared Server Mode. In Dedicated Server Mode as explained before there would be one server process per connected user whereas in Shared Server Mode multiple users would be served by a single server process. Select the Dedicated Server Mode if you want high performance and if you have plenty of system resources available otherwise go with Shared Server Mode.

Page 185: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

185

To see the complete list of initialization parameters click on the ‘All Initialization Parameters’ button. The popped up window will be having complete list of all the initialization parameters, those you have selected and those you haven’t select. It would be a completely editable window i.e. you can select and deselect any of the parameters and edit the values.

Figure 7-21: Click on “All Initialization Parameters …” button as

shown in Figure 7-20 to bring this window. You can edit the values of initialization parameters using this window.

Once done click ‘Close’ button and DBCA will take you back to the previous window. Click the ‘Next’ button.

Page 186: Oracle 10g Made Simple

186

Oracle Database Design Using DBCA: Step 11 of 12

Figure 7-22: Here DBCA presents you with Database Storage

configuration window with default settings. If you want you can change these settings.

If you click the Control file item on the left pane, on the right pane you will see all the multiplexed control files names along with their location. Each database can have one control file but you can have mirror copies at different locations. Having mirror copies is also known as multiplexing of a file. Oracle writes to all these multiplexed control files together. Once done click the ‘Options’ tab. The options tab under “Controlfile” item defines the maximum limit on data files, redo log groups and log members in each redo log group that this database could ever has.

Page 187: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

187

Figure 7-23: It’s better to have mirror copies of control file reside on

different physical disks.

The default values are sufficient enough so it’s better to stick with default. Once done then click “Datafiles” item on the right pane.

Figure 7-24: We can always add data files, redo log groups and redo

log members after creation of the database using the ALTER DATABASE Statement.

Page 188: Oracle 10g Made Simple

188

Once you click the ‘Data files’ in the right pane, the left pane will show all the data files your database is comprised off along with their location in the system. Since you have select ‘General Purpose’ database template, Oracle creates certain tablespaces for you by default. The data files shown above belong to those tablespaces. Remember that once you have created a complete database either through DBCA or Manual technique, you can always add new tablespaces or delete previously designed ones. Click the redo log group ‘1’ and information in the left pane will change.

Figure 7-25: This window shows the member in the first redo log

group. All members within each redo log group are mirror copies of each other.

Once you click ‘1’ under Redo Log Groups item in the right pane, left pane will show member name and its location. You can add more members and specify their location where you want to place them. All members with in a redo log group are

Page 189: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

189

mirror copies of each other. Click ‘2’ to see information about redo log group 2 and similarly for 3. After viewing the information regarding redo log group 3, click ‘Next’.

Figure 7-26: This window shows the member in the second redo log group. There are three redo log groups having one member in each.

You can have more members in each group.

Page 190: Oracle 10g Made Simple

190

Figure 7-27: This window shows the member in the third redo log group. We can always add data files, redo log groups and redo log

members after creation of the database using the ALTER DATABASE Statement.

Page 191: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

191

Oracle Database Design Using DBCA: Step 12 of 12 You can create the Database based on the configuration settings you provided or you can just save the configuration settings as a template or you can do both.

Figure 7-28: Once the template will be saved, it will add on to the four pre-built templates in DBCA. Having a template helps in the creation

of clone database.

Once done click ‘Finish’ button and DBCA will start the database creation process as it has collected all the information it needed from you.

Page 192: Oracle 10g Made Simple

192

Figure 7-29: DBCA will inform you as soon as it saves the scripts and

its location. Click the “OK” button.

Figure 7-30: As DBCA moves along the development of the database,

it updates you regarding the status.

Page 193: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

193

Figure 7-31: When DBCA creates the database successfully this

window will popup. Click on the “Password Management” button to manage the Users accounts.

Page 194: Oracle 10g Made Simple

194

Figure 7-32: Under Password Management window you can

Lock/Unlock accounts as well as change passwords.

Over here you can not only change the passwords for SYS and SYSTEM but you can also Lock/Unlock accounts. After changing the password, click ‘Ok’ button which will close this window and you will be back on the previous screen. Click ‘Exit’ and the database creation process will start. Once you see the message, database has been created successfully. Open SQL*Plus and login using scott account which is mentioned below. Login: scott Password: tiger

Page 195: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

195

Figure 7-33: Make sure SYS and SYSTEM are unlocked.

Make sure you have unlocked SCOTT account before doing this. If everything has been done well then you should be able to login and execute SELECT statements mentioned in the SQL chapter. Once you have database up and running you can always change its structure by first logging in as DBA account like SYSTEM and using ALTER DATABASE statement. We can also create new users, new tablespaces etc. Manual Oracle Database Design Next we look into the manual way of creating database and it will give us more insight to the process of development of database.

Page 196: Oracle 10g Made Simple

196

Figure 7-34: Manual Oracle Database Design: This method is applicable to both Windows and Unix/Linux platforms. It’s

recommended to prefer DBCA over manual method. Manual Technique gives the insight as to what DBCA does behind the scenes.

Page 197: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

197

Although development of database using DBCA is piece a cake and you should be preferring it over the Manual technique in the real world system development as helps in reducing the factor of making mistakes which may come up while you are doing everything own your own. Manual technique actually gives you more insight to DBCA as what it does behind the scenes for you. Manual Database Design: Step 1 Setting up Operating System Environment Variables Just like with DBCA technique, you have to first set up few environment variables the same way you did before invoking DBCA. But here we will be setting two additional parameters LD_LIBRARY_PATH which will point to Oracle library files associated with Oracle Instance and ORA_NLS33 its an optional environmental variable unless you want to specify other than US7ASCII.

Page 198: Oracle 10g Made Simple

198

Figure 7-35: Setup Operating System (OS) environment variables. OS

Environmental variables need to be set before using this technique.

Page 199: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

199

Manual Database Design: Step 2 Decide On Instance Identifier (SID) This will be name of your database instance. It will be unique on the machine running multiple Oracle instances. This is basically you set in the Step 01 when you set the environment variable ORACLE_SID. Manual Database Design: Step 3 Select Authentication Method for DBA Normal database users get authenticated by Oracle database only but DBA or in other words administrators have two methods through which they can get authenticated one is Operating System and the other one is password file. For local or remote database administration you can use either method but you need a secure network connection for remote administration using operating system authentication. In operating system method you don’t have to give password and login to make a connection as SYSDBA. All you have to do is make yourself member of OSDBA or SYSOPER operating system group. For example when you tried to connect using sqlplus to Oracle instance you didn’t specify any login and password, all you did was selected the option Connect as SYSDBA. Once someone sends a connection request to Oracle as SYSDBA without login and password; Oracle contacts the operating system under which Oracle is running to get the login and password of the user submitted the request. Remember, to reach to Oracle running on a server machine, first you logged-in to server, so server already know who is currently logged in. If you are system Administrator or you are member operating system SYSOPER or SYSDBA then Oracle will let you connect as DBA role which has the power to perform all kinds of DBA tasks.

Page 200: Oracle 10g Made Simple

200

Our recommendation is with letting the OS to authenticate the database administrator and not to create a separate external password file. The utility used to create password file is ORAPWD. Manual Database Design: Step 4 Create Initialization Parameter File In ORACLE_HOME/dbs directory you can find generic initialization files templates e.g. one for data warehouse database, one for Online Transactional Processing (OLTP) database and one for combination database. Select the one that suits your needs and change its contents or add new parameters. Finally save it with the name shown below. init<SID>.ora Where <SID> would be name you decided on in the beginning and which is also your environment variable ORACLE_SID. Edit this file and change the following parameters according to your needs. DB_NAME It will be your database name and it should not be eight characters in length e.g., DB_NAME=mydb DB_DOMAIN It will be text string which identifies the network domain where the database is hosted e.g., DB_DOMAIN=takveen.com CONTROL_FILES This parameter defines the control file names and location to be used to create the new database. If you fail to specify the

Page 201: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

201

filename, Oracle creates a file with a default operating system dependent name e.g., CONTROL_FILES = (d:\oracle\databases\ora10\control01.ora, d:\oracle\databases\ora10\control02.ora, d:\oracle\databases\ora10\control03.ora) UNDO_MANGEMENT You can control undo management to be manual (MANUAL) or automatic (AUTO). Its recommended to set this parameter to AUTO in Oracle9i and Oracle 10g e.g., UNDO_MANAGEMENT=auto UNDO_TABLESPACE A default tablespace with the name SYS_UNDOTBS will get created automatically when you execute the CREATE DATABASE statement if you have set UNDO_MANGEMENT=auto and no undo tablespace in the CREATE DATABASE statement. Oracle used this tablespace to store its undo information. DB_BLOCK_SIZE DB Block is the smallest building block of a database. This should be set to even multiple of OS block size to get high performance. Take care when determining its value as you cannot change it after the creation of database e.g., DB_BLOCK_SIZE=8192 Where 8192 represents bytes. The size of Database buffer cache is determined if we multiply DB_BLOCK_BUFFERS with DB_BLOCK_SIZE. Where DB_BLOCK_BUFFERS are the number of buffers in the database buffer cache of SGA (System Global Area).

Page 202: Oracle 10g Made Simple

202

Manual Database Design: Step 5 Connect and Start the Instance Starting SQL*Plus is very simple. No matter whether you are in Unix or Windows environment, all you have to do is to write the following command on the command prompt. E:\> sqlplus /nolog Then you will be taken to the SQL prompt. At the SQL prompt write the following command. SQL> connect / as sysdba Once Oracle receives this command, it will immediately communicate with the underlying OS to make sure that you are member of operating system OSDBA or OSOPER group or you are the system administrator. Now you get connected with the Instance. Next step is to start the instance without mounting a database since there is no database. The following command is used to do so. SQL> startup nomount If your parameter file is not at the default location i.e. ORACLE_HOME/dbs then you need to use the PFILE clause in the STARTUP command. But this is an exceptional case. With the execution of this command the Oracle Instance will get alive without the database or in other words Genie will become alive without Genie’s notebook. There are several options for starting up the Oracle system. These options are discussed below. STARTUP NOMOUNT

Page 203: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

203

This command will erect the Instance with no database mounted on it. No user would be able to connect or interact with the instance except the logged in SYSDBA. This state is usually used to create the new database. STARTUP MOUNT As a result of this command, the instance will mount the database after being alive. No user would be able to interact or access the information from the database. This state is usually used to recover the database in case of failures. STARTUP OPEN OPEN is the default clause of STARTUP command i.e. if you used execute STARTUP without any clause Oracle will take it as STARTUP OPEN. In this, Oracle Instance will open the database after making himself alive and then mounting the database in this brain and finally opens it. In this state users would be able to interact with the instance and access the data. STARTUP RESTRICT Starts the instance, mounts and opens the database but only users with restricted session privileges would be able to access or interact with the instance. STARTUP RECOVER Starts the instance but leaves the database closed and begins the recovery for whatever failure happened. STARTUP FORCE Forces the instance to shutdown abort and immediately startup open. This option is usually used with instance having problems either starting or stopping. Its like OS reboot or restart command. Like the STARTUP command, there is a command to shutdown the instance or in other words oracle system (instance and database) i.e. SHUTDOWN. Using this command we can shutdown the database in four ways. Those four ways are discussed below.

Page 204: Oracle 10g Made Simple

204

SHUTDOWN NORMAL The NORMAL clause in the SHUTDOWN command is default i.e. if you just execute SHUTDOWN Oracle will take it as SHUTDOWN NORMAL. As a result of this command, no new user is allowed to make a connection with Oracle Instance. The Instance will wait for each user to disconnect and then closes the database, dismounts it onto itself and shuts down itself. SHUTDOWN IMMEDIATE As a result of this command, no new user connections are accepted. All the connected users will get disconnected. Oracle Instance will roll back all uncommitted transactions. Closes the database, dismounts the database and shuts down itself. SHUTDOWN TRANSACTIONAL The result of this command is the same as SHUTDOWN IMMEDIATE except that Oracle Instance waits for the connected users to complete the transactions before disconnecting them. SHUTDOWN ABORT As a result of this command, everything shuts down abruptly. Oracle Instance terminates all connected users regardless of SQL statements under process. Terminates itself immediately and will not rollback uncommitted transactions. Instance recovery is needed when you start the database next time. Manual Database Design: Step 6 Issue the CREATE DATABASE Statement CREATE DATABASE statement is used to create the database. It has lots of clauses and it can be better understood if we first look at its syntax and then real world examples. The syntax for CREATE DATABASE statement is provided below.

Page 205: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

205

CREATE DATABASE [database name] [CONTROLFILE REUSE] [LOGFILE [GROUP integer] file specification] [MAXLOGFILES integer] [MAXLOGMEMBERS integer] [MAXLOGHISTORY integer] [MAXDATAFILES integer] [MAXINSTANCES integer] [ARCHIVELOG|NOARCHIVELOG] [CHARACTER SET charset] [NATIONAL CHARACTER SET charset] [DATAFILE filespec [autoextend]] [DEFAULT TEMPORARY TABLESPACE filespec] [UNDO TABLESPACE tablespace DATAFILE files] [SET TIME_ZONE [time_zone_region]]; Let’s look at the items in this statement one by one. Database name you specified in the initialization parameter file using DB_NAME parameter. If you omit the name, the one you specified in the parameter file will be used. Control file reuse means that the control file specified in the initialization parameter file should be reused. Log file group is the place where we specify the redo log files and the group they belong. Things will get clearer to you once we look at the real world example. MAXLOGFILES defines the maximum number of redo log files/redo log groups that can ever be created in the database. Similarly, MAXLOGMEMBERS defines the limit for redo log members per redo log group. MAXLOGHISTORY specifies the maximum number of archive redo log files for automatic media recovery. AUTOEXTEND enables or disables the automatic extension of SYSTEM tablespace data files. MAXDATAFILES defines the maximum number of data files that can ever be added to the database.

Page 206: Oracle 10g Made Simple

206

MAXINSTANCES is basically optional and used specifically in Oracle RAC (Real Application Cluster). The default is 1, if not specified. ARCHIVELOG or NOARCHIVELOG With this clause you can make the database to run in archive log mode or no archive log mode. In archive log mode, Oracle Instance makes sure that redo log files get archived to ARCHIVE_LOG_DEST location before they get overwritten. You can also switch between these two modes later after the creation of database using the ALTER DATABASE statement. CHARACTER SET defines the character set that the database uses to store data. NATIONAL CHARACTER SET this clause is optional and is used to store data in columns specifically defined as NCHAR, NCLOB or NVARCHAR2. Now let’s look at the real world example as provide below. CREATE DATABASE mydb1 CONTROLFILE REUSE LOGFILE GROUP 1 ('/mydatabases/mydb1/log01a.log', '/mydatabase02/mydb1/log01b.log') size 50M, GROUP 2 ('/mydatabases/mydb1/log02a.log', '/mydatabase02/mydb1/log02b.log') size 50M, GROUP 3 ('/mydatabases/mydb1/log03a.log', '/mydatabase02/mydb1/log03b.log') size 50M, DATAFLE '/mydatabases/mydb1/system.dbf' SIZE 250M AUTOEXTEND ON NEXT 10M MAXSIZE 500M UNDO TABLESPACE undotab DATAFILE '/mydatabases/mydb1/undotab.dbf' SIZE 50M DEFAULT TEMPORARY TABLESPACE temptbs TEMPFILE ‘/mydatabases/mydb1/temptbs.dbf' size 75M EXTENT MANGEMENT LOCAL CHARACTER SET US7ASCII

Page 207: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

207

MAXLOGFILES 20 MAXLOGMEMBERS 20 MAXLOGHISTORY 1 MAXDATAFILES 200;

A database must have at least two redo log groups and it’s recommended that all redo log groups should be of same size. Where we have specified 500M for system tablespace, if you use UNLIMITED then there would not be any limit. Actually in that case the limit comes from the space available on your hard disk. Up till this point our database would be having data files, control file, redo log files and obviously the PFILE. Also we would be having SYS and SYSTEM accounts. If you haven’t changed the default password of SYS (change_on_install) and SYSTEM (manager), it’s the best time to do it using the following ALTER USER statement. ALTER USER username IDENTIFIED BY password; Data Dictionary tables would also be available but not the data dictionary views. Manual Database Design: Step 7 Create Additional Tablespaces Create additional tablespaces that you need for your database using the CREATE TABALESPACE statement e.g., CREATE TABLESPACE payroll LOGGING DATAFLE '/mydatabases/mydb1/payroll.dbf' SIZE 250M AUTOEXTEND ON NEXT 10M MAXSIZE UNLIMITED EXTENT MANGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;

Create as many tablespace as you want in this manner. You can also use ALTER TABLESPACE to add more data files to the tablespace.

Page 208: Oracle 10g Made Simple

208

There are two kinds of tablespaces based on the storage management. One is called “Locally Managed” tablespace and the other one is “Dictionary Managed” tablespace. In all pre-Oracle9i systems, there was only one tablespace type i.e. Dictionary Managed and you had to take care of segments and extents within the tablespace. In Oracle10g all sorts of management of segments and extents are done by Oracle all you have to add is “EXTENT MANGEMENT LOCAL”. If you want a locally managed tablespace to have the segment’s free space managed by Oracle, you must include the clause, SEGMENT SPACE MANAGEMENT AUTO. Once done then you don’t even have to worry about PCTUSED and FREELISTS used in pre-Oracle9i releases. Manual Database Design: Step 8 Run Scripts to Build Data Dictionary Views Run the necessary scripts required to build data dictionary view. They are located under the directory ORACLE_HOME/rdbms/admin. Remember SYS is the owner of all the data dictionary view so you have to connect to Oracle Instance as SYS as shown below. CONNECT SYS/password AS SYSDBA The scripts you need to run are CATALOG.sql and CATPROC.sql. Once done all the data dictionary view will be created for you. Manual Database Design: Step 9 Run Scripts to Install Additional Options (Optional) This is optional step. If you need to install any of the optional products like InterMedia or Spatial, you can run the scripts to

Page 209: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

209

have these products added to your database. Consult the Oracle documentation for procedure and installation. Manual Database Design: Step 10 Create Server Parameter File (Highly Recommended) It is highly recommended to have a server parameter file created or in other words SPFILE from PFILE. SPFILE give you the ability to make dynamic changes to the initialization parameters using ALTER SYSTEM statement without the need to restart the Oracle Database. The statement to create the SPFILE given below. C:\>sqlplus /nolog SQL>CONNECT SYS/password AS SYSDBA SQL>CREATE SPFILE FROM PFILE; SQL>SHUTDOWN C:\>sqlplus /nolog SQL>CONNECT SYS/password AS SYSDBA SQL>STARTUP SQL>EXIT Manual Database Design: Step 11 Create Additional Users, Grant Them Quotas On Tablespaces, Privileges/Roles This is an optional step. Now you can create new users, grant them quotas on tablespaces, assign them privileges, profiles or Roles.

Page 210: Oracle 10g Made Simple

210

Manual Database Design: Step 12 Step 12: Back Up the Database Shut down the database as NORMAL and take a cold backup of the database. We learn about back-up in great detail in the backup and recovery chapter. Things to Remember Before Moving Ahead

1) Two ways to design and implement Oracle Database: (1) Using DBCA (Database Configuration Assistant), (2) Using manual technique.

Page 211: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

211

Chapter 8:

Oracle Network Administration The purpose of making Oracle network is to have an environment where users from all over the city or country or even world can access the database as if it’s residing on their machine. Establishing an Oracle network is very simple. All you have to do is to configure Oracle Net layer on both server and client side. Each of the clients that need to make a connection with Oracle server requires an Oracle Net installation. Before Oracle 9i, Oracle Net was called as SQL*Net. Oracle Net gets installed on the server at the time of installation of Oracle Server software but for each client we have to select the option of client installation in Oracle Universal Installer. Once we have configured client and server side Oracle Net layer, the connected client can easily send SQL commands to Oracle server and can get the response back.

Page 212: Oracle 10g Made Simple

212

Figure 8-1: Understanding the Oracle Network Architecture. Oracle

Net has to be there in both clients and server. Configuration of Oracle Net on server side is actually the development of listener.ora file.

Configuration of Oracle Net on the client side is actually the development of tnsnames.ora file. Oracle Net takes care of all different types of Network protocols. Server and clients know how to speak with

Oracle Net and Oracle Net knows all different Network languages. tnsnames.ora file contains the resolution of “Net Service Name” or

“Connect String” that we will use to connect to Oracle Server.

Page 213: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

213

Oracle Net takes care of all different types of Network protocols. Oracle server knows how to communicate with Oracle Net and Oracle Net knows all different Network languages/protocols including world famous TCP/IP. The whole internet runs on TCP/IP protocol based communication and even in LAN (Local Area Network), WAN (Wide Area Network) etc. TCP/IP is now a standard. Protocol is nothing but the “grammar” e.g. right now I am using English protocol to speak with you and you are understanding whatever I am saying since I following English grammar by default. Imagine if I stop following grammar rules than it would be really impossible for you to understand what I am saying. Similarly, when two machines (computers) talks with each other, both of them needs to know the common language and both of them have to follow the grammar (protocol) of the language (TCP/IP). The way it works is first we create the listener.ora file on the server then we start the listener. The development of listener.ora file is actually the configuration of Oracle Net for the server. Once we have started the listener process, it listens to the users connection requests. The job of the listener process is to bequeath the connection to the dispatcher in case the Oracle server is running under shared server mode or to the dedicated server process in case Oracle is running under dedicated mode. On the client side, we have to first install the Oracle Net software layer. It can be done using the same Oracle installation CD and selecting the option of “client side installation” in Oracle Universal Installed. Once done we have to create the tnsnames.ora file. Creating tnsnames.ora file is actually the configuration of Oracle Net on the client side. tnsnames.ora is nothing but contains the resolution of “service name” or “connect string” that we will use to connect to Oracle server running on the same machine or on some other machine located in even different country. All the client side (SQL*Plus) and remote database administration (Oracle Enterprise Manger)

Page 214: Oracle 10g Made Simple

214

tools require Net Service Name or Connect Sting or in other words tnsnames.ora file. This way of name resolution of Oracle server is called “Local Naming” method. This is highly recommended by Oracle and widely used all over the world. There are other ways too e.g. Directory Naming, Easy Connect Naming and External Naming. The preconfigured Oracle database uses local naming and only this form is used is this book. Host naming method requires the existence of external DNS (Domain Name Server) where as Oracle Internet Directory is advantageous when we are dealing with complex Oracle networks having many Oracle Servers running. In this book we have used the local naming method as it’s widely used. Creation of listener.ora file and starting/making sure listener process is running is mandatory on the server end whereas on the client side creating tnsnames.ora file is mandatory. Before starting configuring server and client side Oracle Net make sure to ping the server using the following command. Ping <ip address of Oracle Server> This command is equally good for Unix as well as windows environments. If you are running or using external DNS (Domain Name Server) then you can use domain name instead of ip address of the machine.

Page 215: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

215

Figure 8-2: Oracle Net takes care of all different types of Network

protocols. Server and clients know how to speak with Oracle Net and Oracle Net knows all different Network languages. The sole job of the

listener process is to bequeath the connection to the dispatcher or dedicated server process.

Page 216: Oracle 10g Made Simple

216

Upon ping command’s successful response, we should go ahead with the configuration of Oracle Net on the server. Ping command’s success means that no packets should be lost, out of 4 sent from the machine executed the ping command. In other words the machine executed the ping command can clearly see the other machine on the network. For both client and server side Oracle Net configuration we use ONM (Oracle Network Manger). ONM helps facilitates the development of listerner.ora file on the server end and tnsnames.ora file on the client end.

Figure 8-3: Oracle Net Manager: Java based program, completely

Operating System independent. Oracle Network Manager should be preferred over Oracle Network Configuration as recommended by Oracle. In Unix environment, ONM can be accessed by executing

netmgr command and the same software can be accessed in windows under start>all programs menu.

The next step would be to start the Oracle Net Manger. There is one more tool called Oracle Network Configuration Assistant or ONCA used for basic configuration of Oracle network. For more detailed control ONM is recommended by Oracle and is widely used. With this single tool we can create both listener.ora and tnsnames.ora files. ONM can be accessed under Unix using the netmgr command under ORACLE_HOME/bin directory and the same software can be found in window under Start>All Programs>Oracle. Once you expand the <Service Naming> and <Listeners> items in the tree as shown in Figure 8-4 and Figure 8-5, you will see nothing. There is no listener running moreover there is no tnsnames.ora file. We will first create the listener on the machine running Oracle Server using ONM.

Page 217: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

217

Figure 8-4: No Service Name or in other words no tnsnames.ora file.

The purpose of tnsnames.ora file is that it contains the name resolution of Net Service Name.

Figure 8-5: No listener process or in other words no listerner.ora file. We will first create the listener on the machine running Oracle Server

using ONM.

Page 218: Oracle 10g Made Simple

218

Creating Listener (or creating listerner.ora file) Select the Listener item from the tree in ONM and then click the ‘+’ sign shown in Figure 8-6 to create the listener. In the popped up window write the Listener Name. If you use the default name of the listener than the Oracle Instance registers itself with the listener dynamically and it’s called dynamic service registration. That’s why we are sticking with the default name of the listener i.e. LISTENER.

Figure 8-6: First add a listener by clicking the “+” sign.

Figure 8-7: For dynamic registration of service, use default listener

name.

Page 219: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

219

Not only listener name has to be default but we have to use default protocol i.e. TCP/IP and default port i.e. 1521 or 1520 if we want to go with dynamic service registration. After selecting listener name as LISTENER you have to click the OK button. Then the listener name will appear under the Listeners item in the tree on the left pane of ONM.

Figure 8-8: Once the listener gets created its name will show up in the

tree. Next step will be to add addresses.

Page 220: Oracle 10g Made Simple

220

Figure 8-9: Dynamic Service Registration happen only if we use default Listener Name, Protocol, Port. Two ways to do Dynamic service registration namely, use the default listener or specify the

following three init.ora parameters LOCAL_LISTENER, INSTANCE_NAME & SERVICE_NAMES

Select the listener name and click “Add Addresses” button on the right pane of ONM. Once you click this button Oracle adds the default values for Host (i.e. name of the machine running Oracle Server or its IP address in case no name resolution service like DNS is available), Protocol (i.e. TCP/IP) and port (i.e. 1521).

Page 221: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

221

Figure 8-10: Select “Database Services” from the drop down menu.

Figure 8-11: Zoomed version of Figure 8-10.

Page 222: Oracle 10g Made Simple

222

After you have finalized Host, Protocol and port, select the drop down menu from the top as shown in Figure 8-11 and select the option “Database Service”. Although the Oracle Instance will register itself with the listener as we have selected all default values but if you want to manually register the database you can do it this way. After selecting “Database Services” from the drop down menu click the “Add Database” button as shown in Figure 8-12.

Figure 8-12: Use the same information to fill in these three text boxes

as you used at the time of creation of database.

Page 223: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

223

Fill in the three text boxes with the same information you used at the time of creation of database. The Database name i.e. Global Database Name. In our case it is takveen. Moreover provide the location of Oracle Home directory and the name of SID i.e. takveen in our case. Once done, this is very important, do not forget to click “File” and then “Save Network Configuration” as only saving the configuration generates the listener.ora file. Once we start the listener process it will configure itself according to the configuration contained in the listener.ora file.

Figure 8-13: It’s not recommended that you create the listener.ora file

using text editor. Always use ONM as it’s programmed to produce listener.ora file exactly in same format required by listener process. The

sole purpose of the listener process is to listen to the connection request.

Next thing is to start the listener. The listener process can be started using lsnrctl utility both in Windows Server and Unix environment. You can also run in windows environment by clicking Start>Settings>Control Panel>Services

Page 224: Oracle 10g Made Simple

224

And then selecting the listener service for Oracle and then pressing the “play” on the tool bar of services console.

Figure 8-14: Starting listener process under Windows environment using Services application (snap-in for MS Management Console)

under Control Panel > Administrative Tools.

C:\>lsnrctl start This command will start the listener whereas if you replace “start” with “stop” you can stop the listener. To check the status of the listener use the following command. C:\>lsnrctl status What if you don’t want to have default listener or in other words you don’t want the listener name to be LISTENER or port to be 1521 or even protocol to be TCP/IP. In this case you have to define three more initialization parameters viz., INSTANCE_NAME, SERVICE_NAMES and LOCAL_LISTENER for Oracle to register with the listener dynamically e.g. if you want to run the listener on port other than 1521 then create the listener.ora file using that port number and mention this information in the LOCAL_LISTENER parameter in the init.ora file. For Oracle Instance to register dynamically with the listener you have to set the INSTACNE_NAME to name of the Instance in our case it should be takveen and the

Page 225: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

225

SERVICE_NAMES should be set to global database name, in our case it is Takveen. Creating Net Service Name (or creating tnsnames.ora file) Since now we have created the listener.ora file and started the listener process. Next thing we will do is to create the Net Service Name on this machine. Net Service Name is basically a short & easy to remember name for a long set of parameters that helps client applications to connect to server it includes host name, protocol, port, instance name etc. Select the “Service Naming” item in the tree on the left pane of ONM and click the “+” sign to add the Net Service Name. In the popped up window write the Net Service Name as “fan”. Now we are going to define what the word “fan” means on this machine by clicking “Next” button.

Figure 8-15: tnsnames.ora file resolves Net Service Name. Net Service

Name is basically the alias given to the set of TCP/IP required connection parameters that can lead MS Access, SQL*Plus etc. to the

Oracle Server.

Page 226: Oracle 10g Made Simple

226

Figure 8-16: You can have any name as Net Service Name.

Select protocol as TCP/IP and click “Next” button as shown in Figure 8-17. Then write down the host name of the machine running Oracle Server or in other words the listener’s machine name as shown in Figure 8-18. Remember that client applications send a connection request to the listener and listener bequeath the connection to the dispatcher in a shared server mode or dedicated server process in a dedicated server mode. After the connection has been bequeathed to the Oracle Instance then the communication takes place between Oracle Instance and the connected client without any listener process involvement.

Page 227: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

227

Figure 8-17: Select protocol as TCP/IP and click “Next” button.

Page 228: Oracle 10g Made Simple

228

Figure 8-18: In this window provide the Host Machine Name and the

Port on which Listener will be listening to requests.

Write down the port on which listener is running (i.e. on the host) and click “Next”.

Page 229: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

229

Figure 8-19: In Windows environment the machine name can be found

by right-clicking “My Computer” then clicking “Properties”. In the “System Properties”, click on “Computer Name” tab.

The parameters defined in the Figure 8-18 will take your client application to the listener running on the machine “xeon.apps.selfip.net” at port 1521. Your client application also has to convey to that listener which database on that machine you want him to bequeath the connection. As there are chances, the server might be having more than one Oracle databases running on the same machine.

Page 230: Oracle 10g Made Simple

230

Figure 8-20: Service Name is the Global Database Name of the Oracle

Database your connection will be bequeathed to.

Service Name over here is the parameter where you specify the global database name of Oracle database you what the listener to bequeath the connection in our case it is takveen. Click the “Next” button. The next popped up window will give you the opportunity to test the connection and see that your configured Net Service Name “fan” is resolving properly using tnsname.ora.

Page 231: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

231

Figure 8-21: Test button will give you the opportunity to verify if your

configured Net Service Name (i.e. fan) is resolving properly.

Once you click the “Test” button ONM (Oracle Network Manger) will use the “scott/tiger” account to test the connection. If you don’t have this account in your database or if you like to use some other account you can do that too. Upon successful connection don’t forget to save the Network Configuration. The tnsnames.ora file will get created or updated only when you save the configuration by clicking “File” and then “Save Network Configuration”.

Page 232: Oracle 10g Made Simple

232

Figure 8-22: Since we were having the default account locked, we

clicked the “Change Login” button to use SYSTEM account.

Figure 8-23: A successful connection means, Net Service Name (i.e.

fan) is resolving to Oracle Database Server (on same machine or some other machine) using tnsnames.ora file.

Page 233: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

233

Figure 8-24: ONM generates the tnsnames.ora file once you save the

configuration.

Figure 8-25: “fan” is created as a Net Service Name.

Once you save the network configuration as shown Figure 8-24, the Net Service Name will appear under Service Naming item in

Page 234: Oracle 10g Made Simple

234

the tree on the left pane of ONM. ONM creates/updates the tnsname.ora file every time you make a change in Net Service Name configuration and click on “Save Network Configuration” under “File” menu. The default location of tnsnames.ora file is %ORACLE_HOME%\network\admin on Windows Server 2003/2000/NT platforms and $ORACLE_HOME/network/admin under UNIX environment. It’s very important point to note here that the Net Service Name on one client machine (e.g. “fan”) needs not to be similar to the Net Service Name on the other client machine (e.g. “cow”) but they both can resolve to the same Oracle database server (e.g. takveen). Why & when we need Net Service Name (or Oracle Net client side installation and configuration)? Just to access Oracle Enterprise Manager Database Control, you need not to have tnsnames.ora file created on the machine from where you want to use the Oracle Enterprise Manager Database Control. Oracle Enterprise Manager Database Control has a web-interface and can be accessed from anywhere using any Internet Browser e.g. Opera, FireFox, Internet Explorer etc. Then why we need Net Service Name? My answers is, whenever you want to use SQL*Plus, MS Access etc. to connect to Oracle Database Server either on the same machine where you have Oracle Database Server or from a different machine located in different part of the world; you need to install Oracle Net and configure it for client side i.e. to create tnsnames.ora file. Starting Oracle Enterprise Manager Database Control In order to access the Oracle Enterprise Manager Database Control from a client browser, the dbconsole process has to be running on the server. Usually, the process starts automatically after the installation but in case if the process fails or there is a

Page 235: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

235

need to restart this process, you can start is from the command prompt. Navigate to the $ORACLE_HOME/bin directory and run the following statement: ./emctl start dbconsole Similarly, we can use the following to stop and check the status respectively. ./emctl stop dbconsole ./emctl status dbconsole In Windows OS, we can do the same via Services page under Start -> Control Panel -> Administrative Tools -> Services. The DBConsole service will be having the name based on the following naming convention. Oracle<oracle_home><SID>DBConsole You can double click this service to open up the service properties window. Like any other service in Windows OS, you can start, stop and enable, disable this service. Make sure in the Startup Type its set to Automatic. Accessing Oracle Enterprise Manager Database Control Point your web browser to the following URL: http://hostname:portnumber/em

Page 236: Oracle 10g Made Simple

236

Figure 8-26: In Windows, under Start menu; you can find “Database

Control” under Oracle applications group.

Figure 8-27: Login screen of Oracle Enterprise Manager Database

Control. We are using the SYSTEM account to login. You can also use SYS account and select Connect As SYSDBA.

Page 237: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

237

Figure 8-28: Once you are in Oracle Enterprise Manager Database

Control; this is the Home screen/page. There are four tabs at the top: Home, Performance, Administration, Maintenance.

The complete management of database is possible using Oracle Enterprise Manager Database Control whether the database is residing on the same machine or even in some other state or country. Before the development of Oracle Enterprise Manager Database Control DBAs’ used to do stuff using SQL statements but now Oracle Enterprise Manager Database Control uses the same SQL statements in the background for each of the tasks we perform by clicking on its web interface. In the next chapter we will learn how to manage Oracle database manually as well as using Oracle Enterprise Manager Database Control.

Page 238: Oracle 10g Made Simple

238

Things to Remember Before Moving Ahead

1) Figure 8-1: Understanding the Oracle Network Architecture. Oracle Net has to be there in both clients and server. Configuration of Oracle Net on server side is actually the development of listener.ora file. Configuration of Oracle Net on the client side is actually the development of tnsnames.ora file. Oracle Net takes care of all different types of Network protocols. Server and clients know how to speak with Oracle Net and Oracle Net knows all different Network languages. tnsnames.ora file contains the resolution of “Net Service Name” or “Connect String” that we will use to connect to Oracle Server.

2) Figure 8-13: It’s not recommended that you create the listener.ora file using text editor. Always use ONM as it is programmed to produce listener.ora file exactly in same format required by listener process. The sole purpose of the listener process is to listen to the connection request.

3) Figure 8-14: Starting listener process under Windows environment using Services application (snap-in for MS Management Console) located under Control Panel > Administrative Tools.

4) Figure 8-15: tnsnames.ora file resolves Net Service

Name. Net Service Name is basically the alias given to the set of TCP/IP required connection parameters that can lead MS Access, SQL*Plus etc. to the Oracle Server.

5) It’s very important point to note here that the Net

Service Name on one client machine (e.g. “fan”) needs not to be similar to the Net Service Name on the other client machine (e.g. “cow”) but they both can resolve to the same Oracle database server (e.g. takveen).

Page 239: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

239

6) Just to access Oracle Enterprise Manager Database Control, you need not to have tnsnames.ora file created on the machine from where you want to use the Oracle Enterprise Manager Database Control. Oracle Enterprise Manager Database Control has a web-interface and can be accessed from anywhere using any Internet Browser e.g. Opera, FireFox, Internet Explorer etc.

7) Then why we need Net Service Name? My answers is, whenever you want to use SQL*Plus, MS Access etc. to connect to Oracle Database Server either on the same machine where you have Oracle Database Server or from a different machine located in different part of the world; you need to install Oracle Net and configure it for client side i.e. to create tnsnames.ora file.

Page 240: Oracle 10g Made Simple

240

Page 241: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

241

Chapter 9:

Oracle Database Management

• SQL Statement Based • Using Oracle Enterprise Manager Database Control

SQL Statements Based Oracle Database Management This chapter assumes that there is already an Oracle Database running and in this article we will be using SQL*Plus software to make a connection to Oracle Server either running on the same machine or different. In both cases you need to create the tnsnames.ora file using Oracle Net. When managing Oracle using Oracle Enterprise Manager Database Control, there is no need to install Oracle Net on the client side as it requires only web browser like Opera, Internet Explorer. Let’s start our discussion by first looking at SQL statements relating to tablespace.

Page 242: Oracle 10g Made Simple

242

Figure 9-1: Availability of tablespace to the users can be controlled using ALTER TABLESPACE statement. SYSTEM tablespace can never be placed in the OFFLINE mode as Oracle utilizes the tables

relating to data dictionary views and dynamic performance view in its normal operation.

You can control the availability of tablespaces using the ALTER TABLESPACE statement e.g. you can make them READ ONLY or ONLINE/OFFLINE. Once you put the tablespace READ ONLY then no operation besides SELECT statement is allowed on that tablespace. By default once you start the Oracle database, all the tablespaces would be online unless you take a tablespace offline using the OFFLINE clause in the ALTER TABLESPACE command. The application of each of these will come in the backup and recovery chapter then their purpose will get clearer. Let’s discuss each of these statements in the following lines one by one. ALTER TABLESPACE users OFFLINE NORMAL; With NORMAL clause, Oracle writes all the dirty buffer blocks to the data files associated with that tablespace before taking it offline. All the data files associated with the tablespace needs to

Page 243: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

243

be online. No recovery is necessary when bringing the tablespace ONLINE again using the following statement. ALTER TABLESPACE users ONLINE; If you use the TEMPORARY clause instead of NORMAL no data files are checked whether they are online or not. Oracle performs a checkpoint whenever you use the ALTER TABLESPACE with TEMPORARY clause. Media recovery is necessary when you try to bring the tablespace ONLINE using the above-mentioned statement. With IMMEDIATE as shown below, Oracle takes the tablespace offline immediately without performing even Checkpoint. ALTER TABLESPACE users OFFLINE IMMEDIATE; FOR RECOVER clause in the ALTER TABLESPACE statement, Oracle places the tablespace in recovery mode. Like I said before, the applications of these commands are discussed in Backup and Recovery chapter. Remember that the SYSTEM tablespace can never be placed in OFFLINE mode, as the data dictionary has to be ONLINE all the time.

Page 244: Oracle 10g Made Simple

244

Figure 9-2: Complete management of tablespace using ALTER

TABLESPACE statement.

If your tablespace is running out of space than you can either increase the side of existing data files or you can add more data files to it using the ALTER TABLESPACE statement as shown in the Figure 9-2. Did you ever thought that why in the definition of “Relationship between Physical & Logical Architecture of Database”, we said, “Each tablespace can reside in one or more data files but each data file can never be associated with more than one tablespace.” What’s wrong with the following definition, if Oracle would have defined this relationship as, each tablespace can reside in one data file only, that’s it. Wouldn’t our life be much simpler? We never would have to worry about adding more data files. Whenever we run out of space in tablespace we can just increase it size.

Page 245: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

245

But let me tell you one thing which we are neglecting over here i.e. every OS has a file size limitation without going into details e.g. in Windows 98 you cannot have file size greater than 2 GB where as in Windows XP/Server you cannot have file size greater than 4 GB. So if Oracle would have said that a tablespace can reside in only one data file than it means Oracle tablespace size is limited to the OS maximum file size. That’s the reason, Oracle has lifted this limitation by saying that you can add as many data files as you like. It all depends on your resource limit (e.g. Hard Disks size etc.) but not on OS file size limit. Bottom line is that Oracle tablespace size is unlimited and is not bounded by OS maximum file size limit. DROP TABLESPCE statement helps in dropping of tablespace as shown below. DROP TABLESPACE users; If the tablespace is not empty then we have to add the clause INCLUDING CONTENTS. DROP TABLESPACE users INCLUDING CONTENTS; Remember that if you have named the data files according to file naming convention defined in OMF (Oracle Managed Files) then once dropping a tablespace with DROP TABLESPACE statement will drop/delete the data files associated with that tablespace too otherwise you have to remove the data files yourself at the OS level relating to that tablespace or use the following statement which will remove the data files too. DROP TABLESPACE users INCLUDING CONTENTS AND DATAFILES;

Page 246: Oracle 10g Made Simple

246

Remember that you cannot drop SYSTEM tablespace. As the tables related to data dictionary and dynamic performance Views have to be up all the times during normal Oracle operation. If the tablespace that you are deleting has referential integrity (Primary/Foreign Key relationship) constraints with the objects in other tablespace then include the clause CASCADE CONTRAINS as shown below. DROP TABLESPACE users INCLUDING CONTENTS CASCADE CONSTRAINTS; Now let’s see how to change the name and location of all the data files belonging to a tablespace. It’s always recommended to take full backup of the database before making any change pertaining to the structure of the database. It’s better to have the hard copy of the location and names of data files associated with the tablespace in front of you by using the DBA_DATA_FILES view. This view will give you the name of the tablespaces and the associated data files. Changing The Name/Location Of Complete Tablespace or Data File(s) If the tablespace is comprised of two data files you can change the name and location of one data file or all the data files. Changing the name and/or location of all the data files associated with the tablespace means that you are changing the name and/or location of complete tablespace. Step 1: Take the tablespace offline ALTER TABLESPACE payroll OFFLINE; OR

Page 247: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

247

ALTER TABLESPACE payroll OFFLINE NORMAL; Step 2: Rename the data files at OS Level Use OS commands (cp in Unix, copy in Windows) to change the name/location of data files associated with the tablespace. Step 3: Inform Oracle About The Change Use the ALTER TABLESPACE statement with RENAME DATAFILE clause to inform Oracle regarding the change you made to the data files at the OS level. ALTER TABLESPACE payroll RENAME DATAFILE ‘/disk1/oradata/test/payroll_data01.dbf’, ‘/disk1/oradata/test/payroll_data02.dbf’ TO ‘/disk2/oradata/test/payroll_data01.dbf’, ‘/disk2/oradata/test/payroll_data02.dbf’; Step 4: Make Tablespace ONLINE Use the following statement to bring the tablespace online again and that’s it. ALTER TABLESPACE payroll ONLINE; In case you want to change the name and/or location of data file(s) belonging to SYSTEM tablespace than you have to shutdown Oracle database follow step 2 and then STARTUP MOUNT, this command will make the Instance alive and the Instance will mount the database but it will not be open to the public. Then follow step 3 and finally open the database using following SQL statement. ALTER DATABASE OPEN;

Page 248: Oracle 10g Made Simple

248

Renaming Tablespaces Renaming a tablespace can be achieved using the following SQL statement. Remember that you cannot rename a SYSTEM or SYSAUX tablespace. ALTER TABLESPACE hr_01 RENAME TO hr_02; Bigfile Tablespace (BFT) and Smallfile Tablespace (SFT) This is a special tablespace introduced in Oracle 10g having only one data file. You cannot have more than one data file in bigfile tablespace. This feature is first time introduced in Oracle 10g. The size of the data file can be as big as 2^32 (4GB) blocks. The maximum size of the data file can be calculated as Maximum data file size = (DB_BLOCK_SIZE) * maximum number of blocks If you have set the DB_BLOCK_SIZE of a database to 8K then the maximum size of data file will be 32T. CREATE BIGFILE TABLESPACE hr_01 DATAFILE

‘/disk1/oradata/test/payroll_data01.dbf’ SIZE 2T EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO; Or simply, CREATE BIGFILE TABLESPACE hr_01 DATAFILE

‘/disk1/oradata/test/payroll_data01.dbf’ SIZE 1T; The SIZE represents the data file size and can be specified in terms of kilobytes (K), megabytes (M), gigabytes (G), or terabytes (T). Bigfile tablespaces requires extent management as local with automatic segment-space management (both items are set by default). An Oracle database can have both BFT and SFT. SYSTEM and SYSAUX tablespaces are always created as SFT.

Page 249: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

249

Before Oracle 10g there was only one tablespace, that tablespace is now called smallfile tablespace (SFT). SFT is the default tablespace type. All the CREATE/ALTER TABLESPACE statements we saw at the start of the chapter, Oracle took them as SFT. You can make BFT as a default tablespace type in your database by using the following statement. ALTER DATABASE SET DEFAULT BIGFILE TABLESPACE; After the execution of this statement, every time you use the CREATE/ALTER TABLESPACE statement, Oracle will take it as BFT unless you specify SMALLFILE clause explicitly or change it back to SFT using the following statement. ALTER DATABASE SET DEFAULT SMALLFILE TABLESPACE; Other Database Operations Besides working with tablespaces, using the SQL statements we can manage database access by creating new users, altering existing and assigning them system and/or object privileges, roles, profiles. All this and much more are already covered in the SQL chapter and manual database design technique. Now let’s have a look on how we can manage Oracle database using Oracle Enterprise Manager Database Control.

Page 250: Oracle 10g Made Simple

250

Oracle Enterprise Management Database Control based database management In the previous chapter you have learnt how to access and start Oracle Enterprise Manager Database Control. Here we are presuming that you already logged into Oracle Enterprise Manager Database Control using SYS credentials and as SYSDBA. Figure 9-3 shows the Home page of Oracle Enterprise Manager Database Control. The whole Oracle database management task is divided into four tabs: Home, Performance, Administration and Maintenance.

Figure 9-3: Whole database management divided into 4 sections:

Home, Performance, Administration and Maintenance.

Page 251: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

251

Figure 9-4: Performance tab carries information we need for

performance tuning of the system. This we will learn in detail in the last chapter. The first graph shows the real-time CPU utilization chart whereas the second one shows the active sessions with respect to time.

Page 252: Oracle 10g Made Simple

252

Managing Tablespaces/DataFiles Under Administration tab, there is “Tablespaces” link as shown in Figure 9-5. This link will not only provide you the information about the tablespaces currently in the database but also helps you to add/delete data files or create new tablespaces etc. all with a few clicks. No need to type or memories SQL statements.

Figure 9-5: Manage Tablespaces in your Oracle database using

Tablespaces link.

Page 253: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

253

Figure 9-6: Tablespaces management page under Administration tab.

Figure 9-7: Zoomed version of Figure 9-6. The drop down list provides

the tasks we can perform on database tablespaces besides creating a new one by clicking the “Create” button.

Page 254: Oracle 10g Made Simple

254

Figure 9-8: Add a data file to already existing tablespace.

To add a Datafile to already existing tablespace, first select that tablespace as shown in the Figure 9-6 and then from the drop down menu select the Add Datafile option and finally click the “Go” button. Once done, you will be on Add Datafile page as shown in Figure 9-8. Moreover, you can change the state of a tablespace from Read Write to Read Only or Offline using the Edit button as shown in Figure 9-7. Selecting “Make Locally Managed” item from the drop down list as shown in Figure 9-7 helps you to make your tablespace locally managed in case it is dictionary managed (before Oracle 9i versions). All locally managed tablespaces’ storage is managed by Oracle Instance automatically at the extent and block level.

Page 255: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

255

Figure 9-9: Datafiles link provides looking into the database via

datafiles angle. Creating a data file and assigning it to the tablespace is the same as if we have added a new data file to a tablespace.

Page 256: Oracle 10g Made Simple

256

Managing Redo Log Groups/Redo Log Members Under the Administration tab of Oracle Enterprise Manager Database Control, we have “Redo Log Groups” link. Clicking this link will take you to Redo Log Groups page which will not only provides you the current information about redo log groups but helps you to add new group or new member for already existing group.

Figure 9-10: Redo Log Groups link under Administration tab of Oracle

Enterprise Manager Database Control.

Page 257: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

257

Figure 9-11: Redo Log Groups page shows you the current number of redo log groups. Each group number is hyper-linked to provide you

more information and to give you opportunity add members.

Figure 9-12: Zoomed version of Figure 9-11, showing items under the

drop down list.

Page 258: Oracle 10g Made Simple

258

Figure 9-13: We can add new member in the redo log group as well as their location after clicking the group number as shown in Figure 9-11

and then clicking the “Add” button.

Page 259: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

259

Managing Oracle Instance Memory Architecture Memory Parameters link under the Administration tab enables us not only to control SGA and PDA sizes but provides us with their current status as well.

Figure 9-14: Under Administration tab, there is “Memory Parameters”

link to manage SGA and PGA area.

Page 260: Oracle 10g Made Simple

260

Figure 9-15: Manage PGA (Program Global Area) and view current status using this page. There is “Apply” not shown in the screenshot.

Once you change the value, click the “Apply” button to implement the change.

Page 261: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

261

Figure 9-16: Manage SGA (Shared Memory Area) and view current status using this page. There is “Apply” not shown in the screenshot.

Once you change the value, click the “Apply” button to implement the change.

Page 262: Oracle 10g Made Simple

262

Archive Logs Oracle Enterprise Manager Database Control provides information regarding archived redo logs through the Archive Logs page. This page is accessible through Administration tab as shown in Figure 9-17.

Figure 9-17: Under the Administration tab, there is “Archive Logs”

link.

Page 263: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

263

Figure 9-18: If the database is running under ARCHIVELOG mode only then this information is available otherwise you will see a table

with no values.

Setting Up Automatic/Manual Archiving The ARCHIVELOG mode can either be set during the creation or database or using the following statement. ALTER DATABASE ARCHIVELOG; Make sure that the database was in mounted state and not in open state before the execution of above statement. The Redo log files will get archived to the destination path defined using LOG_ARCHIVE_DEST. Once executed, this command will stays effective unless you execute the following statement. ALTER DATABASE NOARCHIVELOG;

Page 264: Oracle 10g Made Simple

264

Steps for Manual Archiving:

1. To setup manual archiving we set the LOG_ARCHIVE_START initialization parameter to False.

2. Put the database in ARCHIVELOG mode by first

shutting down the database as NORMAL and then starting it in mount state using STARTUP MOUNT statement. Then executing the following statement.

ALTER DATABASE ARCHIVELOG;

3. Finally open the database using the following statement.

ALTER DATABASE OPEN; Now you are ready to perform manual archiving of Redo log files using the following statements. SQL> archive log all; Or SQL> archive log next; With ALL clause you would be able to archive all Redo log files available for archiving whereas with NEXT clause the next group of redo logs will get archived. Steps for Automatic Archiving: Follow the same steps as in the manual method described above except change LOG_ARCHIVE_START to True. To make sure that the archiving is happening, execute the following statement and then check the directory defined in

Page 265: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

265

LOG_ARCHIVE_DEST initialization parameter file. You should see the archived Redo log files ALTER SYSTEM SWITCH LOGFILE; You can use V$DATABASE dynamic performance view to check the status on ARCHIVELOG mode. Using Oracle Enterprise Manager Database Control you can manage redo log files archiving process by clicking on “Recovery Settings” under Maintenance tab.

Figure 9-18a: Manage the ARCHIVELOG mode using this check box.

It is located on the Recovery Settings page. The link for Recovery Settings is available under the Maintenance tab.

Page 266: Oracle 10g Made Simple

266

Other Database Management Operations We have touched very small portion of things that we can do with Oracle Enterprise Manager Database Control. Most of the features/abilities of Database Control are self-explanatory as long as you know the theory/concepts e.g. if you do not know what redo log files are and how redo log gets utilized by Oracle Instance then click “Redo Log Group” link will make you feel as if you are in another world.

Figure 9-19: Manage SPFILE parameter and view the current

initialization parameters values using “All Initialization Parameters” link under “Administration” tab.

Figure 9-20: Manage users: create new users, assign then privileges,

tablespaces, roles etc. Edit existing users etc.

Page 267: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

267

Figure 9-21: Manage Roles using the “Roles” link under

“Administration tab.

Things to Remember Before Moving Ahead

1) Figure 9-3: Whole database management divided into 4 sections: Home, Performance, Administration and Maintenance.

2) Figure 9-5: Manage Tablespaces in your Oracle

database using Tablespaces link.

Page 268: Oracle 10g Made Simple

268

Page 269: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

269

Chapter 10:

Oracle Backup & Recovery Techniques In this chapter we will be studding different ways to perform backup and recovery operations. Oracle 10g backup and recovery techniques can be divided into 5 major categories as shown in the Figure 10-1 as well as below. Each category has a specific application. Most of these techniques are inherited from Oracle 9i to 10g. User Managed Backup and Recovery RMAN Backup and Recovery EM Database Control based Backup and Recovery Logical Backup and Recovery Flashback Technology

Page 270: Oracle 10g Made Simple

270

Figure 10-1: Oracle 10g backup and recovery techniques can be divided into 5 major categories: User Managed, RMAN based,

Enterprise Manager Database Control based, Logical and Flashback Technology based.

Page 271: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

271

Backups taken in the good time or when the database is up and running perfectly fine really help in time of failure or when files get corrupted. It’s exactly like what they say, “Make Hay While the Sun shines”. User-Managed Online/Offline Backup We are starting the discussion with User Managed path. Using the User-Managed path we can do both Oracle database backup as well as recovery. Let’s first start with learning User-Managed Backups. User-Managed Backups can be taken either by first making the database “offline” or even when the database is up and running. The steps of implementation are different in both the cases.

Figure 10-2: Zoomed area of Figure 10-1 with focus on User-Managed online/offline backup. User-Managed Backups can be taken when the database is SHUTDOWN NORMAL or even when it’s running. There is a difference between Restore & Recovery. Restore basically means

putting the stuff back from backed up location to original location using OS level copy command. Recovery process is performed after the

Restoration of data files from backed up location to original location happens. Recovery process is a must if the backup was an online/hot

backup.

Page 272: Oracle 10g Made Simple

272

There is very useful SQL statement and I usually call it a tool than just a SQL statement. This statement will give you the output with all the tablespaces within the database along with all the data files associated with each of these tablespaces. SELECT a.TS#, a.Name, b.Name FROM V$TABLESPACE a, V$DATAFILE b WHERE a.TS# = b.TS#; I call it a “tool” since with any other “tool” in real world you need not to know how its designed and what were mathematical formulae used to develop that tool e.g., with ranch all you need to know how to use it and when to use it. That’s it; unless you want to open up your own Ranch design factory.

= Figure 10-3: Both items on either side of equal (=) signs are tools with

each having a specific application in it’s own domain.

Similarly, in software world all you need to know how to use the application and not how it’s being developed unless you want to open up a software company or you’re a programmer. In Oracle world there are certain queries, I call as “Tools”. All you need to know what information it provides and when to use it. User-Managed Offline Backup The other names given to this kind of backup are Closed/Cold/Consistent Database backup. No recovery is needed in this kind of backup during the restore process, as the SCN (System Change Number) is consistent.

Page 273: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

273

Step 1: Shut down the database Connect to SQL as SYSDBA and then use the SHUTDOWN statement with NORMAL, IMMEDIATE or TRANSACTIONAL clause. C:\> sqlplus /nolog SQL>connect / as sysdba SQL> SHUTDOWN NORMAL; Remember that if there is any single user connected with the database and you have used the NORMAL clause with the SHUTDOWN statement then database will never shutdown unless the user closes the session. Step 2: Backup all the data files Once the database gets completely shutdown backup all the data files associated with the database at the operating system level or in other worlds using operating system commands e.g. copy in Windows and cp in case of Unix. Step 3: Backup Parameter File, Redo Log Files and Archived Redo Log Files Backup all these files too using operating system command. It’s highly recommended and provides greater fault tolerance in case of database failures. Step 4: Startup Oracle Database with MOUNT option Start the oracle instance and mount the database but don’t open. C:\>sqlplus /nolog

Page 274: Oracle 10g Made Simple

274

SQL>connect / as sysdba SQL>startup mount; Step 5: Backup the Control File Control file can be backed up using the following statement and at the desired location. ALTER DATABASE BACKUP CONTROLFILE TO ‘c:\staging\ctl.bak’; The backup created in this fashion will be the binary copy of the control file. We can also take the backup of control file, which will be in text format in the following manner. ALTER DATABASE BACKUP CONTROLFILE TO TRACE; As a result of this statement the text version of control file will get copied to the location/folder specified in USER_DUMP_DEST init.ora parameter. Step 6: Open the database Now you have full database backup or in other words Whole Database Backup. It’s time to make the database available to the users you executing the following statement. ALTER DATABASE OPEN; This completes our User-Managed Offline/Cold Database Backup. Let’s see now how we can perform User-Managed Online/Hot Database Backup. User-Managed Online Backup: The other names given to this kind of backup are viz., Open/Hot/Inconsistent database backup. The SCN will be different in all the backed up data files that’s why once you

Page 275: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

275

restore all the data files, recovery of database is required before making it available to users. There is very useful SQL statement and I usually call it a tool than just a SQL statement. This statement will give you the output with all the tablespaces within the database along with all the data files associated with each of these tablespaces. SELECT a.TS#, a.Name, b.Name FROM V$TABLESPACE a, V$DATAFILE b WHERE a.TS# = b.TS#; Always keep this tools output handy before proceeding with the backup. Step 1: Put the tablespace in backup mode Once connected to Oracle as SYSDBA, use the following statement to put the tablespace in the backup mode. ALTER TABLESPACE users BEGIN BACKUP; Step 2: Copy the associated data files Copy all the data files associated with the tablespace we placed in backup mode at the operating system level or in other words using operating system copy command in Window and cp in Unix. Step 3: Take the tablespace out of Backup mode Once we have copied all the associated data files then its time to take the tablespace out of backup mode using the following SQL statement. ALTER TABLESPACE users END BACKUP; Note: Repeat Step 1 to Step 3 for each of the tablespace with the database.

Page 276: Oracle 10g Made Simple

276

Step 4: Backup the Control File Control file can be backed up using the following statement and at the desired location. ALTER DATABASE BACKUP CONTROLFILE TO ‘c:\staging\ctl.bak’; The backup created in this fashion will be the binary copy of the control file. We can also take the backup of control file, which will be in text format in the following manner. ALTER DATABASE BACKUP CONTROLFILE TO TRACE; As a result of this statement the text version of control file will get copied to the location/folder specified in USER_DUMP_DEST init.ora parameter. Note: It’s recommended to backup Archived Redo Log files, Redo log files and parameter file to get a complete database backup. User-Managed Complete Recovery User-Managed Complete Recovery is done in two different ways and it all depends on the mode in which you are running the Oracle server. You can run Oracle server either in ARCHIVELOG mode or NOARCHIVELOG mode. The way we do the recovery in NOARCHIVELOG mode is different from the way we do recovery in ARCHIVELOG mode. Let’s have a look on each procedure as follows.

Page 277: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

277

Figure 10-4: Zoomed area of Figure 10-1 with focus on User-Managed Complete Recovery. There are two different ways to do such type of

Recovery: ARCHIVELOG mode, NOARCHIVELOG mode. In ARCHIVELOG mode, there will be Archiver process whose job is to archive Redo Log files before they get over written by the Redo Log

writer process (LGWR). The data entered/changed after the last backup will not be recovered in NOARCHIVELOG mode whereas no data will

get lost if you are running Oracle server in ARCHIVELOG mode.

User-Managed Complete Recovery in NOARCHIVELOG Mode In NOARCHIVELOG mode the recovery is very simple. All you have to do is to restore the database files from your backup to the original location and start the database. Let’s suppose one of your data file got corrupted. The time you try to start the Oracle Instance, it will give you an error. In this case shut down the database. Restore all the data files; redo log files and control file back to their original location from your last whole/complete cold backup.

Page 278: Oracle 10g Made Simple

278

Then start the Oracle database again by first running SQL and then connecting as SYSDBA. This time you will not get any error. User-Managed Complete Recovery in ARCHIVELOG Mode Let’s suppose one of your data file got corrupted/deleted. The time you try to start the Oracle Instance, it will give you an error with the name and location of the data files. If the Oracle server is up and running and you don’t want to shut it down then follow the following steps. Step 1: Take the corrupted data file offline Use the following SQL statement to take the corrupted/deleted data file offline. ALTER DATABASE DATAFILE ‘c:\oracle\oradata\test\users01.dbf’ OFFLINE; Step 2: Restore the corrupted data file Restore the corrupted data file by copy it from the backed up location and pasting it to the original location at the operating system level or in other words using operating systems commands like ‘copy’ in windows or ‘cp’ in Unix/Linux. Step 3: Recover Data File Recover the restored data file using the RECOVER DATAFILE statement. Then apply all the available Redo Log files by pressing “Enter” button on the keyboard whenever asked. C:\> sqlplus /nolog SQL>connect / as sysdba SQL>recover datafile ‘c:\oracle\oradata\test\users01.dbf’

Page 279: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

279

This will complete the recovery process and you will realize that no data will get lost i.e. everything that you entered or changed after the last whole database backup will get recovered by Oracle by applying all the redo log files. Difference between Recovery In ARCHIVELOG mode & NOARCHIVELOG mode In NOARCHIVELOG mode, the transactions that got processed after the last complete backup, will get lost where as in ARCHIVELOG mode no data will get lost i.e. everything that you entered or changed after the last whole database backup will get recovered by Oracle by applying all the redo log files including the ones got archived by the Archiver process. RMAN based Online/Offline backup RMAN or in other words the recovery manager is the utility that comes with Oracle software and helps in the backup and recovery process. What it does is like OEM, it communicates with Oracle Server using SQL in the background. RMAN requires a repository or storage area to store information about the database that needs to be backed up or recovered. That repository is called RMAN repository and remember it does not contain the backup itself rather it contains the information regarding target database.

Page 280: Oracle 10g Made Simple

280

Figure 10-5: Zoomed area of Figure 10-1 with focus on RMAN based

Online/Offline Backup. There are two different ways to do such type of backup. RMAN can run either by using target database control file or having its own database called Recovery Catalog database. We can

create Backup Sets and Image Copies using RMAN. Oracle recommendation is to use RMAN with Recovery Catalog Database and

not with target database control file. RMAN backup can only be performed when the database is either open or mount state.

There are two places you can use as a mean for RMAN repository. First is the target database control file and the second is the Recovery Catalog Database. You can use RMAN with either of these repositories. It means that you can run RMAN by using target database control file as RMAN’s repository or you can run it having its own separate database called RMAN Recovery Catalog database. Whatever RMAN needs to write it appends to the control file and would not overwrite or delete any stuff on it. It would be having its own section at the end of target database control file. Oracle recommendation is that one should prefer Recovery Catalog way instead of target database control file.

Page 281: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

281

Connecting To RMAN Here are the steps you need to perform to connect to RMAN with or without recovery catalog. Step 1: Set ORACLE_SID ORACLE_SID is the operating system environment variable and we use the ‘set’ command to set it to the database SID we want RMAN to backup. C:\> SET ORACLE_SID = test In Unix, its done as follows $ oraenv ORACLE_SID = test Step 2: Run RMAN Go to the Oracle bin directory and at the command prompt write rman RMAN> no matter its Unix or Windows Server 2003/NT. Step 3: Issue CONNECT TARGET Using DBA privileges issue CONNECT TARGET as follows. RMAN> connect target / The above mentioned command will make RMAN utilize Recovery Catalog database but before doing that you have to make sure that you have created Recovery Catalog database otherwise run RMAN with NOCATALOG option as shown below.

Page 282: Oracle 10g Made Simple

282

RMAN> connect target / nocatalog This command will make RMAN utilize control file of database we want to backup, as repository for RMAN. Once you are connected to RMAN then the next thing would be to select whether you want to create Backup Sets or Image Copies. Creating Backup Sets: After connecting to RMAN and at the RMAN prompt execute the following command to create the backup sets. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; BACKUP DATABASE FORMAT ‘/bkup/%U’; BACKUP (ARCHIVELOG ALL) FORMAT ‘/bkarc/arc_%p’; RELEASE CHANNEL ch1; }

This command will perform the complete database backup including archive log files. The BACKUP DATABASE clause backs up all the data files, control file and server parameter file (spfile) if used. In the above command %U defines the format of the backup sets name. Where %U is the abbreviation for %u_%p_%c. Where %u stands for 8 character name, %p stands for backup piece number within the backup set and %c means the copy number of backup piece within the backup set. We can also do the backup of tablespace and control file separately by using the following commands after connection with RMAN.

RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; BACKUP TABLESPACE users INCLUDE CURRENT CONTROLFILE; RELEASE CHANNEL ch1; }

Page 283: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

283

Creating Image Copies: After connecting to RMAN and at the RMAN prompt execute the following command to create the image copy of data file and control file. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; COPY DATAFILE 1 TO ‘c:\backup\system01.dbf’, CURRENT CONTROLFILE TO ‘c:\backup\control.ctl’; RELEASE CHANNEL ch1; } In the command above data file 1 will get copied to the backup location. Oracle assigns each data file a unique number in the database. To find out tablespaces names and the associated data files numbers use the following query which is basically a tool for DBA as explained before. SELECT b.name, a.file#, a.ts#, status FROM v$datafile a, v$tablespace b WHERE a.ts# = b.ts# ORDER BY file#; NAME FILE# TS# STATUS ------------------------ ---------- ---------- ------ SYSTEM 1 0 SYSTEM UNDOTBS 2 1 ONLINE CWMLITE 3 2 ONLINE DRSYS 4 3 ONLINE EXAMPLE 5 4 ONLINE INDX 6 5 ONLINE TOOLS 7 7 ONLINE USERS 8 8 ONLINE 8 rows selected.

If you want to copy more than one data file use the following command at the RMAN prompt.

Page 284: Oracle 10g Made Simple

284

RUN { ALLOCATE CHANNEL ch1 TYPE DISK; COPY DATAFILE 1 TO '/bkup/system01.dbf', DATAFILE 2 TO '/ bkup /undotbs01.dbf', DATAFILE 3 TO '/ bkup /cwmlite01.dbf', DATAFILE 4 TO '/ bkup /drsys01.dbf', DATAFILE 5 TO '/ bkup /example01.dbf', DATAFILE 6 TO '/ bkup /indx01.dbf', DATAFILE 7 TO '/ bkup /tools01.dbf', DATAFILE 8 TO '/ bkup /users01.dbf', CURRENT CONTROLFILE TO '/tmp/control01.ctl'; RELEASE CHANNEL ch1; } To copy archived redo log files use the following command. We can also merge the ARCHIVELOG clause mentioned in the RUN command below, in the RUN command mentioned above. RUN { ALLOCATE CHANNEL ch1 TYPE DISK; COPY ARCHIVELOG '/oradata/test/arch/archive1_1.dbf' TO '/bkup/archive1_1.dbf', ARCHIVELOG '/oradata/test/arch/archive1_2.dbf' TO '/bkup/archive1_2.dbf'', CURRENT CONTROLFILE TO '/tmp/control01.ctl'; RELEASE CHANNEL ch1; } Image copies generated using RMAN COPY command are similar to images copies generated using operating system commands like copy in Windows Server2004/XP/NT and no recovery is needed after restoring the files back from the backed up location. RMAN based Complete Recovery There are two types of recoveries that are possible with RMAN. Recovery of Database running under NOARCHIVELOG mode and the other one is the Recovery of Database running under ARCIVELOG mode.

Page 285: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

285

Recovering the database running under NOARCHIVE mode is very simple. All you have to make sure that the target database is first shunt down NORMAL, IMMEDIATE or TRANSACTIONAL. Then start the instance with database mounted on it by first connecting as SYSDBA. Then run RMAN and issue the RESTORE DATABASE command.

Figure 10-6: Zoomed area of Figure 10-1 with focus on RMAN based

complete recovery. There are two different ways to do such type of recovery: ARCHIVELOG mode, NOARCHIVELOG mode. No

recovery of database is needed if it was running under NOARCHIVELOG mode. Two key statements for RMAN recovery process are RESTORE DATABASE and RECOVER DATABASE. For the database in ARCIVELOG mode, we have to first restore the

database files and then start the recovery process. In the recovery process, all the redo logs will get applied to the database.

Since the database was running under NOARCHIVELOG mode that why no recovery is need. The following RMAN command can be used to restore the database. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; RESTORE DATABASE; } This command will restore all the database files from the backed up location to original position. Once the restore process

Page 286: Oracle 10g Made Simple

286

complete we can open the database using the following statement. ALTER DATABASE OPEN; If the database was running under ARCHIVELOG mode then first we have restore the database files and then issue the RECOVER DATABASE statement so that all the redo logs will be applied to the data files. Here “redo logs applied” means that all those redo logs that were archived by the archiver process. The database has to be in MOUNT state. Then start and connect the RMAN with the target database. The following would be used at the RMAN prompt to recover the database that was running under ARCHIVELOG mode before the failure detected. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; RESTORE DATABASE; RECOVER DATABASE; } Once the recover process complete, open the database using the following statement. ALTER DATABASE OPEN; It’s recommended that at this point shutdown the database normal and reopens it to make sure that the restore process completed successfully. It everything went well the database will open with no error. User-Managed Incomplete Recovery When the database was running under ARCHIVELOG mode all the redo log files archived before they gets over written. If something wrong happens to the database then we first have to restore the files and then use the RECOVER DATABASE

Page 287: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

287

statement to inform Oracle to start applying all the redo log files including those archived.

Figure 10-7: Zoomed area of Figure 10-1 with focus on User-managed incomplete recovery. There are three different ways to do such type of recovery. All the redo log files including the ones got archived will get

applied to the database when RECOVER DATABAE statement is executed. We can stop the process of recovery in the middle by using

either of the clauses i.e. UNTIL CHANGE, UNTIL CANCEL or UNTIL TIME with the RECOVER DATABASE statement. A

complete backup must be performed after incomplete recovery. Each transaction in Oracle has been assigned a unique number called SCN or System Change Number. After performing incomplete recovery of any type, the database would then be opened with the RESETLOGS clause.

Page 288: Oracle 10g Made Simple

288

The purpose of Redo Log files is now clear that it helps Oracle in bringing the database to the last committed transaction before the time failure occurred otherwise if there would not be any Redo Logs then would have recovered the database to the last good backup and things or in other words transactions that took place after the backup would then be lost. If you use just RECOVER DATABASE, then this is considered as complete recovery where as if we use the clause UNTIL TIME/UNTIL CANCEL/UNTIL CHANGE with the RECOVER DATABASE statement then we can stop the process of recovery in the middle. This concept applies to both User-Managed and RMAN based. After any type of incomplete recovery, a complete database backup must be performed. In case of time based recovery we can stop the recovery process at any point in time after the last backup but before the time of failure. So instead of just using RECOVER DATABASE, add the UNTILL TIME clause to it as shown below. RECOVER DATABASE UNTIL TIME ‘2004-2-15 11:00:00’; The complete name of such type of recovery is “User-Managed Time-Based Incomplete Recovery” or simple “Time Based” recovery. In “Cancel-Based” recovery, you Oracle will ask you each time its going to apply the redo log file whether to apply it or not. It’s more like a yes/no question. If you press the Enter key, the redo log will get applied and Oracle will ask you again regarding the next redo log file i.e. whether you want to apply the redo log file or not. If you press Enter, Oracle will apply that redo log file again. This process is repeated again and again unless you enter the CANCEL command or all the redo log gets applied. If you respond with the CANCEL command then Oracle will not apply that redo log file and will stop the recovery process. The statement used to perform such type of recovery is as follows.

Page 289: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

289

RECOVER DATABASE UNTIL CANCEL; The last case under User-Managed Incomplete recovery is “Changed-Based Recovery”. The word “Change” means SCN or System Change Number. SCN is the unique number that gets written to the header of data files, control files and redo log files. It gets written whenever Checkpoint happens. Oracle assigns each committed transaction a unique identification number called SCN. So Change Based recovery gives us the most control. We can stop the recovery process at any SCN. Remember that this SCN should be after the last back but before the point of failure. The statement used to perform such type of recovery is as follows. RECOVER DATABASE UNTIL CHANCE 64575343; After performing any type of incomplete recovery the database must be opened with the RESETLOG clause and then back up the complete database. ALTER DATABASE RESETLOGS; RESETLOGS clause makes sure that redo logs applied in the recovery process will never be used by resetting the log sequence and rebuilding the redo log system. The next step would be to perform complete database backup. The information about the SCN can be acquired by querying the V$LOG_HISTORY dynamic performance view. RMAN based Incomplete Recovery The command used to perform RMAN “Time-Based” Incomplete Recovery is as follows. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; SET UNTIL TIME ‘2003-3-4 11:00:00’; RESTORE DATABASE; RECOVER DATABASE; }

Page 290: Oracle 10g Made Simple

290

Figure 10-8: Zoomed area of Figure 10-1 with focus on RMAN based incomplete recovery. There are two different ways to do such type of recovery. After any type of incomplete recovery, open the database

using the RESETLOGS clause. After any type of incomplete recovery, complete database backup is required.

Page 291: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

291

For “Change-Based” Incomplete Recovery use the following command at the RMAN prompt. The information about the SCN can be acquired by querying the V$LOG_HISTORY dynamic performance view. RMAN> RUN { ALLOCATE CHANNEL ch1 TYPE DISK; SET UNTIL SCN=6563452; RESTORE DATABASE; RECOVER DATABASE; } After the completion of any type of RMAN Incomplete Recovery process, open the database using RESETLOGS clause as shown below. ALTER DATABASE OPEN RESETLOGS; RESETLOGS clause makes sure that redo logs applied in the recovery process will never be used by resetting the log sequence and rebuilding the redo log system. The next step would be to take the complete database backup using one of the techniques discussed earlier in this chapter. Logical Backup and Recovery As shown in Figure 10-9 under logical backup and recovery we have two techniques available. One, we inherited from Oracle 9i i.e. Export/Import or Simple Export/Import (exp & imp) and second one is new to Oracle 10g version i.e. Data Pump Export/Import (expdp & impdp). Oracle recommends DBAs to use this latest, fastest technique instead of using the old technology. The simple Export/Import utilities are available in Oracle 10g only for backward compatability. The Data Pump export and import (expdp & impdp) are not backward compatible with old export and import (exp & imp).

Page 292: Oracle 10g Made Simple

292

Figure 10-9: Zoomed area of Figure 10-1 with focus on Logical backup

and recovery. Oracle Import and Export utilities are used to perform such tasks. We can take the backup of table or complete schema using

Export utility. We cannot only recover the same table back into the database but we can also import that table into some other Oracle

database. Export/Import utilities are only for Oracle databases and not for any other database. There are three ways to perform Export:

Interactive, Command-Line, PARFILE. Import utility works the same way as export the only difference is that it imports the data exported

earlier by Export utility into any Oracle database. This Export/Import is not applicable to any non-Oracle database.

Besides the log file there are two data dictionary views (DBA_DATAPUMP_JOBS and DBA_DATAPUMP_SESSIONS) and one dynamic performance view (V$SESSION_LONGOPS) available to monitor the status of Data Pump job. The DBA_DATAPUMP_JOBS data dictionary view shows the status of all the active Data Pump jobs wheareas DBA_DATAPUMP_SESSIONS shows the user sessions related to each of the Data Pump job. In case of V$SESSION_LONGOPS dynamic performance view we can get progress of job and how much that has been done. In the following steps we will discuss the steps of using this new Data Pump technology. We will be using SCOTT account to perform the Data Pump export/import. Before performing the following steps, make sure SCOTT account is unlocked and it’s having necessary privileges by executing the following command.

Page 293: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

293

C:\>sqlplus / nolog SQL>CONNECT sys/password@asim AS SYSDBA OR C:\>CONNECT sys/password AS SYSDBA SQL>ALTER USER scott IDENTIFIED BY tiger ACCOUNT UNLOCK; SQL>GRANT CREATE ANY DIRECTORY TO scott; Step 1: Create directory object SQL> CREATE DIRECTORY TEST_DATA_PUMP AS 'C:\oradata\datapump'; Step 2: Grant privilege to run the EXPDP SQL> GRANT EXP_FULL_DATABASE to scott; Step 3: Grant full permission on directory object to user SQL> GRANT READ, WRITE ON DIRECTORY TEST_DATA_PUMP to scott; Step 4: For Database Import/Export: C:\>expdp SYSTEM/MANAGER@asim FULL=y DIRECTORY=TEST_DATA_PUMP DUMPFILE=asim_database_full.dmp LOGFILE=full_expdp.log C:\>impdp SYSTEM/MANAGER@asim FULL=y DIRECTORY=TEST_DATA_PUMP DUMPFILE=asim_database_full.dmp LOGFILE=full_impdp.log

Page 294: Oracle 10g Made Simple

294

For Schema Import/Export: C:\>expdp scott/tiger@asim SCHEMAS=SCOTT DIRECTORY=TEST_DATA_PUMP DUMPFILE=SCOTT_SCHEMA.dmp LOGFILE=expdpscott.log C:\>impdp scott/tiger@asim schemas=SCOTT DIRECTORY=TEST_DATA_PUMP DUMPFILE=SCOTT_SCHEMA.dmp LOGFILE=impdpscott.log To improve performance we can use the PARALLEL parameter along with "%U" in the DUMPFILE parameter to have multiple dump files generated (or read in case of impdp) as shown in the following command. C:\>expdp scott/tiger@asim SCHEMAS=SCOTT DIRECTORY=TEST_DATA_PUMP PARALLEL=4 DUMPFILE=SCOTT_SCHEMA_%U.dmp LOGFILE=expdpscott.log OR C:\>expdp scott/tiger TABLESPACES=USERS DIRECTORY=TEST_DATA_PUMP DUMPFILE=TSusers.dmp LOGFILE=TSusers.log For Table(s) Import/Export: C:\>expdp scott/tiger@asim tables=EMP,DEPT directory=TEST_DATA_PUMP dumpfile=EMP_DEPT_DATA.dmp logfile=expdpEMP_DEPT.log C:\>impdp scott/tiger@db10g tables=EMP,DEPT directory=TEST_DATA_PUMP dumpfile=EMP_DEPT_DATA.dmp logfile=impdpEMP_DEPT.log We can also use TABLE_EXISTS_ACTION=APPEND parameter in order to import the data into existing tables. Moreover, using INCLUDE/EXCLUDE you can quickly fine tune the selection of tables within the schema as shown in the following command.

Page 295: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

295

C:\>expdp scott/tiger@asim INCLUDE=TABLE:"IN ('EMP', 'DEPT')" directory=TEST_DATA_PUMP dumpfile=SCOTT_SCHEMA.dmp logfile=expdpSCOTT.log C:\>expdp scott/tiger@asim EXCLUDE=TABLE:"= 'HR'" directory=TEST_DATA_PUMP dumpfile=SCOTT_SCHEMA.dmp logfile=expdpSCOTT.log To get more information about other available paramters in expdp and impdp use the following commands. C:\>expdp help=y C:\>impdp help=y Simple Export/Import We can perform logical backup and recovery using Oracle’s Export and Import utilities. The major benefits of this import/export are logical backup/recovery, moving data from one Oracle database to another Oracle database and reorganization of database by using COMPRESS=Y. We export table or complete schema (i.e. all the objects within the schema like tables, views, sequences etc.) to an external binary file called Dump file. The dump file is having extension of .dmp and a default name of expdata.dmp. As it’s a binary file so it is not possible to read/understand that file. We have to use the Import utility to dump this file into any Oracle database. There are two ways to do export of data from Oracle database using Export utility. One is called the “Conventional Path Export” and other is called the “Direct Path Export”. Conventional path export is the default mode of the Export utility where as Direct path export can be achieved by setting DIRECT=Y.

Page 296: Oracle 10g Made Simple

296

Conventional path export takes more time for large amount of data being transferred then the direct path export but it works fine for everyday uses. In this method data is extracted by Export utility from the database using SQL statement (SELECT * FROM emp) and the result is dumped into the Database Buffer Cache. From Buffer Cache, the data then gets evaluated in the evaluating buffer then it gets dumped into the external binary dump file. In Direct path export there is no “evaluation of data” step involved and the data gets transferred to the external dump file from Database Buffer Cache. This elimination of one step results in speedy transfer. There are three ways we can run the Export utility. One is in the “Interactive Mode”, second is the “Command-line” and the third is by using parameter file i.e. PARFILE. PARFILE method is basically used for nightly or scheduled or automatic jobs to do the logical backup of data. In Command line way, we describe all the parameters to run Export utility in a single command where as in the Interactive mode, the Export utility ask questions to get input from the user regarding the parameters required to extract data. Interactive Export: Step 1: Set ORACLE_SID Set the ORACLE_SID to the name of the Oracle Instance with which you want the Export utility to communicate to extract the information.

Page 297: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

297

Step 2: Run & provide your Oracle credentials to Export utility You must be having this utility available under $ORACLE_HOME/bin directory having the name exp. At the Unix or Windows NT/Server/XP prompt write exp. C:\> exp Then provide your Oracle credentials i.e. login/password that you use to connect to Oracle database. Actually Export utility will use your credentials to make a connection with the Oracle database whose SID you have assigned to ORACLE_SID operating system environment variable in step 1. Username: system Password: manager Step 3: Answer questions asked by Export Utility After getting your credentials (login/password) Export utility will ask you certain question before exporting data out to external dump file. The first question would be the buffer size you want to use to facilitate the fetching of data. The default size would be 4096K. If you want to stick with this default size then simply press Enter key. Enter array fetch buffer size: 4096> Then the Export utility will ask for the external dump file name. Provide the full qualified name including the path where you want to store this file. The extension of this dump file should be .dmp whereas the file name could be any name, in our case we are using the file name same as that of table name we want to export i.e. emp table. The default name of dump file is expdat.dmp. If you want to stick with this press the Enter key. Export file: expdat.dmp> emp.dmp Next question will ask for Users or Tables. If you want to export table then select the table option whereas if we want to export

Page 298: Oracle 10g Made Simple

298

the complete schema i.e. all the object under the user account then select the user option. By default its users. (2) U(sers), or (3)T(ables): (2)U> 3 Then the next prompt would be to have extents compressed by default its yes. Compress extents (yes/no): y Lastly, it will ask for the table or partition that needs to be exported. Table or Partition to be exported> emp With the answer to this question, the export utility will start exporting emp data out from Oracle in the binary dump file and once done it will terminates with the success and you will be back on the OS prompt. PARFILE Export: First set the ORACLE_SID operating system environment variable then create a separate text file having all the parameters lined up as follows and then run Export utility specifying PARFILE parameter. > exp system/manager parfile=param.dat Where param.dat file contains the following information: DIRECT=Y FILE=expdat.dmp TABLES=(scott.emp,blake.dept) GRANTS=y INDEXES=y

Page 299: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

299

Command-Line Export: The Export utility can be used in the command line as follows where we provide all the parameters in the single command. Before running this command make sure you set the ORACLE_SID operating system environment variable. > exp system/manager tables=(emp, dept) grants=Y indexes=Y direct=y

You can also get a detailed help on Export utility by running the following command at the OS prompt. >exp –help The Import utility is located under ORACLE_HOME/bin directory in Unix and ORACLE_HOME\bin directory in Windows NT/XP/Server 2003. The utility comes with a detailed help too and can be accessed by running the following command at the operating system prompt. >imp –help With the help of Import utility we can import any previously exported logical objects using Export utility in any Oracle database. The step by step process of importing any .dmp file into the Oracle database is given below. Step 1: Set ORACLE_SID Make sure that ORACLE_SID is set to the SID of Oracle database to which you want to import the file. Step 2: Run & provide your Oracle credentials to Import utility The Import utility is located under ORACLE_HOME/bin directory and can be executed simple by writing imp. Then supply your Oracle username/password. The Import utility will use your credentials to make a connection with the Oracle

Page 300: Oracle 10g Made Simple

300

database and will import the data from external binary file to your schema. Username: system Password: manager Step 3: Answer questions asked by Import Utility Following questions will be asked by import utility and most of them are self-explanatory. The very first prompt would be the name of file you would like to import into your Oracle schema. Over here provide the full qualified dump file name i.e. file name as well as path where it is located. Import file: expdata.dmp> emp.dmp Similarly as with Export utility, the Import utility will ask for the buffer size. We are choosing 8K the minimum one. Enter insert buffer size (minimum is 8192) 30720 > 8192 Next, the utility asks for whether to list the contents of the dump file or not. The default is no, which will do the import without listing the contents. Choose the default i.e. no. List contents of import file only (yes/no): no> n Next prompt would be as follows and it asks for whether to ignore the CREATE ERROR if the object already exits. Choose yes. Ignore create error due to object existence (yes/no): no> y The next question as for whether to import grants related to object that we are trying to import. Import grants (yes/no): yes > y

Page 301: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

301

Next prompt would be to import the data in the table instead of just table structure. Choose yes. Import table data (yes/no): yes > y Lastly, it will prompt for whether you would like to import the entire file or not. Choose yes. Import entire export file (yes/no): no> y Once you finishing answering the last question the import process will start and the utility will notify you as it completes. Once done the utility terminates and bring you back to your OS prompt. Then you can query the table just got imported to your database just to make sure that everything is in perfect shape.

Page 302: Oracle 10g Made Simple

302

Oracle Enterprise Manager Database Control Based Backup Techniques EM Database Control provides common backup features but more comprehensive ones are still available via RMAN. In case the database is running under NOARCHIVELOG mode then there will be two options available under customized backup category as shown in Figure 10-10.

Figure 10-10: Enterprise Manager Database Control has two categories of backup: Oracle-Suggested Backup and Customized Backup. If the

database is running under NOARCHIVELOG mode then there will be two options available under Customized Backup: Whole Database and

All Recovery Files on Disk.

On the other hand if the database is running under ARCHIVELOG mode, you would be having following options available for scheduling of customized backup as shown in Figure 10-11.

1) Whole Database 2) Tablespaces 3) Datafiles 4) Archivelogs 5) All Recovery Files

Page 303: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

303

Figure 10-11: Zoomed area of Figure 10-1 with focus on Enterprise

Manager Database Control based Backup Techniques.

Page 304: Oracle 10g Made Simple

304

ARCHIVELOG mode can be enabled by clicking Maintenance tab and then “Recovery Settings” link. On the recovery settings page select the “ARCHIVELOG Mode” check box and then click the “Apply” button. The Maintenance tab is available once you login to Oracle EM Database Control. Oracle EM Database Control offers two main types of scheduling of backups: Oracle-Suggested Backup and Customized Backup.

Figure 10-12: Screenshot taken from Schedule Backup page under

Maintenance tab.

Figure 10-13: Screenshot taken from Schedule Backup page under

Maintenance tab of EM Database Control. It describes the benefits of using the Oracle-Suggested backup category.

Page 305: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

305

Figure 10-14: In case you are running the database in ARCHIVELOG

mode then these options are available under Customized Backup category. In case the database is running in the NOARCHIVELOG

mode, see Figure 10-10.

Figure 10-15: Screenshot taken from Schedule Backup page under

Maintenance tab of EM Database Control. It describes the benefits of using the Customized backup category.

Page 306: Oracle 10g Made Simple

306

Oracle Enterprise Manager (EM) Database Control based Oracle-Suggested Backup Step 1 of 4: Select the destination media: Disk, Tape or Both. For the sake of this example we are going with first option.

Figure 10-16: Select Disk and then click the “Next” button.

Step 2 of 4: Setup

Figure 10-17: This is the information screen. Click “Next” button.

Page 307: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

307

Step 3 of 4: Schedule backup.

Figure 10-18: Schedule your backup. You can also set the frequency of

backup or make it just one time only.

Step 4 of 4: Review

Figure 10-19: Review your setting and click the “Submit Job” button.

Page 308: Oracle 10g Made Simple

308

Figure 10-20: EM Database control also generates the equivalent

RMAN script.

Figure 10-21: Once you click the “Submit Job” button; this screen

appears.

Page 309: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

309

Oracle Enterprise Manager (EM) Database Control based Whole Database Backup On the Schedule Backup page, select the Whole Database option and then click the “Schedule Customized Backup” button as shown in Figure 10-22.

Figure 10-22: In case you are running the database in ARCHIVELOG

mode then these options are available under Customized Backup category. In case the database is running in the NOARCHIVELOG

mode, see Figure 10-10.

Step 1 of 4: Select the Backup Type and Backup Mode

Figure 10-23: Select the Backup type, mode and click “Next” button.

Page 310: Oracle 10g Made Simple

310

Figure 10-24: For the sake of this example we have selected Full

Backup with Online Backup mode. In Online Backup mode, the backup can be performed when the database is OPEN. Moreover, we have

checked the “Also backup all archived logs on disk” check box.

Step 2 of 4: Select the storage media

Figure 10-25: We have select Disk as storage media. Click “Next”

button.

Page 311: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

311

Step 3 of 4: Schedule Backup

Figure 10-26: Schedule your backup. You can also set the frequency of

backup or make it just one time only.

Figure 10-26a: We have selected “Immediately” with repeat condition

as “One Time Only”.

Page 312: Oracle 10g Made Simple

312

Step 4 of 4: Review your settings

Figure 10-27: Review your setting and click the “Submit Job” button.

EM Database control also generates the equivalent RMAN script.

Page 313: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

313

Oracle Enterprise Manager (EM) Database Control based Tablespaces Backup On the Schedule Backup page, select the Tablespaces option and then click the “Schedule Customized Backup” button as shown in Figure 10-28.

Figure 10-28: In case you are running the database in ARCHIVELOG

mode then these options are available under Customized Backup category. In case the database is running in the NOARCHIVELOG

mode, see Figure 10-10.

Step 1 of 5: Select Tablespaces to backup

Figure 10-29: Use the Add button to add tablespaces.

Page 314: Oracle 10g Made Simple

314

Figure 10-30: In our example, we have selected SYSTEM,

UNTOTBS1 and USERS tablespaces backup. Click “Next” button.

Step 2 of 5: Select Backup options

Figure 10-31: Here we selected Full Backup option with the “Backup

all archived logs on disk”.

Page 315: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

315

Figure 10-32: If you understood the concepts from previous chapters;

all the stuff mentioned here is self-explanatory.

Step 3 of 5: Select the Storage Media

Figure 10-33: We selected Disk as storage media for backup.

Page 316: Oracle 10g Made Simple

316

Step 4 of 5: Schedule Backup

Figure 10-34: Schedule your backup. You can also set the frequency of

backup or make it just one time only.

Figure 10-35: We have selected “Immediately” with repeat option as

“One Time Only”.

Page 317: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

317

Step 5 of 5: Review your settings

Figure 10-36: Review your setting and click the “Submit Job” button.

Figure 10-37: EM Database control also generates the equivalent

RMAN script.

Page 318: Oracle 10g Made Simple

318

Oracle Enterprise Manager (EM) Database Control based Datafiles Backup On the Schedule Backup page, select the Datafiles option and then click the “Schedule Customized Backup” button as shown in Figure 10-38.

Figure 10-38: In case you are running the database in ARCHIVELOG

mode then these options are available under Customized Backup category. In case the database is running in the NOARCHIVELOG

mode, see Figure 10-10.

Step 1 of 5: Select Datafiles

Figure 10-39: Use Add button to add datafiles.

Page 319: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

319

Figure 10-40: We have selected few datafiles as shown in screenshot.

Step 2 of 5: Backup Options

Figure 10-41: Here we selected Full Backup option with the “Backup

all archived logs on disk”.

Page 320: Oracle 10g Made Simple

320

Figure 10-42: If you like you can select the check boxes based on your requirements. For the sake of this example we are going with “Backup

all archived logs on disk”.

Step 3 of 5: Storage Media and Location

Figure 10-43: We selected Disk as storage media for backup.

Page 321: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

321

Step 4 of 5: Schedule Backup

Figure 10-44: Schedule your backup. You can also set the frequency of

backup or make it just one time only.

Step 5 of 5: Review your setting

Figure 10-45: Review your setting and click the “Submit Job” button.

Page 322: Oracle 10g Made Simple

322

Figure 10-46: EM Database control also generates the equivalent

RMAN script.

Page 323: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

323

Oracle Enterprise Manager (EM) Database Control based Archivelogs Backup On the Schedule Backup page, select the Archivelogs option and then click the “Schedule Customized Backup” button as shown in Figure 10-47.

Figure 10-47: In case you are running the database in ARCHIVELOG

mode then these options are available under Customized Backup category. In case the database is running in the NOARCHIVELOG

mode, see Figure 10-10.

Step 1 of 5: Archivelogs

Figure 10-48: We have selected the option to have the Archivelogs

deleted immediately after the backup.

Page 324: Oracle 10g Made Simple

324

Step 2 of 5: Backup Options

Figure 10-49: Select the Advanced Backup options and click the

“Next” button.

Step 3 of 5: Storage Media and Location

Figure 10-50: We selected Disk as storage media for backup.

Page 325: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

325

Step 4 of 5: Schedule Backup

Figure 10-51: Schedule your backup. You can also set the frequency of

backup or make it just one time only.

Step 5 of 5: Review your settings before submitting

Figure 10-52: Review your setting and click the “Submit Job” button.

Page 326: Oracle 10g Made Simple

326

The last option of “All Recovery Files on Disk” is for tape based backups. It will backup all the recovery files wherever they will to tape drive and not on the disk drive. The steps of implementation are similar to the ones discussed before and are self-explanatory.

Figure 10-53: Tape drive based backup of all the recovery files.

Enterprise Manager Database Control Based Recovery The “Perform Recovery” page link is located under Maintenance tab of EM Database Control. There are two categories of recovery available using EM Database Control: Whole Database Recovery and Object-level Recovery.

Figure 10-54: “Perform Recovery” link located under Maintenance tab.

Page 327: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

327

Figure 10-55: Zoomed area of Figure 10-1 with focus on Enterprise

Manager Database Control based Recovery Techniques.

Page 328: Oracle 10g Made Simple

328

Figure 10-56: Screenshot taken from Perform Recovery page.

Figure 10-57: In case you are running the database in ARCHIVELOG

mode then these options are available under Perform Recovery page. In case the database is running in the NOARCHIVELOG mode, see

Figure 10-59.

All these methods are self explanatory if you know the concepts from the previous chapters. There is one thing I would like to make it clear here i.e. the difference between the term “restore” and “recover”. Restore is basically putting the files back from

Page 329: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

329

backed up location to original location. The SCN will be different in all the backed up data files that’s why once you restore all the data files, recovery of database is required before making it available to users. In NOARCHIVELOG mode the recovery is very simple. All you have to do is to restore the database files from your backup to the original location and start the database.

Figure 10-58: Zoomed version of Figure 10-57.

Page 330: Oracle 10g Made Simple

330

Figure 10-59: In case you are running the database in

NOARCHIVELOG mode then these options are available.

Oracle Flash Back Technologies There are following six Flash Back Technologies exits in Oracle. All these help us in the recovery operations and compared to previous known methods present in Oracle 9i, this is another route with the benefit of Flash/Fast/Easy recovery. Flashback Database: helps to recover the whole database to a previous point in time. Flashback Drop: helps to recover the dropped table. Flashback Table: helps to recover table to a previous point in time state. Flashback Query: helps to retrieve the data for a time in the past. Flashback Version Query: helps to retrieve all the changes in data between given interval of time.

Page 331: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

331

Flashback Transaction Query: helps to retrieve all the changes in data between given interval of time. It also provides the SQL statement to undo the change. With the exception of Flashback Database, all the flashback technologies depend on undo data.

Figure 10-60: Flashback technology provides the EM Database Control

based six options which help us in the recovery operations.

Page 332: Oracle 10g Made Simple

332

Flash Recovery Area Flash Recovery Area is a single place (folder) for all the recovery-related files. One single location approach provides easy manageability. In this location we can have all the following files required in the recovery operation. Control Files: One of copy of control file is saved at Flash Recovery Area at the time of creation of database. RMAN backup sets & Image Copies: Flash Recovery Area serves the default location on the disk for RMAN backup sets and image copies. Data Files: When RMAN BACKUP AS COPY is used, the default location of data files will be Flash Recovery Area. Control File and SPFILE: Under RMAN back-up process, control file and SPFILE get backed up to this location automatically. Archived Log Files: When the Flash Recovery Area is configured, the ARCn processes create archived log files at this location. Flashback Logs: When flashback is enabled, flashback logs are generated. These flashback logs are saved at this location. How to Enable/Disable Flash Recovery Area? Setting up following two initialization parameters activates the Flash Recovery Area. DB_RECOVERY_FILE_DEST_SIZE DB_RECOVERY_FILE_DEST DB_RECOVERY_FILE_DEST_SIZE should be large enough to hold a copy of all data files, archived log files, incremental

Page 333: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

333

backups, Control file etc. Moreover, this parameter must be defined first before the other. SQL> ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE = 12G SCOPE=BOTH; This statement will set the Flash Recovery Area size to be 12 GB. SCOPE=BOTH means that this change will not only be implemented as soon as the statement executes but will remain in effect even if the database is restarted. Next we will execute the following statement to let Oracle Instance know the location of Flash Recovery Area. SQL> ALTER SYSTEM SET DB_RECOVERY_FILE_DEST = ‘/flash_recovery_area’ SCOPE=BOTH; To disable Flash Recovery Area, clear the DB_RECOVERY_FILE_DEST parameter first and then DB_RECOVERY_FILE_DEST_SIZE. Oracle manages this area by deleting the unwanted files and if the area reaches 85 percent, a warning message is written to alert log file and when it reaches 95 percent another critical message is written. These messages also appear on EM Database Control as well as under DBA_OUTSTANDING_ALERTS. For details relating the Flash Recovery Area, we can use the V$RECOVERY_FILE_DEST dynamic performance review. Oracle has also developed two commands to backup the Flash Recovery Area using RMAN. These are as follows. RMAN> backup recovery area; This command will back up the whole recovery area to tape and to back up just the files in the recovery area use the following command. RMAN> backup recovery files;

Page 334: Oracle 10g Made Simple

334

You can also create and maintain Flash Recovery Area using EM Database Control by clicking Maintenance tab and then Configure Recovery Setting. Remember that setting Mean Time To Recover (MTTR) to a very low value may reduce the crash recovery time but at the cost of lots of extra not needed check points which may reduce the overall runtime performance of the system.

Figure 10-61: Set the desired Mean Time To Recover (MTTR). If you

set it to a very low value then the actual Mean Time To Recover will be higher than your desired.

Page 335: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

335

So it’s a tradeoff between MTTR and system performance. In order to disable fast-start check pointing set FAST_START_MTTR_TARGET to zero then the check points will occurs as normal. The same Recovery Settings page provides us the control for running the database either in ARCHIVELOG mode or NOARCHIVELOG Mode. Moreover, we can also define the archive log destinations as shown in Figure 10-62.

Figure 10-62: You can control ARCHIVELOG/NOARCHIVELOG

using the ARCHIVELOG Mode check box on Recovery Settings page.

In the lower section of Recovery Settings page we can control the parameters related to Flash Recovery Area. You can define the location for Flash Recovery Area and then set its size as well.

Page 336: Oracle 10g Made Simple

336

Figure 10-63: Recovery Settings page enables us to control parameters

relating to Flash Recovery Area.

Figure 10-64: Recovery Settings page also provides the current status

of Flash Recovery Area utilization graphically.

Page 337: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

337

Flashback Database Once this feature is activated, the entire database can be taken to a state back to any specific point in time and RVWR background process gets live to write Flashback Database logs. Flashback database logs contain the before image of physical database blocks. The Flashback Recovery Area must be enabled for the Flashback database logs to be written. How to activate Flashback Database feature? The database has to be in the mounted state before enabling this feature. Step 1: Run SQL*Plus and connect as SYSDBA. C:\Documents and Settings\Administrator> SQLPLUS /NOLOG SQL> CONNECT / AS SYSDBA Step 2: The following command will start the Oracle Instance and mount the database. SQL> STARTUP MOUNT Step 3: The following statement will set the DB_FLASHBACK_RETENTION_TARGET initialization parameter to two days. The value is in minutes. SQL> ALTER SYSTEM SET DB_FLASHBACK_RETENTION_TARGET = 2880;

Page 338: Oracle 10g Made Simple

338

Step 4: The following statement will enable the Flashback database feature. SQL> ALTER DATABASE FLASHBACK ON; Step 5: Now the database is ready to make available to end users i.e. to open. SQL> ALTER DATABASE OPEN; How Flashback Database can help? We can use RMAN to perform recoveries on the Flashback Database (or database having Flashback feature on). The database has to be in the MOUNT state to perform such type of recovery. Moreover, you need to get either the OLDEST_FLASHBACK_SCN or OLDEST_FLASHBACK_TIME from a V$FLASHBACK_DATABASE_LOG dynamic performance view. Following example will take you the step by step process of taking the whole database to previous point in time using RMAN. Step 1: Run SQL*Plus and connect as SYSDBA. C:\Documents and Settings\Administrator> SQLPLUS /NOLOG SQL> CONNECT / AS SYSDBA Step 2: The following command will start the Oracle Instance and mount the database. SQL> STARTUP MOUNT

Page 339: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

339

Step 3: The first query will let you know about current SCN (System Change Number) whereas the second query will let know about both oldest_flashback_scn and oldest_flashback_time. SQL> SELECT current_scn FROM v$database; SQL>SELECT oldest_flashback_scn, oldest_flashback_time FROM v$flashback_database_log; Step 4: Get into RMAN. C:\Documents and Settings\Administrator>rman RMAN> CONNECT TARGET Step 5: In case you use SCN then use the following statement. RMAN> FLASHBACK DATABASE TO SCN=451373; In case you use the time then use the following statement. RMAN> FLASHBACK DATABASE TO TIMESTAMP (SYSDATE-1/24); Or RMAN> FLASHBACK DATABASE TO TIMESTAMP timestamp'2004-10-05 16:00:00'; Step 6: Finally open the database with RESETLOGS option as you recovered the database prior point in time. SQL> ALTER DATABASE OPEN RESETLOGS;

Page 340: Oracle 10g Made Simple

340

How to check if Flashback Database feature is ON or OFF? Use the V$Database dynamic performance view as shown below. SQL> SELECT flashback_on FROM V$Database; How to Monitor Flashback Database? Following dynamic performance views help us monitor the Flashback Database. V$Database, V$FLASHBACK_DATABASE_LOG, V$FLASHBACK_DATABASE_STAT You can also use the EM Database control to perform the Flashback Database recovery. To do this first you make sure the FLASH RECOVERY AREA is enabled and then use the Perform Recovery link under the Maintenance tab. Flashback Drop Flash back drop helps you to restore the dropped table without using tablespace point in time recovery as it was in the case of Oracle 9i. In Oracle 10g, each tablespace has its own recycle bin which holds the dropped tables. The following SQL statement is used to restore the table from the recycle bin. SQL> FLASHBACK TABLE emp TO BEFORE DROP; You can also rename the tables within one statement by following the following syntax. SQL> FLASHBACK TABLE <object_name> TO BEFORE DROP {RENAME TO <new_table_name>};

Page 341: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

341

In order to purge the table completely from the recycle bin use the PURGE command as shown below. SQL> PURGE TABLE emp; For purging the user recycle bin use the following statement. SQL> PURGE recyclebin; To purge the dba recycle bin use the following command. SQL> PURGE dba_recyclebin; The following statement purges all objects from tablespace users in the recycle bin: SQL> PURGE TABLESPACE users; To get the information of what is inside the recycle bin use the following statements. SQL> SHOW RECYCLEBIN; SQL> SELECT object_name as bin_nick, original_name FROM RECYCLEBIN; Flashback Table FLASHBACK TABLE can be used to take the table to prior point in time or prior state based on SCN. It is the fastest technique for quick data recovery for table level mistakes or data corruptions. Before running a Flashback Query, make sure that the database is running under Automatic Undo Management and you have set the UNDO_RETENTION initialization parameter. Moreover, set the undo tablespace with RETENTION GUARANTEE option, this will make sure nothing gets over written in case undo tablespace gets full before UNDO_RETENTION period.

Page 342: Oracle 10g Made Simple

342

To take the table to prior point in time, use the following SQL statement. Make sure you enable row movement at the table level first. SQL> ALTER TABLE emp ENABLE ROW MOVEMENT; SQL> FLASHBACK TABLE emp TO TIMESTAMP TO_TIMESTAMP('2007-09-10 05:20:44 PM’, ‘YYYY-MM-DD HH:MI:SS AM’); OR SQL> FLASHBACK TABLE emp TO TIMESTAMP SYSTIMESTAMP – INTERVAL ‘10’ MINUTES; This statement takes the table ‘emp’ prior to 10 minutes to the execution of the statement. The SYSTIMESTAMP gives the current system data/time. The syntax for time based flashback is as follows. You can use more than one table in place of <table_name> separated by comma (,). Each of the tables must have row movement enabled first. SQL> FLASHBACK TABLE <table_name> TO TIMESTAMP <timestamp>; Using SCN we use the following statement. Make sure you enable row movement on the table before executing flashback based on SCN. SQL> FLASHBACK TABLE emp TO SCN 183434; You can get the SCN information from the V$DATABASE dynamic performance view. SQL> SELECT current_scn FROM v$database;

Page 343: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

343

EM Database Control also provides the feature of Flashback Table. Under Maintenance tab, it can be accessed by clicking the Perform Recovery link.

Figure 10-65: Use Oracle Enterprise Manager Database Control to

enjoy Flashback Table feature. Its available on Perform Recovery page.

Flashback Query Oracle Flashback Query enables us to see the data inside the table as it existed in the prior point in time. Before running a Flashback Query, make sure that the database is running under Automatic Undo Management and you have set the UNDO_RETENTION initialization parameter. Moreover, set the undo tablespace with RETENTION GUARANTEE option, this will make sure nothing gets over written in case undo tablespace gets full before UNDO_RETENTION period.

Page 344: Oracle 10g Made Simple

344

How to activate Automatic Undo Management feature? Automatic Undo Management requires locally managed tablespace and it is done at the time of creation of database or creation of undo tablespace. By default tablespaces are created as locally managed unless you specify dictionary explicitly. Its recommend to create locally managed tablespaces and let Oracle mange the storage at the extent level. -- At the time of database creation CREATE DATABASE mydb1 CONTROLFILE REUSE LOGFILE GROUP 1 ('/mydatabases/mydb1/log01a.log', ... UNDO TABLESPACE undotbs_01 DATAFILE 'C:\Oracle\Ordata\mydb1\ undotab.dbf' SIZE 500M REUSE AUTOEXTEND ON; OR -- At the time of undo tablespace creation CREATE UNDO TABLESPACE undotab DATAFILE 'C:\Oracle\Ordata\mydb1\ undotab.dbf' SIZE 500M REUSE AUTOEXTEND ON; If you set the UNDO_MANAGEMENT initialization parameter to AUTO then Oracle Instance will automatically create undo tablespace. UNDO_MANAGEMENT is a static parameter and can be altered using the following statement with SCOPE option set to SPFILE. SQL> ALTER SYSTEM SET UNDO_MANAGEMENT=AUTO SCOPE=SPFILE;

Page 345: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

345

SQL> show parameter UNDO; NAME TYPE VALUE ----------------------- -------------- ----------- undo_management string AUTO undo_retention integer 900 undo_suppress_errors boolean TRUE undo_tablespace string undotab How to set UNDO_RETENTION? The UNDO_RETENTION initialization parameter is defined in seconds and to set it to two days use the following statement. SQL>ALTER SYSTEM SET UNDO_RETENTION = 172800; Flashback Query is a SELECT query with an AS OF TIMESTAMP clause. SQL> SELECT * FROM emp AS OF TIMESTAMP ('15-JUL-04 14:50:58','DD-MON-YY HH24:MI:SS'); OR SQL> INSERT INTO emp_temp (SELECT * FROM emp AS OF SCN 1897209); This statement will insert all the recorded changes in undo tablespace since SCN into emp_temp table.

Page 346: Oracle 10g Made Simple

346

Flashback Version Query Flashback Version Query is an enhancement to Flashback Query technology. It provides the all the versions of a specific row existed between one time to another time or between one SCN to another SCN. We use the VERSIONS BETWEEN clause of SELECT statement to make this happen. Like Flashback query, make sure that the database is running under Automatic Undo Management and you have set the UNDO_RETENTION initialization parameter. Moreover, set the undo tablespace with RETENTION GUARANTEE option, this will make sure nothing gets over written in case undo tablespace gets full before UNDO_RETENTION period. Let’s first have a look on Flashback version query based on timestamp. SELECT versions_startscn, versions_starttime, versions_endscn, versions_endtime, versions_xid, versions_operation, emp_id, emp_name FROM test_emp_table VERSIONS BETWEEN TIMESTAMP TO_TIMESTAMP('2008-01-11 15:00:00', 'YYYY-MM-DD HH24:MI:SS') AND TO_TIMESTAMP('2008-01-11 17:00:00', 'YYYY-MM-DD HH24:MI:SS') WHERE emp_name = 'ASIM'; Using SCN, the SELECT statement will look like as follows. SELECT versions_startscn, versions_starttime, versions_endscn, versions_endtime, versions_xid, versions_operation, emp_id, emp_name FROM test_emp_table VERSIONS BETWEEN SCN 1899340 AND 1899359 WHERE emp_name = 'ASIM';

Page 347: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

347

The pseudocolumns available under Flashback Version Query are as follows. VERSIONS_STARTSCN This field provides the starting System Change Number (SCN) when the row was first created inside the table. If there is NULL value in this field it means that row version was created before the lower SCN bound as defined in the BETWEEN … AND … clause. VERSIONS_STARTTIME This field provides the starting TIMESTAMP when the row was first created inside the table. If there is NULL value in this field it means that row version was created before the lower time bound as defined in the BETWEEN … AND … clause. VERSIONS_ENDSCN This field provides the ending System Change Number (SCN) when the row version expired. If there is a NULL value in this field, it means either the row is still current or it corresponds to a DELETE operation. VERSIONS_ENDTIME This field provides the ending TIMESTAMP when the row version expired. If there is a NULL value in this field, it means either the row is still current or it corresponds to a DELETE operation. VERSIONS_XID Each row version has been assigned an identifier, VERSIONS_XID field provides this information. VERSIONS_OPERATION This field provides the nature of operation happened that resulted in the row version. If it contains I, it means the version of the row created because of INSERT operation. Similarly, U represents UPDATE and D as DELETE operation.

Page 348: Oracle 10g Made Simple

348

Flashback Transaction Query Flashback Transaction Query is basically querying the FLASHBACK_TRANSACTION_QUERY view. This view not only provides the information regarding the transaction but also provides the SQL statement to undo the transaction. Like Flashback query, make sure that the database is running under Automatic Undo Management and you have set the UNDO_RETENTION initialization parameter. Moreover, set the undo tablespace with RETENTION GUARANTEE option, this will make sure nothing gets over written in case undo tablespace gets full before UNDO_RETENTION period. SELECT operation, undo_sql, logon_user FROM flashback_transaction_query WHERE xid = HEXTORAW('0A0009005F060000'); This query helps you to get the undo SQL for the VERSIONS_XID that you retrieved using Flashback Version Query. Things to Remember Before Moving Ahead

1) Figure 10-1: Oracle 10g backup and recovery techniques can be divided into 5 major categories: User Managed, RMAN based, Enterprise Manager Database Control based, Logical and Flashback Technology based.

Page 349: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

349

Chapter 11:

Oracle Performance Tuning Oracle Performance Tuning, the topic is not that scary as it sounds. Actually it’s very simple if you understand the performance tuning concept –the bigger picture or in other words bird’s eye view. Performance tuning is nothing but the collection of statistics regarding the current status of the system and then changing system values based on the statistics analysis outcome to enhance the performance. In other words performance tuning is

• Collection of system statistics • Identifying the problematic areas • Changing system based on the statistics

You can collect statistics using the built-in DBMS_STATS PL/SQL Package or through EM Database Control. In this chapter we will be using EM Database Control as a primary tool for Oracle system performance tuning.

Page 350: Oracle 10g Made Simple

350

Collection of Statistics Using AWR Oracle 10g has two new background processes. Memory Monitor (MMON) and Memory Monitor Light (MMNL). The MMON does most of the work. By default it wakes up after every hour and gathers information from data dictionary views, dynamic performance views, optimizer and then stores this information in the SYSAUX tablespace. The tables that contain this information are called the Automatic Workload Repository (AWR). These tables are stored under SYS schema. Any table name starting with “WR” belongs to AWR. The AWR tables are divided into three categories: table names starting with WRM$ represents AWR metadata tables, table names starting with WRH$ contains historical data whereas AWR tables relating to advisory functions begin with WRI$. The statistics collected in AWR are related to system and session, time-model (i.e. database response time), wait event (i.e. time a session has to wait for an event to get completed) statistics, active session history (ASH i.e. every active session with Oracle Server is sampled every second) statistics and top load SQL (i.e. SQL statements taking most of the overall system resources and adding a prominently extra burden on the server) statistics. How to activate AWR? In order to activate AWR, you first have to set the PFILE/SPFILE parameter STATISTICS_LEVEL to one the following values. BASIC: Disables the AWR. Few database statistics are gathered at each collection interval when operating the Oracle instance in this mode. TYPICAL: Setting this value will enable the AWR. This is the default value and is good for most environments.

Page 351: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

351

ALL: It captures all the statistics including those as in the case of TYPICAL plus the execution plans and timing information from the operating system. Oracle recommends setting this parameter to either TYPICAL or ALL. There is one more parameter: DBIO_EXPECTED. Its value is specified in micro seconds with a default value of 10,000. This parameter defines the average time it takes to read/write a single database block. The value of 10,000 microseconds works for most of the hard drive. In hard drive jargon it’s mentioned as the seek time. Typical it’s within the range of 5000 to 15000 microseconds. To change the default value, use the following command. What is the Retention policy of gather statistics? By default the snapshots are generated once every hour and saved in AWR with the default retention period of 7 days. You can over ride this default value either by using the Enterprise Manger Database Control or by using the supplied package i.e. DBMS_WORKLOAD_REPOSITORY. In case of EM Database Control, click <Administration> tab then <Automatic Workload Repository> link and finally <Edit> on the main screen to get to ‘Edit Settings’ window. Here you can change the retention policy as well as the frequency of statistics collections (snapshots taken). In case of supplied package, at the SQL prompt, execute the following statement. SQL> execute dbms_workload_repository.modify_snapshot_settings (interval=>60, retention=>43200); Where 43200 hours = 30 days

Page 352: Oracle 10g Made Simple

352

What happens after AWR statistics collection process completes? After the completion of AWR statistics collection process, ADDM (Automatic Database Diagnostics Monitoring) feature automatically analyzes the gathered statistics by comparing it with the previous two snapshots taken. Such analysis can help in finding out database problems e.g. the utilization of Oracle’s memory structure, lock contention, resource intensive SQL or PL/SQL, CPU bottlenecks etc. The results from ADDM are also stored in AWR. Identifying the Problematic areas using ADDM Enterprise Manager Database Control graphically displays the results of the ADDM analysis under the Performance Findings link in the “Diagnostic Summary” section. It’s also available under the “Performance” tab of main Enterprise Manger Database Control screen as well as under the Advisor Central link at the bottom.

Figure 11-1: Screenshot of portion of Performance page. There is “Run

ADDM Now” button under Average Active Session section.

Page 353: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

353

Figure 11-2: Screenshot of portion of Performance page.

Page 354: Oracle 10g Made Simple

354

Moreover, you can use the following data dictionary views to view the ADDM recommendation. DBA_ADVISOR_FINDINGS: Describes the findings identified by ADDM analysis. DBA_ADVISOR_OBJECTS: Describes the objects referenced in the ADDM analysis. DBA_ADVISOR_RECOMMENDATIONS: Contains the recommendations based on ADDM findings. DBA_ADVISOR_RATIONALE: Describes the rationale behind each finding. Advisor Central Oracle EM Database Control provides the Advisor Central section as shown in Figure 11-3. You can access it through Home page under the Related Links area. As the names states, it contains the following advisors each relates to the specific functionality/area of Oracle performance and tuning. These advisors extracts the data from dynamic performance view and other area of AWR and then generates their recommendations for better performance of Oracle Database Server overall. These advisors can help you examine several database problems along with suggestions to fix them. SQL Tuning Advisor SQL Access Advisor Memory Advisor Mean Time to Recover Advisor Segment Advisor Undo Management Advisor Let’s have a look on each of these one by one. Going into the details is beyond the scope of this book. You can easily get the details from Oracle provided documentation or doing the Google

Page 355: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

355

using the advisor name. To me it appeared as self-explanatory. All you need to remember is that there is an Advisor Central link.

Figure 11-3: On Oracle Enterprise Manager Database Control Home

page you can find the Advisor Central link under Related Links section.

Figure 11-4: Advisor Central is the hub for all advisors. Here you will

find the link for all the Oracle supplied advisors.

ADDM (Automatic Database Diagnostics Monitoring)

Here we can run ADDM either based on past instance performance (i.e. between any two snapshots taken in the past. You can select the Start Time and End Time. You will be provided with available snapshots option) or we can analyze current instance performance (i.e. using the new AWR snapshot

Page 356: Oracle 10g Made Simple

356

and having it compared with the one already taken in the past). Let’s have a look on the steps involved in generating the ADDM recommendations based on first option i.e. Run ADDM to analyze current instance performance. Step 1: For the example here we have selected first option and then clicked the OK button.

Figure 11-5: Screenshot of portion of Run ADDM (Automatic

Database Diagnostics Monitoring) page.

Page 357: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

357

Step 2: Are you sure? We clicked “Yes” button.

Figure 11-6: Oracle Enterprise Manager Database Control will confirm

your action by asking “are you sure?” kind of question.

Figure 11-7: Oracle EM Database Control will show the under

processing page.

Figure 11-8: Oracle EM Database Control will shown the message after

the completion of the task.

Page 358: Oracle 10g Made Simple

358

Figure 11-9: You can view the ADDM recommendation in case there is

some problem or click on the “View Report”. The “View Snapshots” button provides the window to actually snapshots taken in the past

point in time.

Page 359: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

359

Segment Advisor This feature is introduced in Oracle 10g and it’s used to identify segments having unused space. Once those segments have been shrunk, then the unused space can be reclaimed for other purposes. Segment Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Figure 11-10: Segment Advisor Job submission screenshot. You can

either have the whole tablespace analyzed or Schema Objects.

Page 360: Oracle 10g Made Simple

360

Memory Advisor If your enable Automatic Shared Memory then Oracle will manage the PGA and SGA memory based on Memory Advisor recommendations. Memory Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Figure 11-11: Automatic Shared Memory is enabled.

Page 361: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

361

Figure 11-13: Memory Parameters page showing PGA management

area. When Oracle Instance starts the PGA gets created.

SQL Access Advisor The SQL Access Advisor provides recommendations in terms of indexes, materialized views and partitions to achieve better performance. Materialized views, partitions, and indexes are necessary in tuning the database as they help in fast execution of complex, data intensive SQL statements. SQL Access Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Page 362: Oracle 10g Made Simple

362

Figure 11-15: SQL Access Advisor can be accessed via Advisor

Central on Home page under the Related Links section.

Page 363: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

363

SQL Tuning Advisor SQL Tuning Advisor is an intelligent system that not only analyzes the poorly executing SQL statements and gives recommendations but provides the actual commands to implement the advice/recommendation. SQL Tuning Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Figure 11-16: SQL Tuning Advisor provides links to Top Activity and

other SQL Tuning pages.

Page 364: Oracle 10g Made Simple

364

Figure 11-17: Top Activity page helps you identify high-load SQL

statements and other related information.

Page 365: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

365

Undo Management Advisor Undo Management page will gives you full control on UNDO tablespace management. It will provide you with Undo Advisor button, current undo settings, edit Undo Tablespace button along with other related information. The Undo Advisor can analyze the data and has the ability to determine how much undo has been generated then displays it in the form of graph. This helps in estimating the size of UNDO tablespace and to achieve the desired UNDO_RETENTION time. Undo Management Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Figure 11-18: Undo Management Advisor link under Advisor Central

will first take you to the Undo Management page.

Page 366: Oracle 10g Made Simple

366

Figure 11-19: Undo Tablespace Usage and Undo Retention Auto

Tuning graphical representations.

Figure 11-21: Undo Advisor page showing the Auto-tuned Undo

Retention to 15 minutes.

Page 367: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

367

MTTR Advisor The MTTR Advisor provides us with the information which helps us in making changes to FAST_START_MTTR_TARGET parameter setting of the database. This parameter enables the Oracle Instance to take certain steps in terms of setting internal triggers to achieve this mean time to recover. Remember that setting Mean Time To Recover (MTTR) to a very low value may reduce the crash recovery time but at the cost of lots of extra not needed check points which may reduce the overall runtime performance of the system. The V$MTTR_TARGET_ADVICE dynamic performance view provides the statistics collected by MTTR Advisor. MTTR stands for Mean-Time-To-Recover. To enable MTTR Advisor set the STATISTICS_LEVEL to TYPICAL or ALL and set the FAST_START_MTTR_TARGET to non-zero value. MTTR Advisor can be accessed through Advisor Central page. The link to Advisor Central page is located on Home page under Related Links section as shown in Figure 11-3.

Page 368: Oracle 10g Made Simple

368

Oracle Alerts Oracle has a built-in performance alerts mechanism relating to tablespace usage, recovery area low in free space, snapshot too told etc. Whenever an alert is generated it appears in the Alerts section of EM Database Control Home page as shown in Figure 11-23.

Figure 11-23: All alert messages are displayed on the Home page of Oracle Enterprise Manager Database Control under Alerts section.

You can get the details about the alert by clicking on the message and then taking appropriate actions based on the provided information. With the passage of time, you may end up having lots of alert messages. In order to clear alert messages, click on the Alert Log date under Diagnostic Summary on EM Database Control Home page, as shown in Figure 11-24. This action will take you to the Alert Log Errors page.

Figure 11-24: To access Alert Log Errors page click on date under the

Diagnostic Summary section.

Page 369: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

369

Finally select the alert messages you want to clear and then click on the “Clear Every Open Alert” button on the Alert Log Errors page.

Figure 11-25: Manage alert log using the Alert Log Errors page.

All Metrics All Metrics link can be accessed from Home page of Oracle EM Database Control under the Related Links section. The All Metrics page provides the comprehensive list of the entire Oracle system performance metrics nicely bundled up into categories/groups, all on one page.

Figure 11-26: All Metrics link under the Related Links section of

Performance page. You can find the same section under Home page.

Page 370: Oracle 10g Made Simple

370

Figure 11-27: Screenshot of the portion of All Metrics page.

Figure 11-28: Manage Metrics under the Related Links sections gives

the full control in setting these metrics’ threshold values.

Page 371: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

371

Figure 11-29: Manage Metrics page shows the current threshold values.

Anything going above the threshold generates a alert message. Click the “Edit Threshold” button to change the default values.

Figure 11-30: You can set the Warning and Critical Threshold values

for the given metrics.

Page 372: Oracle 10g Made Simple

372

Oracle Active Session History (ASH) ASH is mechanisms by which we can get the real-time information about the active sessions as the sessions get sampled every second. We studied Automatic Database Diagnostics Monitor earlier in this chapter; ADDM helps us identifying the problems by analyzing the data captured in AWR. But the problem in this scenario is that MMON process wakes up after every hour to gather statistics and then saves in AWR. In case there are some short-lived performance problems having a lifespan of 10 minutes or in other words less than the duration in-between the two taken snapshot then ADDM will not be able to capture such performance issues. Such performance problems are called as Transient Performance Problems and can be addressed better using Oracle provided the ASH mechanism. Its architecture is comprised of following components. ASH Memory Buffer: Portion of RAM, gets utilized in a circular fashion. MMON Lite (MMNL) process: MMNL is a new Oracle Instance’s background process which gathers active sessions’ information and moves it over to ASH memory buffer and then flushes the ASH memory buffer to AWR before it gets over written (out of space). You can view these ASH statistics using V$ACTIVE_SESSION_HISTORY dynamic performance view. In case the collected statistics are more than the size of ASH Memory buffer then you can collect the information from DBA_HIST_ACTIVE_SESS_HISTORY data dictionary view (based on WRH$_ACTIVE_SESSION_HISTORY AWR table). DBA_HIST_ACTIVE_SESS_HISTORY displays the history of the contents of the in-memory ASH statistics or in other words snapshots of V$ACTIVE_SESSION_HISTORY. Moreover, using Oracle Enterprise Manager Database Control you can have the ASH report generated at any time.

Page 373: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

373

Figure 11-31: Using Oracle EM Database Control ASH report can be

generated with the flexibility of time frame selection. The ASH Report link is available on Performance tab in Average Active Sessions block.

Figure 11-32: The almost real-time information shown under

Performance tab of Oracle EM Database Control is based on the ASH mechanism.

Page 374: Oracle 10g Made Simple

374

Figure 11-33: Generated ASH Report. It can be saved to a File as well

by clicking the “Save to File” button. The report contains detailed information about Top Events, Load Profile, Top SQL, etc.

Page 375: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

375

Things to Remember Before Moving Ahead

1) Collection of Statistics Using AWR (Automatic Workload Repository).

2) Identifying the Problematic areas using ADDM.

3) Advisor Central page of Oracle EM Database Control as shown in Figure 11-3.

4) Oracle has a built-in performance alerts mechanism relating to tablespace usage, recovery area low in free space, snapshot too told etc. Whenever an alert is generated it appears in the Alerts section of EM Database Control Home page as shown in Figure 11-23.

5) Understanding of Oracle Active Session History (ASH). Although the book ends here but the Oracle story has just begun!

Page 376: Oracle 10g Made Simple

376

Page 377: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

377

Index

$ $ORACLE_HOME, 23

“ “Group” functions, 35 “Primary/Foreign” key, 56 “Single Row” functions, 35

< <=, 30

> >=, 30

1 1521 or 1520, 232

A ABS, 45 active session history, 375 ADD_MONTHS, 43 ADDM, 376, 377, 378, 379, 381,

382, 384, 398, 402 Advisor Central, 377, 379, 380,

385, 386, 387, 388, 389, 391, 392, 393, 402

Aladdin, 14, 19 Alert Log, 395 ALL, 31

All Recovery Files on Disk, 322, 346

ALTER, 26, 88 ALTER ANY TABLE, 89 ALTER DATABASE, 88, 199, 202,

207, 218, 263, 264, 279, 280, 291, 293, 295, 303, 304, 307, 310, 361, 363

ALTER INDEX, 81 ALTER SEQUENCE, 82 ALTER SYNONYM, 84 ALTER SYSTEM, 88 ALTER TABLE, 67 ALTER TABLESPACE, 89, 220, 257,

258, 259, 261, 262, 263, 264, 292, 293, See

ALTER USER, 84, 86, 89, 91, 92, 219, 312

AND, 32 ANSI, 25 ANY, 31 ANY/SOME, 30 ARCHIVE_LOG_DEST, 218 Archived Log Mode, 97, 109 Archived Redo Log Files, 98 ARCHIVELOG, 189, 296 ARCn, 123, 125, 128, 132, 136,

137, 143, 354 ASCII, 36 ASCII('Q'), 37 ASH, 375, 398, 399, 400, 401, 402 AUTOEXTEND, 218, 219, 220, 368 Automatic Database Diagnostics

Monitoring, 376, 381, 382 Automatic Storage Management,

177, 178

Page 378: Oracle 10g Made Simple

378

Automatic Workload Repository, 106, 374, 376, 402

AVG, 51 AWR, 374, 375, 376, 379, 381,

398, 399, 402

B background processes, 112 Backup and Recovery, 258, 286,

310 Backup Sets, 299 BFILE, 66 BFT, 263, 264 BIGFILE, 263, 264 Binary Large Object, 66 BLOB, 66 broadband, 155

C Cartesian Product, 57 CEIL, 45, 46 CHAR, 65 CHARACTER SET, 218 CHECK, 71, 72 CHR, 36 CHR(84), 37 CKPT, 137 CLOB, 66 Cluster, 88 COMMIT, 26 COMPRESS, 315 CONCAT, 36, 37 connect, 214 Connect Sting, 227 CONNECT TARGET, 298 CONSTRAINT, 70 Constraints, 25, 68, 69 Control file, 15 Control File, 98 CONTROL_FILES, 212 COUNT, 51 COUNT(*), 52 CREATE, 26

CREATE TABLESPACE, 89 CREATE DATABASE, 216 CREATE INDEX, 80 CREATE PROFILE, 92 CREATE PUBLIC SYNONYM, 83, 89 CREATE ROLE, 91 CREATE SEQUENCE, 81, 89 CREATE SYNONYM, 83 CREATE TABLE, 25, 63, 64, 65, 66,

67, 68, 69, 70, 71, 72, 73, 74, 78, 89, 148

CREATE USER, 85 CREATE VIEW, 79 CTXSYS, 93

D Data Consistency, 76 Data Dictionary Cache, 120 Data files, 15 Data Files, 98 Data Integrity, 75 Data type, 25 Data Types, 65 Data Warehouse, 178 Database, 18, 19 Database Buffer Cache, 120 Database Service, 236 DATE, 65 DB_BLOCK_BUFFERS, 213 DB_BLOCK_SIZE, 100, 213, 263 DB_DOMAIN, 212 DB_FLASHBACK_RETENTION_TAR

GET, 360, 361 DB_KEEP_CACHE_SIZE, 121 DB_NAME, 187, 188, 212, 217 DB_RECOVERY_FILE_DEST, 354,

355 DB_RECOVERY_FILE_DEST_SIZE,

354, 355 DB_RECYCLE_CACHE_SIZE, 121 DB_UNIQUE_NAME, 187, 188 DBA_ADVISOR_FINDINGS, 379 DBA_ADVISOR_OBJECTS, 379 DBA_ADVISOR_RATIONALE, 379

Page 379: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

379

DBA_ADVISOR_RECOMMENDATIONS, 379

DBA_DATAPUMP_JOBS, 311 DBA_DATAPUMP_SESSIONS, 311 dbca, 173 DBCA, 151, 163, 169, 170, 171,

172, 173, 174, 175, 177, 178, 181, 183, 185, 186, 187, 189, 191, 192, 193, 197, 199, 203, 204, 205, 209, 222

dbconsole, 249 DBMS_STATS, 374 DBMS_WORKLOAD_REPOSITORY,

376 DBSNMP, 93, 185 DBWn, 135 DCL, 26, 27 DDL, 26 Dedicated Server, 131 Dedicated Server mode, 122 DEFAULT, 120 DELETE, 26 DIRECT, 315, 318 Dirty Buffers, 121 dispatcher, 126, 129, 134, 226,

229, 240 Dispatcher, 125, 134, 135, 138,

139 Division, 31 DML, 26 DMSYS, 93 Dnnn, 138 DNS, 227, 234 DQL, 26 Dr. E.F. Codd, 24 DROP, 26 DROP ANY TABLE, 89 DROP CONSTRAINT, 70 DROP INDEX, 81 DROP SEQUENCE, 83 DROP SYNONYM, 84 DROP TABLESPCE, 260 DUAL, 41, 42 DUMPFILE, 312, 313

E emctl, 249 Enterprise Edition, 152, 153, 160,

167, 175 Equijoin, 57 EXAMPLE, 107 EXISTS, 33 exp, 310, 316, 318, 319 expdp, 310, 312, 313, 314 Export, 315 Express Edition, 153 EXTENT MANAGEMENT LOCAL,

263 EXTENT MANGEMENT LOCAL,

219, 220

F FAST_START_MTTR_TARGET, 357,

393 Flash Recovery Area, 189, 190,

353, 354, 355, 356, 358, 359 Flashback Database, 351, 352,

360, 361, 363 Flashback Drop, 351, 364 Flashback Query, 351, 365, 367,

369, 370 Flashback Table, 351, 365, 366,

367 FLASHBACK TABLE, 364, 365, 366 Flashback Technology, 286, 287,

373 Flashback Transaction Query, 352,

372 Flashback Version Query, 352,

370, 371, 372 FLOOR, 45, 46 FOREIGN KEY, 73 Free Buffers, 121 Functions, 35

G General Purpose, 178

Page 380: Oracle 10g Made Simple

380

Genie, 13, 14, 15, 17, 19, 95, 111, 214

Genie’s Notebook, 95 Global Database Name, 182 GRANT, 27, 84, 86, 87, 91, 312

H Human brain, 116

I idle time, 122, 126, 129, 131, 142 Image Copies, 299 imp, 310, 319 impdp, 310, 313, 314 Import, 315 IN, 32 IN operator, 32 INCLUDING CONTENTS, 260, 261 init.ora, 98 INITCAP, 36, 38 Initialization Parameters, 196, 283 INSERT, 26, 61 INSERT ANY TABLE, 89 INSERT INTO, 62 INSTACNE_NAME, 239 Instance, 13, 18, 19 INSTANCE_NAME, 234, 238 INSTR, 36, 42 INSTRB, 36, 42 IS NULL, 34 iSQL*Plus, 24

J Java Pool, 120 Joins, 55

K KEEP, 118, 120, 121, 128

L LAN, 226 Large Pool, 120 LARGE_POOL_SIZE, 121 LAST_DAY, 43 LCKn, 138 LD_LIBRARY_PATH, 209 LENGTH, 36 LENGTHB, 36, 43 LGWR, 123, 125, 128, 132, 136,

137, 143, 189, 294 Library Cache, 120 licenses, 153 LIKE, 34 listener.ora, 226 Listeners, 230, 232 Local Naming, 227 locally managed tablespace, 220,

368 LOG_ARCHIVE_DEST, 279, 281 LOG_ARCHIVE_START, 137, 280,

281 LOGFILE, 217, 218, 281, 312, 313,

314, 368 Logical Architecture, 95, 99, 102,

259 LOGICAL_READS_PER_CALL, 93 LONG, 65 LONG RAW, 66 LOWER, 36, 38 LPAD, 36, 38 lsnrctl, 237, 238 LTRIM, 36, 39

M MAX, 51, 52 MAX_SHARED_SERVERS., 139 MAXDATAFILES, 218 MAXINSTANCES, 218 MAXLOGFILES, 217, 219 MAXLOGHISTORY, 217 MDDATA, 93 MDSYS, 93

Page 381: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

381

Mean Time To Recover, 356, 357, 393

Mean Time to Recover Advisor, 379

Memory Advisor, 379, 386 memory architecture, 99, 112,

113, 116, 117, 118, 123, 125, 128, 192

Memory Monitor, 374 Memory Monitor Light, 374 MIN, 51 MMNL, 374, 399 MMON, 374, 398, 399 MOD, 45, 48 MONTHS_BETWEEN, 43, 44 MS Access, 14, 24, 105, 239, 248,

252, 253 MS SQL Server, 24 MTTR, 356, 357, 393 Multiplexing, 107 Multiplication, 31 MySQL, 24

N Net Service Name, 227 Network Manger, 229 NOARCHIVELOG, 189, 190, 217,

218, 279, 293, 294, 296, 302, 303, 321, 322, 325, 329, 333, 338, 343, 349, 350, 351, 358

NOCATALOG, 299 NOMAXVALUE, 82 NOT, 33 NOT NULL, 68 Notebook, 19 NOVALIDATE, 71 NULL, 34 NUMBER, 65 NVL, 50

O Object Privileges, 87 OFA, 150, 151, 172, 187

OLAPSYS, 93 OLTP, 212 OMF, 150, 151, 187, 260 ON DELETE CASCADE, 70, 74 ONCA, 229 ONM, 229, 230, 231, 232, 234,

237, 239, 245, 247, 248, 252 ORA_NLS33, 209 Oracle, 25 Oracle Database, 95 Oracle Database Lite, 152, 153 Oracle Instance, 19, 95, 111 Oracle Internet Directory, 227 Oracle Managed Files, 151, 187,

260 Oracle Net, 223, 224, 225, 226,

227, 228, 229, 248, 252, 253, 256

Oracle Personal Edition, 153 Oracle SQL, 25 Oracle Universal Installer, 73, 84,

155, 157, 158, 162, 167, 173, 224

ORACLE_BASE, 171, 172, 187, 188 ORACLE_HOME, 172, 173, 187,

188, 212, 214, 221, 229, 248, 249, 316, 319

ORACLE_SID, 172 OracleRAC, 118 Oracle-Suggested Backup, 322,

324, 326 ORDER BY, 29 order of precedence, 31 ORDPLUGINS, 93 ORDSYS, 93 organizational chart, 147 OS Block, 100, 101, 109 OSDBA, 211 OUI, 155 Outer Join, 60 OUTLN, 93

P PARFILE, 311, 316, 318

Page 382: Oracle 10g Made Simple

382

PATH, 173 PGA, 118, 122, 128, 275, 276, 386,

387 physical and logical architecture,

103, 104 physical architecture, 102 Physical architecture, 96, 115 Physical Architecture, 16 ping, 227, 229 Ping, 227 Pinned Buffers, 121 PL/SQL, 22 plus (+) sign, 60 PMON, 123, 125, 128, 132, 137,

143 port, 232 Primary key, 69 PRIMARY KEY, 70, 72, 73, 74, 75,

79 protocol, 226 PURGE TABLE, 364

Q QMNn, 138

R RAM, 115 RAW, 65 RDBMS, 24 READ ONLY, 79, 257 RECO, 123, 128, 137 RECOVER DATABASE, 303, 304,

305, 306, 307, 308, 310 RECOVER DATAFILE, 296 Recovery Catalog, 106, 297, 298,

299 RECYCLE, 118, 120, 128 Redo Log Buffer Cache, 120 Redo log files, 15 Redo Log files, 97, 98, 99, 107,

108, 109, 110, 136, 137, 189, 293, 294, 296, 306

Redo Log Files, 98

redo log group, 107 Redo Log Groups page, 272, 273 REPLACE, 36, 40 Request and Response Queues,

126, 128 Request Queue, 134, 138 RESETLOGS, 305, 307, 309, 310,

363 Response Queue, 125, 138 RESTORE DATABASE, 302, 303,

304, 308, 310 REVOKE, 27, 84, 86, 87, 91 RMAN, 286, 287, 296, 297, 298,

299, 300, 301, 302, 303, 304, 306, 307, 308, 309, 310, 321, 328, 332, 337, 342, 354, 356, 361, 362, 363, 373

ROLLBACK, 26 ROUND, 43, 45, 46, 47 RPAD, 37, 39 RTRIM, 36 RUN, 301

S Schema, 63 SCN, 290, 292, 305, 307, 310, 350,

361, 362, 365, 366, 369, 370, 371

scott, 67, 206, 245, 312, 313, 314, 318

SCOTT, 56, 57, 94, 207, 312, 313, 314

Segment Advisor, 379, 385 Segments, 104 SELECT, 18, 26, 27 Self Join, 56 Self Joins, 55 Service Naming, 239 SERVICE_NAMES, 234, 238 Services, 238 Session, 18, 19 SFT, 263, 264

Page 383: Oracle 10g Made Simple

Oracle 10g Database Administration Concepts & Implementation Made Simple

383

SGA, 117, 118, 120, 121, 122, 123, 125, 128, 134, 139, 213, 275, 277, 386

Shared Memory, 118 Shared Pool, 120 Shared Server, 118, 122, 123, 124,

128, 131, 132, 133, 134, 138, 139, 142, 143, 147, 149, 195

Shared Server Mode, 131 SHARED_POOL_SIZE, 120 SHARED_SERVERS, 139 SHOW RECYCLEBIN, 365 SHUTDOWN, 216 SHUTDOWN ABORT, 216 SHUTDOWN NORMAL, 216, 288,

290 SHUTDOWN TRANSACTIONAL,

216 SID, 151, 172, 173, 181, 182, 187,

188, 211, 212, 237, 249, 298, 316, 318, 319

SIGN, 45 smallfile tablespace, 264 SMALLFILE TABLESPACE, 264 SMON, 123, 125, 128, 132, 137,

143 SOUNDEX, 36, 40 SQL, 14, 22 SQL Access Advisor, 379, 387, 388 SQL built-in functions, 35 SQL operator, 29 SQL Tuning Advisor, 379, 389 SQL*Net, 224 SQL*Plus, 22, 23, 24, 27, 64, 66,

94, 96, 206, 214, 227, 239, 248, 252, 253, 256, 360, 361

sqlplus, 214 sqlplus /nolog, 221, 222, 290, 291,

296 sqlplus username/password, 23 SQRT, 45, 48 SSA, 29 stack space, 122 Standard Edition, 152, 153, 167 Standard Edition One, 152, 167

STARTUP FORCE, 215 STARTUP MOUNT, 215 startup nomount, 214 STARTUP NOMOUNT, 215 STARTUP OPEN, 215 STARTUP RECOVER, 215 STARTUP RESTRICT, 215 STATISTICS_LEVEL, 375, 393 Sub-Queries, 33 Sub-Query, 53 SUBSTR, 36, 41 SUBSTRB, 36, 41 SUM, 51, 52 Synonyms, 78 SYS, 93, 94, 185, 206, 207, 213,

219, 221, 222, 251, 265, 374 SYSAUX, 106, 263, 264, 374 SYSDATE, 43, 44 SYSDBA, 90, 211 SYSMAN, 94, 185 SYSOPER, 90, 211 SYSTEM, 88, 93, 94, 106, 107, 121,

185, 206, 207, 218, 219, 221, 246, 250, 257, 258, 261, 262, 263, 264, 281, 301, 312, 313, 334, 355, 361, 368, 369

System Change Number, 290, 305, 307, 362, 371

System Global Area, 117, 118, 128, 213

System privileges, 88

T Tablespace, 104 TCL, 26 TCP/IP, 226 TEMP, 106, 107 tnsname.ora, 248 tnsnames.ora, 225, 226, 227, 229,

230, 239, 245, 246, 247, 248, 252, 253, 256

TO_CHAR, 48 TO_DATE, 48, 49 TO_NUMBER, 48, 49

Page 384: Oracle 10g Made Simple

384

TRANSACTIONAL, 290, 302 TRIM, 36, 39 TRUNC, 43, 45, 47 TRUNCATE, 26 TYPICAL, 375, 393

U Undo Management Advisor, 379,

391, 392 UNDO_MANGEMENT, 213 UNDO_RETENTION, 365, 367, 369,

370, 372, 391 UNDO_TABLESPACE, 213 UNDOTBS1, 106 UNIQUE, 25, 68 Unix, 7, 172, 173, 174, 175, 208,

214, 227, 229, 237, 262, 290, 292, 295, 298, 316, 319

UNTIL CHANCE, 307 UNTIL TIME, 305, 306, 308 UPDATE, 26, 61 UPDATE ANY TABLE, 89 UPPER, 36 US7ASCII, 209, 219 User-Managed Backups, 288 USERS, 107

V V$ACTIVE_SESSION_HISTORY, 399

v$datafile, 300 V$FLASHBACK_DATABASE_LOG,

361, 363 V$FLASHBACK_DATABASE_STAT,

363 V$LOG_HISTORY, 307, 310 V$MTTR_TARGET_ADVICE, 393 V$RECOVERY_FILE_DEST, 355 v$tablespace, 300 VALIDATE, 71 VARCHAR2, 65, 66, 69, 70, 72, 73,

74, 148 VERSIONS_ENDSCN, 371 VERSIONS_ENDTIME, 371 VERSIONS_OPERATION, 372 VERSIONS_STARTSCN, 371 VERSIONS_STARTTIME, 371 VERSIONS_XID, 371, 372 Views, 78 VSIZE, 50, 51

W WAN, 226 WHERE, 29, 30 WR, 374 WRH$, 374, 399 WRI$, 374 WRM$, 374