ora_sothea
description
Transcript of ora_sothea
1-1 Copyright © 2005, Oracle. All rights reserved.
Introduction
Chapter 1
1
1-2
Course ObjectivesAfter completing this course, you should be able to do
the following:– Install, create, and administer Oracle Database 10g– Understand Oracle SQL and PL/SQL– Configure the database for an application– Create and Configure Oracle Distributed Database– Can Perform Backup, Restore and Recover Database
2
1-3
Lesson Objectives
• After completing this lesson, you should be able to do the following:– Explain the Oracle Database architecture
3
1-4
Oracle Products and Services
– Oracle databases– Oracle Application Server– Oracle applications– Oracle Collaboration Suite– Oracle Developer Suite– Oracle services
4
1-5
Oracle Database Architecture
• An Oracle server:– Is a database management system that provides an
open, comprehensive, integrated approach to information management
– Consists of an Oracle Service ,Oracle instance and an Oracle database
5
1-6
Database Structures
Storage structures
Memory structures
Process structures
Instance
System Global Area (SGA)
Background processes
Database files
DB structures - Memory - Process - StorageOracle Service
6
1-7
Oracle Memory Structures .
Databasebuffer cache
Redo log buffer
Shared pool Large pool
SGA
Streams pool
Serverprocess
1PGA
Serverprocess
2PGA Background
processPGA
DB structures> Memory
ProcessStorage
7
1-8
Process Structures
– User process: Is started at the time a database user requests a connection to the Oracle server
– Server process: Connects to the Oracle instance and is started when a user establishes a session
– Background processes: Are started when an Oracle instance is started
Instance
SGA
Background
processes
Serverprocess
PGA
User process
DB structuresMemory
> Process Storage
8
1-9
Oracle Instance Management
SystemMonitor(SMON)
DatabaseWriter
(DBWn)
LogWriter(LGWR)
ProcessMonitor(PMON)
Archiver(ARCn)
SGA
Java pool
Shared pool Large poolStreams pool
Databasebuffer cache
Redo log buffer
Checkpoint(CKPT)
Controlfiles
Datafiles
Redo logfiles
Archive log files
9
1-10
Server Process and Database Buffer Cache
• Buffers:– Pinned– Clean– Free or
unused– Dirty
DBWn
Serverprocess
SGA
Databasebuffer cache
Data files
10
1-11
Physical Database Structure .
• Online redo Online redo log fileslog files
• PasswoPassword filerd file
• ParameteParameter filer file
• Archive log Archive log filesfiles
Control files • Data Data filesfiles
• Alert and Alert and trace log filestrace log files
• Backup Backup filesfiles
DB structuresMemoryProcess
> Storage
11
1-12
Tablespaces and Data Files– Tablespaces consist of one or more data files.– Data files belong to only one tablespace.
Data file 1 Data file 2
USERS tablespace
12
1-13
SYSTEM and SYSAUX Tablespaces
– The SYSTEM and SYSAUX tablespaces are mandatory tablespaces.
– They are created at the time of database creation.– They must be online.– The SYSTEM tablespace is used for core functionality
(for example, data dictionary tables).– The auxiliary SYSAUX tablespace is used for additional
database components (such as the Enterprise Manager Repository).
13
1-14
Segments, Extents, and Blocks– Segments exist within a tablespace.– Segments are made up of a collection of extents.– Extents are a collection of data blocks.– Data blocks are mapped to disk blocks.
Segment Extents Data blocks
Disk blocks
14
1-15
Logical and Physical Database Structures
15
Database
Logical Physical
Tablespace Data file
OS block
Segment
Extent
Oracle datablock
Schema
1-17
Course Examples: The HR SchemaREGIONSREGION_ID (PK)REGION_NAME
COUNTRIESCOUNTRY_ID (PK)COUNTRY_NAMEREGION_ID (FK)
LOCATIONSLOCATION_ID (PK)STREET_ADDRESSPOSTAL_CODECITYSTATE_PROVINCECOUNTRY_ID (FK)
DEPARTMENTSDEPARTMENT_ID (PK)DEPARTMENT_NAMEMANAGER_IDLOCATION_ID (FK)
JOBSJOB_ID (PK)JOB_TITLEMIN_SALARYMAX_SALARY
EMPLOYEESEMPLOYEE_ID (PK)FIRST_NAMELAST_NAMEEMAILPHONE_NUMBERHIRE_DATEJOB_ID (FK)SALARYCOMMISION_PCTMANAGER_ID (FK)DEPARTMENT_ID (FK)
JOB_HISTORYEMPLOYEE_ID (PK)START_DATE (PK)END_DATEJOB_ID (FK)DEPARTMENT_ID (FK)
REGIONS
COUNTRIES
LOCATIONS
DEPARTMENTS
JOBS
EMPLOYEES
JOB_HISTORY
17
1-18
Database Architecture:Summary of Structural Components
– Database Service– Memory structures:
• System Global Area (SGA): Database buffer cache, redo buffer, and various pools
• Program Global Area (PGA)
– Process structures:• User process and Server process• Background processes: SMON, PMON, DBWn, CKPT, LGWR,
ARCn, and so on
– Storage structures:• Logical: Database, schema, tablespace, segment, extent, and
Oracle block• Physical: Files for data, parameters, redo, and OS block
18
1-19
Summary• In this lesson, you should have learned how to:
– Install, create, and administer Oracle Database 10g– Configure the database for an application– Employ basic monitoring procedures– Implement a backup and recovery strategy– Move data between databases and files
19
1-20
End of Chapter 1
20
1-21 Copyright © 2005, Oracle. All rights reserved.
Installing the Oracle Database Software
Chapter 2
21
1-22
Objectives• After completing this lesson, you should be able to
do the following:– Describe your role as a database administrator (DBA),
and explain typical tasks and tools– Plan an Oracle database installation– Use Optimal Flexible Architecture
(OFA)– Install the Oracle software by using
Oracle Universal Installer (OUI)
22
1-23
Tasks of an Oracle Database Administrator• A prioritized approach for designing, implementing,
and maintaining an Oracle database involves the following tasks: 1. Evaluating the database server hardware2. Installing the Oracle software3. Planning the database and security strategy4. Creating, migrating, and opening the database5. Backing up the database6. Enrolling system users and planning for
their Oracle Network access7. Implementing the database design8. Recovering from database failure9. Monitoring database performance
23
1-24
Tools Used to Administer an Oracle Database
– Oracle Universal Installer– Database Configuration Assistant– Database Upgrade Assistant– Oracle Net Manager– Oracle Enterprise Manager– SQL*Plus and iSQL*Plus– Recovery Manager – Oracle Secure Backup– Data Pump– SQL*Loader– Command-line tools
24
1-25
Installation: System Requirements– Memory requirements:
• 1 GB for the instance with Database Control– Disk space requirements:
• 1.5 GB of swap space • 400 MB of disk space in the /tmp directory• Between 1.5 GB and 3.5 GB for the Oracle software• 1.2 GB for the preconfigured database (optional)• 2.4 GB for the flash recovery
area (optional)– Operating system: See
documentation.
25
1-26
Checking the System Requirements
– Adequatetemporary space
– 64-bit versus 32-bit issues
– Checks for the correct operating system (OS) – System and kernel parameters– ORACLE_HOME
26
1-27
Optimal Flexible Architecture (OFA)• OFA is designed to:
– Organize large amounts of software – Facilitate routine administrative tasks – Manage and administer database growth
adequately – Help eliminate fragmentation of free space
27
1-28
Using Optimal Flexible Architecture
– Naming mount points:• /u01• /disk01
– Naming directories:• /u01/app/oracle• /u01/app/applmgr
– Naming files:• Control files: controln.ctl• Redo log files: redon.log• Data files: tn.dbf
28
1-29
Setting Environment Variables
– ORACLE_HOME: The directory containing the Oracle software
– ORACLE_SID: The initial instance name (by default, ORCL)
– NLS_LANG: The language, territory, and client character set settings
29
1-30
Oracle Universal Installer (OUI)
30
1-31
Database Configuration Options
31
1-32
Completing Your Installation
32
1-33 Copyright © 2005, Oracle. All rights reserved.
Creating an Oracle Database
Chapter 3
33
1-34
Objectives
• After completing this lesson, you should be able to do the following:– Create a database with the Database Configuration
Assistant (DBCA)– Create a database design template with the DBCA– Generate database creation scripts with the DBCA
34
1-35
Planning the Database• As a DBA, you must plan:
– The logical storage structure of the database and its physical implementation:
• How many disk drives do you have for this?• How many data files will you need? (Plan for growth.)• How many tablespaces will you use?• Which type of information will be stored?• Are there any special storage requirements
due to type or size?– The overall database design– A backup strategy for the database
35
1-36
Databases: Examples– Data Warehouse:
• Research and marketing data• State or federal tax payments • Professional licensing (doctors, nurses, and so on)
– Transaction Processing:• Store checkout register system• Automatic teller machine (ATM) transactions
– General Purpose: • Retail billing system, for example, of a software house or
a general database.
36
1-37
Database Configuration Assistant (DBCA)
37
1-38
Using the DBCA to Create a Database
38
1-39
Using the DBCA to Create a Database
3
4
39
1-40
Using the DBCA to Create a Database
5
6
7
40
1-41
Using the DBCA to Create a Database
8
9
41
1-42
Using the DBCA to Create a Database
A
B
10
42
1-43
Using the DBCA to Create a Database
11
12
43
1-44
Password ManagementA
B
C
44
1-45
Creating a Database Design Template
45
1-46
Using the DBCA to Delete a Database
3
1
2
46
1-47
Summary
• In this lesson, you should have learned how to use the DBCA to:– Create a database– Create a database design template – Generate database creation scripts
47
1-48
Practice Overview: Using the DBCA
• This practice covers the following topics:– Creating the ORCL database by using the DBCA– Unlocking the HR schema
• Note: Completing the database creation and unlocking the HR schema is critical for all following practice sessions.
• Optionally:– Creating the ORCL database design template by using the
DBCA– Creating database creation scripts with the DBCA
48
1-49
Creating Database by Manual• Component:
- Configure Parameter File or Init File- Create Database Service- Startup Instance- Create Database - Setup System Database- Create Database Storage- Configure oracle network- Create Database Objects
49
1-50
Create Init File• Parameter File or Init File is an text file contains
parameters use to configure Database Instance while it is started up.
• Parameters are consist of:• DB_NAME=Specific name of the instance(Database)• Control_files=(Specific location and name of control file)• Undo_Management=Define how to management transaction auto or
by rollback segment• Undo_Tablespace=Name of Tablespace to keep transaction.• Processes=Number of Process allow• Sessions=number of current connection• DB_Block_Size=Size of unit write or read data into file.
50
1-5151
1-52
Create Database Service • Oracle Database Service: is an identifier of database on
network environment. It’s a service provider to clients whom whish to connect to oracle server to get service.
Syntax: On DOS Prompt
OraDim –NEW –SID nameofservice [-SYSPWD internal password –START MODE Auto|Manual -PFILE ‘Path\Parameter file name’]
52
1-53
• Syntax Delete:Syntax Delete:
• Oradim –Delete –SID Oradim –Delete –SID nameofservicenameofservice
53
1-54
Connect to Oracle Service and Create Instance:
To Create Database Instance (In-Memory Database) - Specific Oracle service (SID)SET ORACLE_SID=Oracle Service Name- Go into Oracle Utility call SQL PLUS with nolog option
SQLPLUS/NOLOG Connect to specific service(SID) by database administrator
CONNECT / AS SYSDBA
- Startup Database Instance with nomount optionSTARTUP NOMOUNT [PFILE=Path\Parameter File Name]
54
1-5555
1-56
Create Database File and Open Database Instance
56
1-5757
1-5858
1-59
Setup System
For oracle 10g and above must be configureSysAux Datafile @%Oracle_home%\rdbms\admin\catalogInstall database catalog and dynamic view@%Oracle_home%\rdbms\admin\catprocInstall PL/SQL Compiler and oracle pre-define functions and
packages.
59
1-60
Create Tablespace (Storage)• An tablespace is a pointer of data files on database
instance. There are following type of tablespace.• - System: Store system database objects• - System Auxiliary: store system object support
to system tablespace (this tablespace unavailable for oracle 9i or below.
• - Temporary tablespace: use to store query data such join, sort.
• - Undo Tablespace: This tablespace use transaction.
• - User Tablespace: Store user input data(tables)• - Index Tablespace: Store index.
60
1-61
Create Tablespace:• Create [undo] Tablespace Name-Of-Tablespace• Datafile ‘path\filename’ size initialSize • [Temporary]• [Auto extend on [Next Size IncrementalSize]
MaxSize MaximumDatafile;
61
1-62
Create net service• Net Service is representative of Oracle Service in client computer,
it’s used to connect to oracle server by application. Without netservice Application could not connect to Oracle.To create netservice
- Open “Net Manager”• - Select “Service Naming”• - Click “Edit\Create”• - Complete parameters as following• -Net Service Name: use for connecting• -Host Name: Computer Server Name(PC NAME) • -Protocol (Keep Default TCP) and Port Number
(Keep default 1521)• -Oracle Service: Oracle Service Name
62
1-63
Connect to database• On Dos:• SQLPLUS Username/password@netservicename• On SQLPLUS• Connect Username/password@netservicename
Net Service Name
63
1-64
Startup and Shutdown ServerStartup Oracle Server: is a process to create oracle instance.Startup:
- Start oracle service- Connect to oracle service by dba (database administrator)
- Set Oracle_SID=OracleServiceName- SQL/NOLOG- Connect / as SysDBA
- Startup DatabaseStartup [Option] Pfile=‘Path\
ParameterFile’Option:
Nomount: Start for creating databaseMount: Start for reconfiguring databaseOpen: Start for working and providing service.
64
1-65
Shutdown Oracle ServerShutdown Oracle Server is process to close oracle server
Connect to oracle server as sysdbaShutdown
Shutdown [Option]Option
Normal: Normally shutdown by let user disconnect oracle server by themselves.
Transactional: Wait until user save transaction then server disconnect user and shutdown instance when disconnect all user.
Immediate: Rollback all transaction and shutdown instance.
Abort: Shutdown instance without manage every thing. Check “Startup instance when instance is started”
-
65
1-66
Configure Oracle Server to Startup Auto• To let oracle server to startup automatically when Window is Started:• - Configure Oracle Service to start automatic
• - Connect Parameter File:- Connect Parameter File:
• Name:InitDBNAME.ORAName:InitDBNAME.ORA
• FOLDER: Oracle_HOME\DatabaseFOLDER: Oracle_HOME\Database
• (D:\oracle\product\10.1.0\db_2\(D:\oracle\product\10.1.0\db_2\database)database)
• - Open program “Administration Assistant for - Open program “Administration Assistant for Window”Window”
• - Select “Database\DatabaseName” Right Click->- Select “Database\DatabaseName” Right Click->
• Startup/Shutdown OptionStartup/Shutdown Option
66
1-6767
1-68
Configure Transactional• - Shutdown Server.• Open Parameter File• -Add Command• Undo_Management=Auto• Undo_Tablespace=TablespaceName
68
1-69 Copyright © 2005, Oracle. All rights reserved.
Creating Oracle Database Objects
Chapter 4
69
1-70 Copyright © 2005, Oracle. All rights reserved.
Oracle Objects
Objectives:Using Data Definition Language to create:
TableIndex
SequenceView
Synonym
To Create object:- Start Oracle Database Server
- Connect to Oracle by User “System”- Write SQL Script:
- Run Script:
70
1-71
Creating a Table• Oracle Data Type
StringString CharChar SizeSize
VarcharVarchar 40004000
Varchar2Varchar2 40004000
NCharNChar 20002000
NVarchar2NVarchar2 20002000
LongLong 2GB2GB
NumberNumber Number(N,P)Number(N,P)
IntegerInteger
FloatFloat
BinaryBinary BLOBBLOB 4GB4GB
DateTimeDateTime DateDate71
1-72
TABLE statement is as follows:CREATE Table Schema.table_name (column_name type [CONSTRAINT constraint_def DEFAULT
default_exp] [, column_name type [CONSTRAINT constraint_def DEFAULT default_exp]...]
) [TABLESPACE tab_space Storage];
72
1-73
• Schema:• Name of user to store object:• Tablespace: Name of Tablespace where table is located.Storage option define extends and segment to store table’s data
73
1-74
Constraints• Are condition of column:• Primary Key:• Foreign Key:• Unique: Do not duplicate value• Check: Set Condition for column • Not Null:
74
1-75
Index• An index is object store address of records. It’s use to
retrieve record when it’s selected.
Syntax:Create Index Name-Of-IndexOn Table_Name(ColumnName,..)Tablespace Name-of-Tablespace.Guideline:
Index set on unique column or less duplicateIndex set on columns use in where condition
75
1-76
ViewView: is virtual table to view data from tables.Syntax: Create View Name-of-View[(Col1,Col2,…)] AS Select SQL Statement.
76
1-77
Sequence:Is object use to generate autonumber.
Syntax:Create Sequence Name-Of-Sequence[Increment By Step][Start With StartNumber]
Attribute of Sequence.NextVal: .CurrVal:
77
1-78
Synonym
Is Object reference to another object:Syntax:Create [public] Synonym Name-Of-Synonymfor [Schema.]ObjectName
78
1-79
System View use to check:• DBA_Tablespaces: Store tablespace information of Server.• User_Tablespaces: Similar DBA_Tablespaces store for
current schema.• User_Tables,DBA_Tables:• DBA_Indexes,User_Indexes• DBA_Views,User_Views• DBA_Sequences,User_Sequences• *** General form: USER_ObjectTypes• Check Structure tables or views• DESC Table-Name
79
1-80
End of Chapter 4
80
1-81 Copyright © 2005, Oracle. All rights reserved.
Structured Query Language(SQL)
Chapter 5
81
1-82
Agenda
• Keyword IN and BETWEEN• Dual ?????• FUNCTIONS
– Aggregate– Numeric– String– Date
• Group By Having
82
1-83
Keywords IN & BETWEEN
• INSELECT columns FROM tablesWHERE column1 in (value1, value2, .... value_n);e.g. Select name from employee
where desig IN(‘Manager’, ‘Clerk’, ‘Worker’);
• BETWEENSELECT columns FROM tablesWHERE column1 between value1 and value2;e.g. Select name from Employee where salary between 4500 AND 7000;
83
1-84
What is DUAL???
• The DUAL table is a real table. • It’s owned by the user SYS and has one row. • The table has only one column, which is named DUMMY and
has a string with a length of 1. • The value of DUMMY in the one and only row is X.
Note: Anyone can create a table like this, with one row, and accomplish the same thing. But it’s good practice to have one place where you always have one row and you always know the table name.
84
1-85
Aggregate Functions
• AVG• MAX• MIN• COUNT• SUM• CORR• VARIANCE• STDDEV…
85
1-86
Aggregate Functions…• Select count(*) from Employee;• Select Count(Distinct(city)) from Employee;• SELECT SUM(salary) as "Total Salary“ FROM employees where
salary > 25000;• SELECT SUM(sales * 0.10) as "Commission“ FROM order_details;• SELECT MIN(salary) as "Lowest salary“ FROM employees;• SELECT MAX(salary) as "Highest salary“ FROM employees;• SELECT Avg(salary) as "Avg Salary“ FROM employees WHERE salary >
25000;• SELECT Avg(sales * 0.10) as "Average Commission“ FROM orders;• select stddev(salary) from employee;
86
1-87
Numeric Function
• ABS• ACOS• BITAND• CEIL• COS• COSH• EXP• FLOOR• LN• MOD
• NANVL• POWER• ROUND• SIGN• SIN• SQRT• TAN• LEAST• GREATEST
87
1-88
Numeric Function…
• Select abs(23.65) from dual;• Select abs( 12.34 * -2) from dual;• Select bitand(6,2) from dual;• Select acos(0.35) from dual;• Select ceil(32.65) from dual; would return 33.• Select ceil(-32.65) from dual; would return -32• Select floor(32.65) from dual; would return 32.• Select floor(-32.65) from dual; would return -33• Select exp(3) from dual;• Select ln(20) from dual;
88
1-89
Numeric Function…• Select greatest(2, 5, 12, 3) from dual; would return 12• Select greatest('2', '5', '12', '3') from dual; would return '5'• Select greatest('apples', 'oranges', 'bananas') from dual; • Select least(2, 5, 12, 3) from dual; would return 2• Select least ('2', '5', '12', '3') from dual; would return ‘12‘• Select least ('apples', 'oranges', 'bananas') from dual;• Select mod(15, 4) from dual;• Select power(3, 2) from dual;• Select sqrt(5.617) from dual;• Select sign(-0.675) from dual; would give -1• Select sign(0) from dual; would give 0• Select sign(7.0001) from dual; would give 1
89
1-90
String Function
• TRIM• LTRIM• RTRIM• ASCII• CHR• LPAD• RPAD• CONCAT
• INSTR• INITCAP• LENGTH• LOWER• UPPER• REPLACE• SUBSTR
90
1-91
String Function…• TRIM( [ leading | trailing | both [ trim_character* ] ]
string1 )select TRIM('A' from 'AABABAB4AAA') from dual;select TRIM(LEADING 'A' from 'AABABAB4AAA') from dual;select TRIM(TRAILING 'A' from 'AABABAB4AAA') from dual;select TRIM(BOTH 'A' from 'AABABAB4AAA') from dual;• CONCAT(string1, string2)select concat('a','b') from dual;Select ‘a’ || ‘b’ from dual;
91
1-92
String Function…• LPAD(string, length, [set])lpad('tech', 7); would return ' tech'lpad('tech', 2); would return 'te'lpad('tech', 8, '0'); would return '0000tech'lpad(‘this is my text', 15, 'z'); would return ' this is my text'lpad(' this is my text', 16, ‘#'); would return ‘#this is my text '• RPAD(string, length, [set])rpad('tech', 7); would return 'tech 'rpad('tech', 2); would return 'te'rpad('tech', 8, '0'); would return 'tech0000'rpad(' this is my text', 15, 'z'); would return ' this is my text'rpad(' this is my text', 16, ‘$'); would return ' this is my text$'
92
1-93
String Function…
• LTRIM(string, [set])ltrim(' tech'); would return 'tech'ltrim(' tech', ' '); would return 'tech'ltrim('000123', '0'); would return '123'ltrim('123123Tech', '123'); would return 'Tech'ltrim('123123Tech123', '123'); would return 'Tech1ltrim('xyxzyyyTech', 'xyz'); would return 'Tech'• RTRIM(string, [set])rtrim('Tech123123', '123'); would return 'Tech'rtrim('123Tech123', '123'); would return '123Tech'
93
1-94
String Function…• LOWER(string)lower('GEORGE BURNS 123 '); would return 'george burns 123 '• UPPER(string)upper('george burns 123 '); would return 'GEORGE BURNS 123 '• INITCAP(string)initcap('GEORGE BURNS'); would return 'George Burns'• LENGTH(string)length(''); would return NULL.length(‘hello'); would return 5length(‘ hello '); would return 7• SUBSTR(string, [count])substr('This is a test', 6) would return 'is a test'substr('TechOnTheNet', 1, 4) would return 'Tech‘substr('TechOnTheNet', -6, 3) would return 'The'
94
1-95
String Function…• REPLACE( string1, string_to_replace, [ replacement_string ] )
replace('123123tech', '123'); would return 'tech'replace('123tech123', '123'); would return 'tech‘ -replace('222tech, '2', '3'); would return '333tech'replace('0000123', '0'); would return '123‘
• CHR( number_code )chr(116); would return 't'chr(84); would return 'T‘• ASCII( single_character )ascii('t') would return 116ascii('T') would return 84ascii('T2') would also return 84
95
1-96
String Function…
• INSTR( string1, string2, [ start_position ], [ nth_appearance ] )
instr('this is my text', ‘s') ;would return 4 instr(‘this is my text', ‘s', 5, 1) would return 7 instr('this is my text', ‘s', 1, 2) would return 7 instr('this is my text', ‘s', -7, 2) would return 4
96
1-97
Date Functions
• SYSDATE• SYSTIMESTAMP• ADD_MONTHS• CURRENT_DATE• CURRENT_TIMESTAMP• EXTRACT• MONTHS_BETWEEN• LAST_DAY• NEXT_DAY
97
1-98
Date Functions…• SysdateSelect emp_name, sysdate from employee;
• SYSTIMESTAMPSELECT SYSTIMESTAMP FROM dual;
• add_months( date1, n )add_months('01-Aug-03', 3) would return '01-Nov-03'add_months('01-Aug-03', -3) would return '01-May-03‘
• Current_Timestamp
select systimestamp from dual;
ALTER SESSION SET TIME_ZONE = '+5:30';
select current_timestamp from dual;
select systimestamp from dual;
98
1-99
Date Functions…
• NEXT_DAY( date, weekday )Where weekday: Monday, Tuesday…e.g.Select next_day(sysdate, ‘MONDAY’) from dual;• LAST_DAY(date)select last_day(sysdate) LAST_DATE from dual;• MONTHS_BETWEEN(date1, date2 )select months_between(sysdate,
to_date('1/1/2005', 'dd/mm/yyyy')) from dual;
99
1-100
GROUP BY• The GROUP BY clause, along with the aggregate functions, groups a result
set into multiple groups, and then produces a single row of summary information for each group.
• If we have a mix of aggregate and nonaggregate expressions in the SELECT list, SQL expects that we are trying to perform a GROUP BY operation, and we must also specify all nonaggregate expressions in the GROUP BY clause.
• When we GROUP BY a column that contains NULL values for some rows, all the rows with NULL values are placed into a single group and presented as one summary row in the output.
• While using GROUP BY Clause, we can filter records from the table based on a WHERE clause.
100
1-101
GROUP BY…e.g.
select max(salary), min(salary), desig, avg(salary) from employee group by desig;
Group By with NULL values;select count(*), department from employee group by department;
With where Clauseselect max(salary), min(salary), desig, avg(salary), count(*) from employee where salary > 5000 group by desig;
101
1-102
GROUP BY HAVING
• The HAVING clause is used to put a filter on the groups created by the GROUP BY clause. If a query has a HAVING clause along with a GROUP BY clause, the result set will include only the groups that satisfy the condition specified in the HAVING clause.
e.g.select desig, max(salary), avg(salary) from employeegroup by desighaving avg(salary) > 5000;
102
1-103
ORDER BY• The SQL ORDER BY clause comes in handy when you want to sort your
SQL result sets by some column(s).SYNTAX:
Select <field_name(s)> from <table_name(s)> ORDER BY <EXPR>, <FIELD(s) NAME>[ASC | DESC ]
• Specifies a column(s) on which to sort.• The ORDER BY clause can include items not appearing in the select list,
but in case of using keywords like DISTINCT then the sort columns must appear in the select list
103
1-104
Select Revisited
• Complete Syntax:SELECT select_list
FROM table_source [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ]
104
1-105
JOINBy using joins, you can retrieve data from two or more tables
based on logical relationships between the tables.
A join condition defines the way two tables are related in a query by:
• Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table.
• Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
105
1-106
JOIN…
Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.
Syntax:FROM first_table join_type second_table [ON
(join_condition)]
106
1-107
JOIN…
Joins can be categorized as: • Inner joins (the typical join operation, which uses some
comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.
• Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.
• Outer joins can be a left, a right, or full outer join.
107
1-108
OUTER JOINOuter joins are specified with one of the following sets of keywords when
they are specified in the FROM clause:
• LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.
• RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.
• FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
108
1-109
JOINBy using joins, you can retrieve data from two or more tables based on logical relationships between the tables.
A join condition defines the way two tables are related in a query by:
• Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table.
• Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.
109
1-110
JOIN…
Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.
Syntax:FROM first_table join_type second_table [ON
(join_condition)]
110
1-111
JOIN…
Joins can be categorized as: • Inner joins (the typical join operation, which uses some
comparison operator like = or <>). Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.
• Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.
• Outer joins can be a left, a right, or full outer join.
111
1-112
OUTER JOINOuter joins are specified with one of the following sets of keywords when
they are specified in the FROM clause:
• LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.
• RIGHT JOIN or RIGHT OUTER JOIN. A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.
• FULL JOIN or FULL OUTER JOIN. A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
112
1-113
Scalar Subqueries
• The Scalar Subquery can be used anywhere a value can be used.
• When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery.
• When the subquery returns no rows, a database null is used as the result of the subquery.
• Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
113
1-114
Predicate Subqueries
• Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct.
IN Subquery – The IN Subquery tests whether a scalar value
matches the single query column value in any subquery result row.
General Syntax:1. value-1 [NOT] IN (query-1)
114
1-115
Predicate Subqueries…2. value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1)
• The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row.
• The ANY, ALL, SOME specifiers give the type of match expected.
• ANY and SOME must match at least one row in the subquery.
• ALL must match all rows in the subquery
115
1-116
• EXIST Subquery– The EXISTS Subquery tests whether a subquery
retrieves at least one row, that is, whether a qualifying row exists.
General Syntax: EXISTS(query-1)
116
1-117
Table Subqueries
• Table Subqueries are queries used in the FROM clause, replacing a table name.
• Its the result set of the Table Subquery acts like a base table in the from list.
• Table Subqueries can have a correlation name in the from list.
117
1-118
Scalar Subqueries
• The Scalar Subquery can be used anywhere a value can be used.
• When the subquery returns a single row, the value of the single select list column becomes the value of the Scalar Subquery.
• When the subquery returns no rows, a database null is used as the result of the subquery.
• Should the subquery retreive more than one row, it is a run-time error and aborts query execution.
118
1-119
Predicate Subqueries
• Predicate subqueries are used in the WHERE (and HAVING) clause. Each is a special logical construct.
IN Subquery – The IN Subquery tests whether a scalar value
matches the single query column value in any subquery result row.
General Syntax:1. value-1 [NOT] IN (query-1)
119
1-120
Predicate Subqueries…2. value-1 {=|>|<|>=|<=|<>} {ANY|ALL|SOME} (query-1)
• The comparison operator specifies how to compare value-1 to the single query column value from each subquery result row.
• The ANY, ALL, SOME specifiers give the type of match expected.
• ANY and SOME must match at least one row in the subquery.
• ALL must match all rows in the subquery
120
1-121
Predicate Subqueries…
• EXIST Subquery– The EXISTS Subquery tests whether a subquery
retrieves at least one row, that is, whether a qualifying row exists.
General Syntax: EXISTS(query-1)
121
1-122
Table Subqueries
• Table Subqueries are queries used in the FROM clause, replacing a table name.
• Its the result set of the Table Subquery acts like a base table in the from list.
• Table Subqueries can have a correlation name in the from list.
122
1-123
NULLS"As we know, There are known knowns. There are things we know we know. We also know There are known unknowns. That is to say We know there are some things We do not know.”- Donald Rumsfeld
• What is NULL ?????- NULL as "a special value, or mark, that is used
to indicate the absence of any data value." - NULL in SQL is not a "data value", but rather
an indicator that we have missing data
123
1-124
NULLS…
• Nulls in Conditions:Condition Value of A Evaluationa IS NULL 10 FALSEa IS NOT NULL 10 TRUEa IS NULL NULL TRUEa IS NOT NULL NULL FALSEa = NULL 10 UNKNOWNa != NULL 10 UNKNOWNa = NULL NULL UNKNOWNa != NULL NULL UNKNOWNa = 10 NULL UNKNOWNa != 10 NULL UNKNOWN
124
1-125
NULLS…
• Nulls in SQL FunctionsAll scalar functions (except REPLACE, NVL, and CONCAT) return null when given a null argument.
NVL( string1, replace_with )e.g.
select emp_name, nvl(department, 'N/A') from employee;
125
1-126
Alter Table
ALTER TABLE table_nameADD ( column_1 column-definition,column_2 column-definition,...column_n column_definition );
ALTER TABLE table_nameMODIFY ( column_1 column_type,column_2 column_type,...column_n column_type );
126
1-127
Alter Table…
ALTER TABLE table_nameDROP COLUMN column_name;
ALTER TABLE table_name SET UNUSED column_name;
ALTER TABLE table_nameRENAME COLUMN old_name to new_name;
127
1-128
Alter Table…
The Rules for Adding or Modifying a Column• You may add a column at any time if NOT
NULL isn’t specified.• You may add a NOT NULL column in three
steps:1. Add the column without NOT NULL specified.2. Fill every row in that column with data.3. Modify the column to be NOT NULL.
128
1-129
Alter Table…
• These are the rules for modifying a column:– You can increase a character column’s width at any time.– You can increase the number of digits in a NUMBER column at any
time.– You can increase or decrease the number of decimal places in a
NUMBER column at any time.
• In addition, if a column is NULL for every row of the table, you can make any of these changes:– You can change the column’s datatype.– You can decrease a character column’s width.– You can decrease the number of digits in a NUMBER column.
129
1-130
Alter Table…e.g.- Alter table mytable
Add constraint pk_mytable PRIMARY KEY (a);- alter table mytable
add b varchar2(50);- Alter table emp_hourly
MODIFY (HOURRATE NUMBER(5,2) DEFAULT 7.25);- Alter table mytable
RENAME CLOUMN a TO z;- Alter table mytable
RENAME to mynewTable;
130
1-131
RENAME
e.g.Rename mynewtable to mytable;
RENAME old_table_name TO new_table_name;
131
1-132
DROP Table
e.g.
DROP table mytable;
DROP TABLE table_name;
132
1-133
PL/SQL
Chapter 6
133
1-134
PL/SQL
• Lesson Objectives• Introduction to PL/SQL• SQL Review• Basic PL/SQL• Trigger• Store Procedure and Function• Package
134
1-135
IntroductionWhat is PL/SQL: PL is stand for Procedural Language.PL/SQL= {Procedural or Structure Programming Language}
+ SQL
PL/SQL is a procedural programming language which improving from SQL Language by added structured programming feature in order to process business logic of information system.
135
1-136
Feature of PL/SQLPL/SQL use to develop business logic layer of
application which run on server-side.Feature of Server-Side Code are:
- Good performance- Reduce network traffics- High security- High reusable
136
1-137
SQL• There are 3 types of SQL Command:• DDL: Data Definition Language. There are follow command of DDL• - Create : for creating objects• - Alter: for modifying objects• - Drop: for removing objects• DML (Data Manipulated Language): Use to manipulate data. DML
Consist of • - Select• - Insert• - Delete• - Update• DCL(Data Control Lanaguage) begin tran, commit,rollback,save tran
137
1-138
DML (Continue)Select Statement: for reading data from databases,
the select statements return rows from tables:Syntax:Select *|Col1,Col2,…..From Table | Joined Tables[Where Condition][Group By Col1,Col2,…][Having Condition][Order by Col1,Col2,…]
138
1-139
Transaction SQLInsert: for inserting records into tables:
Syntax1:Insert Into Table_Name[(Col1,Col2,…)]Values(val1,val2,…)Syntax2Insert Into Table_Name[(Col1,Col2,…)]Select co1l,col2,…from TableName….
Delete: for removing records (data) into tables:Delete from Table_Name[Where Condition]
Update: for modifying records (data) in tables:Update Table_Nameset Col1=Expr,Col2=Expr,…
[Where Condition]
139
1-140
Basic PL/SQLDeclare Variable:PL/SQL is a structure programming language. Before use a variable
must be declare above the body of program.Syntax:
Declare varname1 Datatype[:=initialvalue]; VarName Datatype[:=initialvalue];
ExampleDeclare
x integer;
Str varchar2(20):=‘BBU’;
140
1-141
PL/SQL Data Type• PL/SQL Data Type is similar to Oracle Database Data Type,
However the size of some data type is difference• Example varchar2 in database is 4K in pl/sql is 32k
• %TYPE is use to declare a variable to match with the other.• Example• Declare • s varchar2(20);• s1 s%type;• pcode tblProducts.ProductCode%Type;• %RowType is use to declare a variable to match a record type of a
table or cursor.• Example• Declare prow tblProducts%RowType
141
1-142
Assignment and Operator• Assignment is most important operator. In oracle we can assign to a
variable an expression or value which on memory or we can select a value from a column or row of table then assign direct to variable.
• Syntax1:• VarName:=Expression;• Syntax2
Select Col1,Col2,…. INTO var1,var2 from tablename,.[Where Condition]
Syntax 1 is assign a value or expression value to varnameSyntax 2: is select a single row of data of col1,col2 from table
then assign to var1,var2
142
1-143
Assignment (Cont)• Example:• Declare Code Varchar2(10);• price float;• Qty Integer;• …• …..• -- Assign ‘P001’ to Code• Code:=‘P001’;• -- Select Quatity and UnitPrice from tblProducts then
assign to price and Qty.• Select Quantity,UnitPrice Into Qty, Price from
tblProducts • Where ProductCode=‘P001’;
143
1-144
Operator
144
1-145
Control StructureIF StatementSyntax:If Condition then Statements;[elsif condition then
statements;Elsif condition then
statements;…..][Else
statements;]End if;
145
1-146
Loop StatementSyntaxLoopStatement1;Statement2;Exit When Condition;….End Loop;Loop execute by repeating statement1,statement2,.... To exit loop use following:
Exit When Condition or if Condition Then Exit
146
1-147
While LoopSyntaxWhile Condition LoopStatement1;Statement2;……………….
End loop;
147
1-148
For StatementIn oracle for statement can be used to loop and scan value in
collection of value or collection of records the counter variable will automatic define it data type to match collection.
SyntaxFor counter IN Collection Loop
Statements;Statements;Statements;
End Loop;
148
1-149
For StatementExample:
for I in 1..100 loopStatements;
end loop;-- statement I run from 1 to 100
For pRow IN (Select * from tblProducts) LoopStatements;
END LOOP;In above statement pRow is a record variable which will be
stored each record.
149
1-150
Case StatementIn oracle case statement, use to return value like a value.Syntax1:Case When Condition Then Value1
When Condion Then Value2…..
[else valN]ENDSyntax 2Case Expression
When val1 Then Value1When val2 Then Value2[else valN]
END;
150
1-151
CURSORCursor is a data type which its variable use to store address of records
returned from select statement.Declare
Cursor Cursor_Name[(Parameter,…)] is select statement;To use cursor first open cursor then read data from cursor parse to variableSyntax Open
Open Cursor_name[(arg,…)]Syntax Read
Fetch Cursor_Name into var_name;Var_name must be declare as Cursor_name%rowtype.The fetch statement always move next rows while eof theAttribute cursor_name%notfound=trueClose Cursor Close Cursor_Name
151
1-152
Trigger• Trigger is a special procedure or sub program is bound to
a table’s transaction and will be execute when the bound table receive transaction. There two type of Trigger: Row Trigger and Statement Trigger
• Row trigger is trigger which will execute every row effect by transaction.
• Statement trigger is execute a time for every statement. It’s does not depend on how many rows created by transaction
152
1-153
TriggerSyntax:Create [or replace] trigger trigger_name After|Before TransactionOn Table_name[For Each row][When condition]--Declare partsBegin--PL/SQL Codes;End;Transaction : [INSERT [Or Delete Or [Update [of ColumnName,
…]]]
153
1-154
Trigger• :New and :Old• :New is a trigger parameter store the inserted
records and new records of update statement.• :Old is a trigger parameter store the deleted
records and previous records of update statement.
• INSERTING,DELETING,UPDATING is a Boolean parameter use to recognize transaction type.
154
1-155
Procedure and FunctionCreate [Or Replace] Procedure Name-Of-Procedure(Par,…..) IS--Variable declarationBegin--PL/SQL Statement;End;
Create Or Replace Function Name-Of-Function (Par,Create Or Replace Function Name-Of-Function (Par,…..) Return DataType IS…..) Return DataType IS
--Variable declaration--Variable declaration
BeginBegin
--PL/SQL Statement;--PL/SQL Statement;
Return Value,-- return the value to functionReturn Value,-- return the value to function
End;End;155
1-156
Procedure and FunctionParameters are variable use for receiving value from argument
and parsed value to arguments.Syntax:
Par-Name [IN|OUT|IN OUT] DataType
IN parameters use to receive value only from clients;OUT Parameter use to parse value from server to client’s
arguments.IN OUT parameter for both receive and parsed.Parameter cannot specific size
156
1-157 Copyright © 2005, Oracle. All rights reserved.
Oracle Security
Chapter 7
157
1-158
• Learning Topics:• Create Users• Privileges and Granting Privileges• Role• Auditing Users
158
1-159
Create UsersA user is a key to access database. An user must be provided some
privileges (right) for access database objects and perform tasks.
Syntax Create User
Create User UserName Identified by password[Password expire][Default Tablespace name-of-tablespace][Temporary tablespace name-of-temporary-tablespace][Quota {Size|Unlimited} on Tablespace-Name]---------;
159
1-160
Create Users(Continue)- User-Name must be string and no duplicate Password is user password Password Expire an option for user change password at first
time log on Default tablespace is tablespace to store object will be created
by users. Temporary tablespace is name of temporary tablespace will
store data query of users. Quota is the permission to use tablespace
160
1-161
Create User (Example)• Ex1• Create User BBUMSC Identified by bbu• Password Expire• Default tablespace users• Temporary tablespace temp• Quota 100M on Users;• Ex2:• Create User BBUCEO• Identified by bbumanager• Temporary tablespace temp;
161
1-162
PrivilegesPrivilege is right to access oracle system:There are two type of Privileges System PrivilegeAnd Object Privileges
System Privileges: Right to access system resources. System Privileges consist of:Create Session Select ANY TABLEINSERT ANY TABLEUPDATE ANY TABLEDELETE ANY TABLECREATE TABLE,CREATE VIEW,CREATE TABLESPACE,….
162
1-163
Privileges (Continue)Granting System Privileges:
Grant Privileges,… to USERNAME[With Grant Option]
ExampleGrant Create Session,Select Any Table,Create
Tablespace,Create Table to BBUMSC;
163
1-164
Privileges (Continue)Are right to access data in table, view and execute store
procedure, function and package:Object Privileges consist of:SelectInsertDeleteUpdateExecuteSyntax: Granting Object Privileges:Grant All|Select,Insert On ObjectName to UserName[With Grant Option];Example:Grant All on Students to BBUMSC;
164
1-165
RolesRole is a set of privileges use to grant to users.
Syntax Create Role:Create Role RoleName;To grant privileges to role is the same user.Example:Create Role StudentRole;Grant create session,Select any table to StudentRole;Grant StudentRole to BBUMSC;
165
1-166
Auditing UserUse to control action of users who access to oracle
system.Syntax:Audit option,.. [by user][by access|by session][whenever [not] successful];Audit Option
- Select Table- Delete Table- Update Table- Insert Table- Session- ……..
166
1-167
Auditing User (Continue)• To set audit user:
- Set Parameter file AUDIT_TRAIL=True
- User Audit Command- Check Audit on view
167
1-168
End of Chapter 7
168
1-169 Copyright © 2005, Oracle. All rights reserved.
Oracle Backup & Recovery
Chapter 8
169
1-170
Oracle Backup & Recovery• 4-1 Backup/Recovery Basic• 4-2 Oracle Backup/Recovery Configuration• 4-3 Physical Backups• 4-4 Types of Failure and Troubleshooting• 4-5 Oracle Recovery without Archiving• 4-6 Complete Recovery with Archiving • 4-7 Incomplete Recovery with Archiving• 4-8 Recovery when loss of Control Files / Online
Redo Logfiles
170
1-171
Oracle backup/recovery basic
• Backup methods• Backup strategy
171
1-172
Backup methods• Logical backup
– export/import• Database, user, table, table partition• full• increasement
• Physical backup– cold/offline backup
• full• increasement
– hot/online backup• full• Increasement
– archive log backup
172
1-173
Backup strategy
• Determinded by – Business– Technical– Management– Mean-time to recover
173
1-174
Determine backup strategy• Ask customer:
– What’s your backup strategy now?– How many data can you loss?– How long can your database be shutdonw?– How long can you allow to backup?– How long can you allow to recover?– How many archived logs per day?– How many free disk space do you have to store the
archived logs?– Do you consider about standby database?
174
1-175
Objectives
• Identify recovery implications of operating in “Noarchive” mode
• Describe the differences between “Archivelog” mode and “Noarchivelog” mode
• Configure a database for “Archivelog” mode and automatic archiving
• Use init.ora parameters to duplex archive log files
175
1-176
Overview
• Noarchivelog or Archivelog Mode– Decision to use one or the other is
dependent upon how much data can be lost due to a failure.
176
1-177
Online redo Online redo log fileslog files
053
No redo No redo historyhistory
NOARCHIVELOG Mode
054
054
053
053
LGWR
177
1-178
Archivelog Mode
Online redo Online redo log fileslog files
LGWR
Archived log filesArchived log files
054
054
053
053 053
052
051
Redo historyRedo history
178
1-179
Configuring for Archiving
ARCH
LOG_ARCHIVE_DEST=/archive/archLOG_ARCHIVE_DEST=/archive/arch
LOG_ARCHIVE_FORMAT=%s.arcLOG_ARCHIVE_FORMAT=%s.arc
/archive/arch052.arc
Archived log Archived log filefile
Online redo log filesOnline redo log files
053
053
052
Group 1Group 1 Group 2Group 2
052
052
179
1-180
Duplexing Archived Log Files
ARCH
Online redo log filesOnline redo log files
053
053
052
052
LOG_ARCHIVE_DUPLEX_DESTLOG_ARCHIVE_DUPLEX_DEST
052
052
Group 1Group 1 Group 2Group 2
LOG_ARCHIVE_DESTLOG_ARCHIVE_DEST
Archived log filesArchived log files
180
1-181
Changing Database Archive Modes
• Startup and mount the database• Alter the mode of the database• Shutdown in normal or immediate• Take a full closed database backup• Startup and open the database
181
1-182
Enabling Archive Processing
• Automatic archiving
• Manual archiving
ARCH
053
053053
053
DBADBA
182
1-183
Manual Archive
ALTER SYSTEM ARCHIVE LOG all;
1
2
ARCH052
051 052
3
051Online redo Online redo logslogs
183
1-184
Automatic Archiving
ARCH
052051
Archived log Archived log filesfiles
053 051
052
ArchivedArchivedArchivedArchived
CurrentCurrent
LOG_ARCHIVE_START=TRUELOG_ARCHIVE_START=TRUE
Online redo Online redo logslogs
184
1-185
Obtaining Archive Log Information
V$ARCHIVE_DESTV$ARCHIVE_DEST
V$ARCHIVED_LOGV$ARCHIVED_LOG
V$LOG_HISTORYV$LOG_HISTORY
• Data dictionary views
• Command line
ARCHIVE LOG LIST;
V$DATABASEV$DATABASE
185
1-186
Summary
Complete database recovery requires:• Archivelog mode• Automatic archiving• A database backup immediately after it is
put into archivelog mode
186
1-187
Exercise 4-2• 1. See database is running on archive or noarchive log
mode:– svrmgr>select * from v$database;
• 2. Set database to archive log mode:– Edit init_sid.ora files
• archive_log_dest• archive_log_format (see Oracle References about values)• log_archive_start
– svrmgr> shutdown immediate;– svrmgr> startup mount;– svrmgr> alter database archivelog;– svrmgr> alter database open;
187
1-188
Exercise 4-2
• 3. Check archive log configuration:– Check the archive process:
• $ps –ef|grep arch
– Check archive log parameters:• svrmgr> show parameter arch
188
1-189
Objectives•Perform database backups using operating system commands•Describe the recovery implications of closed and open database backups•Perform closed(offline) and open(online) database backups•Identify the different types of control file backups•List the data dictionary views useful for backup operations
189
1-190
Backup methods• Logical backup
– export/import• Database, user, table, table partition• full• increasement
• Physical backup– cold/offline backup
• full• increasement
– hot/online backup• full• Increasement
– archive log backup
190
1-191
Backup Methods
Physical backupPhysical backup
Closed databaseClosed database Open databaseOpen database
Archive Archive ModeMode
No archive No archive ModeMode
191
1-192
Closed Database Backup
DatafilesDatafiles Control Control FilesFiles
PasswordPasswordFileFile
Online or Online or Offline Offline
StorageStorage
Parameter Parameter FilesFiles
Redo Log Redo Log Files Files
192
1-193
Advantages of ClosedDatabase Backups
•Conceptually simple•Easy to perform•Requires little operator interaction•Reliable
193
1-194
Database File Information
–Data dictionary viewsV$DATAFILEV$DATAFILE
V$CONTROLFILEV$CONTROLFILE
V$LOGFILEV$LOGFILE
DBA_DATA_FILESDBA_DATA_FILES
194
1-195
Performing a Closed Database Backup
2
3
4
SHUTDOWN IMMEDIATE;
HOST cp <files> /backup/
STARTUP OPEN;
Data FilesData Files Control Control FilesFiles
Parameter Parameter FilesFiles
1
195
1-196
Open Database Backup
DatafilesDatafiles
Control Control FilesFiles
Parameter Parameter FilesFiles Archived RedoArchived Redo
Log FilesLog FilesPassword FilePassword File
Online Online RedoRedo
Log FilesLog Files
196
1-197
Advantages of OpenDatabase Backups
•Maintains high database availability•Can be done at a tablespace or datafile level•Allows recovery to point-in-time
197
1-198
Archived Log FilesArchived Log Files
ARCH
Archivelog ModeArchivelog Mode
Online Redo Online Redo Log FilesLog Files
LGWR
054
054
053
053052
051
Open Database Backup Requirements
053
198
1-199
Open Database Backup Options
All tablespace All tablespace datafilesdatafiles
Tablespace Tablespace USER_DATAUSER_DATA
user02.dbfuser01.dbf
Individual Individual datafiledatafile
user02.dbf
Tablespace Tablespace USER_DATAUSER_DATA
user01.dbf
199
1-200
Performing an Open Database Backup
1ALTER TABLESPACE user_data BEGIN
BACKUP;
2HOST cp <files> /backup/
3ALTER TABLESPACE user_data END
BACKUP;
200
1-201
Data dictionary views:• V$BACKUPV$BACKUP
• V$DATAFILE_HEADERV$DATAFILE_HEADER
Backup Status Information
201
1-202
Backing Up a Control File
–Creating a binary image:alter database backup controlfile to
‘control1.bkp’;
• Creating a text trace file:
alter database backup controlfile to
trace;
202
1-203
Exercise 4-3
• 1. Cold backup:– Shutdown database– Copy datafile, control file, logfile, init file,
password file to other place
• 2. Hot backup:– svrmgr>ALTER TABLESPACE system BEGIN
BACKUP;– svrmgr>host cp /abc/system01.dbf /backup– svrmgr>ALTER TABLESPACE system END BACKUP;
203
1-204
Categories of Failures
•Statement failure•User process failure•User error•Instance failure•Media failure
204
1-205
Causes of Statement Failures•Logic error in an application•Attempt to enter bad data into the table•Attempt an operation with insufficient privileges•Attempt to create a table but exceed allotted quota limits•Attempt an INSERT or UPDATE to a table, causing an extent to be allocated, but with insufficient free space left in the tablespace
205
1-206
Resolutions for Statement Failures
•Correct logic flow of the program•Modify and reissue the SQL statement•Provide the necessary database privileges•Change the user’s quota limit by using the ALTER USER command•Add file space to the tablespace
206
1-207
Causes of User Process Failures
•The user performed an abnormal disconnect in the session•The user’s session was abnormally terminated•The user’s program raised an address exception terminating the session
207
1-208
Resolving User Process Failures
•The PMON process detects an abnormally terminated server process•PMON rolls back the transaction and releases any resources and locks being held by it
208
1-209
Possible User Error Failures
SQL> DROP TABLE Employee;
SQL> TRUNCATE TABLE Employee;
SQL> UPDATE Employee SET SALARY =
SALARY * 1.5;
SQL> COMMIT;
SQL> DELETE FROM Employee;
209
1-210
Resolving User Errors
•Train the database users•Recover from a valid backup•Bring back a table export•Perform a point-in-time recovery
210
1-211
Causes of Instance Failure
•Power outage•Hardware failures–CPU–Memory–Disk failure
•Background process failure
211
1-212
Recovery from Instance Failure
•No special recovery action required•Start the instance•Open the database•Notify users
212
1-213
Instance Recovery Process
•Unsynchronized files•Roll-forward process•Committed and uncommitted data in files•Rollback process•Committed data in data files•Synchronized files
213
1-214
Causes of Media Failure
•Head crash on disk drive•Physical problem reading or writing to database files•File was accidentally erased
214
1-215
Resolving Media Failures
•The recovery strategy depends upon which backup method was chosen and which files are affected•If available, apply archived redo log files to recover data committed since the last backup
215
1-216
Database Synchronization
•All data files (except offline and read-only) must be synchronized for the database to open•Synchronization is based on the current checkpoint number•Applying redo logs synchronizes files•Redo logs are automatically requested by Oracle
216
1-217
The Alert Log File•Records informational and error messages for Oracle•Reflects the ongoing status of the system•Continuously written to, with new messages being appended to the end of the alert file•Shows date and time of startup, shutdown, recovery operations, and so on
217
1-218
Oracle Trace Files
•Created by Oracle background processes•Written to destination specified by parameter BACKGROUND_DUMP_DEST•Source of additional diagnostic information
218
1-219
Summary
•Understand the types of failures and the degree of DBA intervention•Locate error messages in the alert log and trace files
219
1-220
Exercise 4-4
• View alert log to calculate archive log size per day
220
1-221
Objectives
•Note the implications of media failure with a database in noarchivelog mode•Recover a database in noarchivelog mode after media failure•Restore files to a different location if media failure occurs
221
1-222
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
146
145
146
146
146
146
OverviewInstance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCHUser
ProcessServer
ProcessPGA
UserProcess
ServerProcess
PGA
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
144
145
144
144
144
144
222
1-223
Media Failure and Recovery Without Archiving
•Failure–Loss of disk, datafile, or corruption
•Recovery–Restore all datafiles, control files, and redo
logs–Restoring password and parameter files is
optional
223
1-224
Recovery Without Archiving
•Advantages–Easy to perform, with low risk of error–Recovery time = Time to restore all files
•Disadvantages–Data is lost and must be reapplied manually–The entire database is restored to the point of
the last whole closed backup
224
1-225
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
145
146146
146
146
146
Recovery Without Archiving
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Backup
143
144144
144
144
144
Restore most recent backupRestore most recent backup
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
143
144144
144
144
144
225
1-226
Restoring to a Different Location
•Rename the file or directory location:SVRMGR> connect system/manager as sysdba;
Connected.
SVRMGR> startup mount pfile=initDB00.ora;
Oracle instance started.
SVRMGR> alter database rename file
2> ‘/disk1/data/user_01.dbf’
3> to ‘disk2/data/user_01.dbf’;
Statement Processed.
SVRMGR> alter database open;
226
1-227
Database
PasswordFile
ArchivedLog Files
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
146
145
146
146
146
146
Overview
UserProcess
ServerProcess
PGA
Database
Data File 2
146
Instance
SGA
Redo Log Buffer
Large Pool
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
Data Buffer Cache
227
1-228
Media Failure and Recovery with Archiving
•Failure–Loss of disk, datafile, or corruption
•Recovery–Datafiles for restore must be offline–Restore only lost or damaged datafiles–Do not restore the control file, redo logs,
password, or parameter files–Recover the datafiles
228
1-229
Recovery with Archiving(Complete Recovery)
•Advantages–Only need to restore lost files–Recovers all data to the time of failure–Recovery time = Time to restore lost files and
apply all archived logs
•Disadvantages–Must have all archived logs since the backup
from which you are restoring
229
1-230
Complete Recovery Methods
• 1. Closed database recovery: For system, rollback segment data files, or whole database
• 2. Open database recovery, with database initially open: For file loss
• 3. Open database recovery with database initially closed: For hardware failure
• 4. Recover a datafile with no backup230
1-231
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
146
145
146
146
146
146
ArchivedLog File
144
Complete Recovery: Method 1
RestoreRestoreData File 2Data File 2(Log Seq(Log Seq 144)144)
Data File 2
1441
Instance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
UserProcess
ServerProcess
PGA
Instance
SGA
Redo Log Buffer
Large Pool
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
UserProcess
ServerProcess
PGA
Mount InstanceMount Instance2
Data Buffer Cache
145146Apply Log Apply Log FilesFiles
3
Open the Open the databasedatabase
4
231
1-232
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
146
145
146
146
146
146
ArchivedLog File
144
Complete Recovery: Method 2
Offline Data File 2Offline Data File 2
Data File 2
146
1
Instance
SGA
Redo Log Buffer
Large Pool
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
UserProcess
ServerProcess
PGA
RestoreRestoreData File 2Data File 2(Log Seq(Log Seq 144)144)
Data File 2
1442
145146Apply Log Apply Log FilesFiles
3
Online Data File 2Online Data File 2
Data File 2
146
4
Data Buffer Cache
232
1-233
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
146
145
146
146
146
146
ArchivedLog File
144
Complete Recovery: Method 3
Mount the Mount the databasedatabase
1
Instance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
Instance
SGA
Redo Log Buffer
Large Pool
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
UserProcess
ServerProcess
PGA Data Buffer Cache
Offline Data File 2Offline Data File 2
Data File 2
146
2
Open DatabaseOpen Database3
RestoreRestoreData File 2Data File 2(Log Seq(Log Seq 144)144)
Data File 2
1444
145146Apply Log Apply Log FilesFiles
5
Online Data File 2Online Data File 2
Data File 2
146
6
233
1-234
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
146
145
146
146
146
146
ArchivedLog File
144
Complete Recovery: Method 4
Offline Data File 2Offline Data File 2
Data File 2
146
1
RecreateRecreateData File 2Data File 2(Log Seq(Log Seq 144)144)
Data File 2
1442
145146Apply Log Apply Log FilesFiles
3
Online Data File 2Online Data File 2
Data File 2
146
4
Instance
SGA
Redo Log Buffer
Large Pool
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
UserProcess
ServerProcess
PGA Data Buffer Cache
234
1-235
Recover SyntaxRecover a closed database:
SVRMGR> recover database;
SVRMGR> recover datafile
> ‘/disk1/data/df2.dbf’;
SVRMGR> alter database recover;
SVRMGR> recover tablespace USER_DATA;
SVRMGR> recover datafile 2;
SVRMGR> alter database recover datafile 2;
Recover an open database:
235
1-236
Recovery Using Archived Logs
•To change archive location, use the ‘alter system archive log …’ command•To automatically apply redo log files:– Issue ‘set autorecovery on’ before starting
media recovery–Enter ‘auto’ when prompted for an archived
log file–Use the ‘recover automatic’ command
236
1-237
Files Needed for Recovery
•View V$RECOVER_FILE to locate datafiles needing recovery•View V$ARCHIVED_LOG for a list of all archived logs for the database•View V$RECOVERY_LOG for a list of all archived logs required for recovery
237
1-238
Database
PasswordFile
ArchivedLog Files
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
146
145
146
146
146
146
OverviewInstance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCHUser
ProcessServer
ProcessPGA
UserProcess
ServerProcess
PGA
238
1-239
Reasons for Incomplete Recovery
•User error•Complete recovery fails because an archived log is lost•Recovery using a backup control file•Loss of all unarchived redo logs and the datafile
239
1-240
Recovery with Archiving(Incomplete Recovery)
•Advantages–Recovers prior to the time of failure–Provides recovery in situations where complete
recovery is not possible
•Disadvantages–Database taken back in time (lose data)–Recovery time = Time to restore all datafiles +
apply required archived logs
240
1-241
Types of Incomplete Recovery
•Time-based recovery•Cancel-based recovery•Recovery using a backup control file•Change-based recovery
241
1-242
“recover” Command Syntax
Recover a database until cancel: SVRMGR> recover database until cancel;
SVRMGR> recover database
2> until time ‘1997-12-04:14:22:03’;
Recover a database until time:
SVRMGR> recover database
2> until time ‘1997-12-04:14:22:03’
3> using backup controlfile;
Recover using backup control file:
242
1-243
Recovery Steps• 1. Shut down and backup the database• 2. Restore all data files• 3. Do not restore the control file, redo logs,
password, or parameter files• 4. Mount the database and recover the
datafiles before the time of failure• 5. Open the database with “resetlogs”• 6. Perform a closed database backup
243
1-244
Recovery Guidelines• Follow/Record all steps since most
errors occur during this type of recovery• Take whole database backup before and
after recovery to assist future recovery• Always check if recovery is successful• Backup the control file regularly• Backup archived logs
244
1-245
Time-Based Recovery
•Scenario:–The current time is 12 PM on 9-DEC-97–Your training DBA just told you he dropped the
employee (EMP) table–The table was dropped around
11:45 AM–Database activity is minimal because most staff
are currently in a meeting–The table must be recovered
245
1-246
Instance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCHUser
ProcessServer
ProcessPGA
UserProcess
ServerProcess
PGA
Shutdown and backup Shutdown and backup the databasethe database
1
Mount databaseMount database2
Instance
SGA
Redo Log Buffer
Data Buffer
Large PoolLocks
Shared Pool
Data Dict.Cache
Shared SQL& PLSQL
PMON DBWRSMON LGWRCKPT ARCH
PasswordFile
ParameterFile
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
Database
EMP
146
145
146
146
146
146
ArchivedLog File
144
“Until Time” Recovery
Restore allRestore allData FilesData Files(Log Seq(Log Seq 144)144)
3
Data File 3
Data File 2
Data File 1
144
144
144
EMP
4
5145
145
145
146
145
145
145
145
146
Data File 3
Redo logFile 2
Data File 2
Control Files
Redo logFile 1
Data File 1
1
0
1
1
1
1
EMP
Open DatabaseOpen Database揜揜 esetlogsesetlogs
6
UserProcess
ServerProcess
PGA
UserProcess
ServerProcess
PGA
Backup databaseBackup database7
246
1-247
Cancel-Based Recovery
•Scenario:–The current time is 12 PM on 9-DEC-97–Your training DBA dropped the EMP table while
trying to fix bad blocks–Log files exist on the disk containing the
employee data file–The table was dropped around
11:45 AM
247
1-248
Cancel-Based Recovery
•Findings:–Redo logs are not multiplexed–One of the online redo logs is missing–The missing redo log is not archived–The redo log contained information from 11:34
AM–Twenty six minutes of data will be lost–Users can recover their data
248
1-249
Backup Control File Recovery
•Scenario:–The current time is 12 PM on 9-DEC-97–Your training DBA dropped the entire
employee tablespace, not just the table–The error occurred around 11:45 AM–Many employee records were updated this
morning, but not since 11:00 AM–Backups are taken every night
249
1-250
Backup Control File Recovery
•Findings:–The backup last night contains datafiles and
control files required for recovery –Employee tablespace has one datafile–The current log sequence number is 61–You confirm that the tablespace was dropped
at 11:44:54 AM on 9-DEC-97.–Datafile number 4 is offline.
250
1-251
Recover database syntax
RECOVER [AUTOMATIC] DATABASE [USING BACKUP CONTROLFILE] [UNTIL < CANCEL |
TIME date |CHANGE integer> ]
[NOPARALLEL | PARALLEL [integer] ]
251
1-252
Loss of control files
• Should not loss of all control files if configured multiple control files
• If loss all control files:– Method 1: Recreate control file– Method 2: Restore backup control file
252
1-253
Recreate control files
• You must get all database structure before recreate control files
253
1-254
Recreate control file
• svrmgr>alter database backup controlfile to trace;
• The create control file command will exist in the latest trace file
• Edit the trace file and save to script• Run the create control file script
254
1-255
Restore backup control file
• Restore backup control file• svrmgr> recover database using backup
controlfile;
255
1-256
Loss of a Redo Log File
•Loss of a Redo Log file:–Archiving still occurs using a good online
redo log file–Loss of all redo log files for a group should
‘NEVER’ occur if the database is configured properly using mirrored redo log files
256
1-257
Redo Log File Recovery•Non-Current logs:
–Add group, drop group
•Current logs:– If database shutdown normally:
• 1. Recover database until cancel• 2. Alter database open resetlogs
– If database shutdown abnormally:• Have backups:
– Restore from backups– RECOVER DATABASE UNTIL CANCEL and cancel when prev log
applied
• No backup– Can be startup in a corruption status– Ask Oracle support
257
1-258
Scenario 1
• Loss of non-current logfiles:– svrmgr>alter database add logfile
‘new_file_name’ size 1m;– svrmgr>alter database drop logfile
<‘old_file_name’ | group n>
258
1-259
Scenario 2
• Loss of current logfile and instance is shutdown normally:– svrmgr>recover database until cancel;– cancel– svrmgr>alter database open resetlogs;
259
1-260
Scenario 3• Loss of current logfile and instance is shutdown
abnormally:– Have backups
• Restore backups• svrmgr>recover database until cancel;• svrmgr>alter database open resetlogs;
– No backups• Ask Oracle support• _allow_resetlogs_corruption in init_sid.ora• svrmgr>recover database using backup controfile until
cancel;• svrmgr>alter database open resetlogs;• Export database
260