NAVEEN

Monday, March 22, 2010

Guarantee restore ponit - new feature of 10g

2 Document Overview
This document explains the best practice to recover the database with minimum outage and data loss with high availability of the database through Guaranteed Restore Point.

2.1 Scope
The Flashback Recovery includes the following activities

1) Guaranteed Restore Point overview
2) Requirement for Guaranteed Restore Point
3) Creation of Guaranteed Restore Point
4) DML Tasks
5) Restoration

2.2 Objectives
The objectives of Guaranteed Restore Point is to

• Recovering the database with point-in-time recovery
• Minimal outage of Production & DR.
• Enabling the Flashback Mode is not necessary.

3 Guaranteed Restore Point
3.1 Guaranteed Restore Point overview

Like normal restore points, guaranteed restore points can be used as aliases for SCNs in recovery operations. However, they also provide specific functionality related to the use of the Flashback Database feature.

Creating a guaranteed restore point at a particular SCN enforces the requirement that you can perform a Flashback Database operation to return your database to its state at that SCN, even if flashback logging is not enabled for your database. If flashback logging is enabled, creating a guaranteed restore point enforces the retention of flashback logs required for Flashback Database back to any point in time after the creation of the earliest guaranteed restore point.

A guaranteed restore point can be used to revert a whole database to a known good state days or weeks ago, as long as there is enough disk space in flash recovery area to store the needed logs. As with Flashback Database, even the effects of NOLOGGING operations like direct load inserts can be reversed using guaranteed restore points.

Note:
Limitations that apply to guarantee restore points: For example, shrinking a datafile or dropping a tablespace can prevent flashing back the affected datafiles to the guaranteed restore point.
3.2 Requirement for Guaranteed Restore Point


 Database must be running in ARCHIVELOG mode.
 Flash recovery area should be configured
 ORACLE Version should be compatible with 10.2 or more.









3.3 Creation of Guaranteed Restore Point
 Creation of table for testing.





 For creating Guaranteed Restore Point, We should have SYSDBA privilege.

 To create first guaranteed restore point when flashback off, first we need to start the database in mount state after a consistent shut down otherwise we will get an error like below.



 After opening in mount state we can create first guaranteed restore point like below.

















 Subsequent guaranteed restore points can be created when database is open. When you want to see the available guaranteed restore points you can use the select below

3.4 DML operations done for Test case

Some DML actions on the Created Table RSTR_EMP and create Restore points for that as below for test.







 Checking for number of restore points created














3.5 Restoration

 Set the database in mount stage.



 Restoring the database to the before_upgrade level.



 Checking for success of Restoration.

Database upgrade from 10g to 11g - Praposal document

2. Requirement Analysis:

DETAILED SYSTEM STUDY ON THE EXISTING ENVIRONMENT


Existing System Environment
Operating System Windows Server 2003 Enterprise Edition - 64 bit
Release Service pack 2
CPU Intel Xeon® CPU X5365
Processor speed 3 GHz
RAM Size 11.7 GB
PF Size Min 30 GB
PF Size Max 42 GB
Computer Name MELEXHTRAX01
IP Address 172.23.201.84
Oracle Software Oracle 10g Enterprise Edition x64 Bit


Drive Details
Drive Name Total Size in GB Free Size in GB
Local Disk (C Drive) 39.9 14.0
Swap Volume (D Drive) 39.9 9.22
Data Volume (E Drive) 249 82.9



















3. FEASIBILITY STUDY ON UPGRADE:
A feasibility study’s main goal is to assess the economic viability of the proposed approach. The outcome of the feasibility study will indicate whether or not to proceed with the proposed venture.
From technical view, following points are to be considered.
1. Cost involved for DB Migration/Upgrade
2. Time and effort involved
3. Technical Benefits of DB Migration/Upgrade

Why Upgrade to Oracle Database 11g?
The innovation continues with Oracle Database 11g Release 2 to lower IT costs and deliver a higher quality of service by:
 Consolidating business applications onto fast, reliable and scalable.
 Maximizing availability and eliminating idle data center redundancy
 Compressing data onto low cost storage partitions for faster performance
 Securely protecting information and enabling compliance
 Doubling DBA productivity and reducing the risk of change
The key value propositions of Oracle Database 11g and the faster and smooth upgrade process make it compelling for businesses to consider upgrading older Oracle databases. Upgrading provides businesses with access to new functionality and ensures that an Oracle database is fully supported by Oracle.



Oracle Database version 11.1g new features
Overall, Oracle Database 11g makes database infrastructure far more efficient, resilient, and manageable. For example, very compelling new features in the realm of partitioning ease the
design and management of partitioned tables immensely.

1) SQL Performance Analyzer (SPA)
2) Database Replay
3) Automatic Memory Tuning
4) Case sensitive password
5) Virtual columns and indexes
6) Interval Partition and System Partition
7) Feature based patching
8) RMAN Undo bypass
9) New default Audit setting
10) Faster DML triggers
11) Parallel backup and restore for very large files
12) Improved block media recovery performance
13) Enhanced Index rebuild online: Online index build with NO pause to DML.
14) No recompilation of dependent objects
15) Fast incremental backups on physical standby database

Upgrade Methods

1. Database Upgrade Assistant
The Database Upgrade Assistant (DBUA) interactively steps you through the upgrade process and configures the database for the new Oracle Database 11g release. The DBUA automates the upgrade process by performing all of the tasks normally performed manually. The DBUA makes appropriate recommendations for configuration options such as tablespaces and redo logs. The DBUA provides support for Real Application Clusters (RAC) and Automatic Storage Management (ASM).
2. Manual Upgrade
A manual upgrade consists of running SQL scripts and utilities from a command line to upgrade a database to the new Oracle Database 11g release. While a manual upgrade gives you finer control over the upgrade process, it is more susceptible to error if any of the upgrade or pre-upgrade steps are either not followed or are performed out of order.
3. Export/Import Method
Unlike the DBUA or a manual upgrade, the Export/Import utilities physically copy data from current database to a new database. We can use either the Oracle Data Pump Export and Import utilities (available as of Oracle Database 10g) or the original Export and Import utilities to perform a full or partial export from your database, followed by a full or partial import into a new Oracle Database 11g database. Export/Import can copy a subset of the data in a database, leaving the database unchanged.




4. PROPOSED APPROACH
IMPLEMENTATION APPROACH (Manual/DBUA Upgrade)
A manual upgrade consists of running SQL scripts and utilities from a command line to upgrade a database to Oracle Database 11g Release 1 (11.1).While a manual upgrade gives you finer control over the upgrade process, it is more susceptible to error if any of the upgrade or pre-upgrade steps are either not followed or are performed out of order.



*RAT – REAL APPLICATION TESTING
Before the Upgrade
When manually upgrading a database, perform the following pre-upgrade steps:
• Analyze the database using the Pre-Upgrade Information Tool. The Upgrade Information Tool is a SQL script that ships with Oracle Database 11g Release 1 (11.1), and must be run in the environment of the database being upgraded.
The Upgrade Information Tool displays warnings about possible upgrade issues with the database. It also displays information about required initialization parameters for Oracle Database 11g Release 1 (11.1).
• Prepare the new Oracle home.
• Perform a backup of the database.
Depending on the release of the database being upgraded, you might be required to perform additional pre-upgrade steps (adjust the parameter file for the upgrade, remove obsolete initialization parameters and adjust initialization parameters that might cause upgrade problems).
After the Upgrade
Review the upgrade spool log file and use the Post-Upgrade Status Tool. The Post-Upgrade Status Tool is a SQL script that ships with Oracle Database 11g Release 1 (11.1), and should be run in the environment of the new release.
APPROACH FLOWCHART




5. IMPLEMENTATION PLAN

Prerequisites for Implementation

Hardware requirements for upgradation

Hardware requirement for Upgrade (recommended)
CPU Intel Extended memory (EM64T) or AMD64
Processor speed 3 GHz
RAM Size 15 GB
PF Size Min 30 GB
PF Size Max 45 GB

Software requirements for up gradation

Software requirement (recommended)
Operating System Windows Server 2008 Enterprise Edition - 64 bit
Oracle Oracle server software 10.2.0.2.0
Oracle Patch 10.2.0.4.0 Patch set
Oracle Oracle server software 11.1.0.7.0


Drive Details
Drive Name Total Size in GB Required (in GB)
Local Disk (C Drive) 40 40
Swap Volume (D Drive) 40 40
Data Volume (E Drive) 250 250

Network Requirements

The computer on which you want to install Oracle Database should be connected to the network.





Tools / Resources Required
This section deals with the tools and the resources that are required to do the migration or upgrade of the Database that has been identified. This may contain the following:

1. The way in which the Original data can be transferred to the new server.
E.g. like Export dump or a Cold back of the database, etc
2. Tools that needs to be used. E.g. Oracle client, Import Utility, DBUA, etc
3. Two new servers are required (Primary and Standby).
4. Servers should be connected to network.
5. IGATE IMS Team should be able to login to new servers through CITRIX.
6. Administrator rights should be provided for IGATE IMS team login ids.
7. Oracle server software and patch set specified in the above section should be downloaded, and the location of the software should be shared.
Pre upgrade and Post upgrades activities

This includes following activities:
1. Timing tests
2. Data dictionary growth observations after upgradation.
3. Database resource usage observations, such as undo and temporary segment usage

Collecting this information will help to compare the current database (10.2.0.4.0) with the new Oracle Database (11.1.0.7.0).

Installation steps

1 What the database name is?

SQL> Select name from v$database;

2 What version is running?

SQL> Select * from v$version;

3 What option is installed?

SQL>Select VERSION, COMP_NAME, STATUS from dba_registry;


4 What is the count of the objects in that database?

SQL> Select count(*) from dba_objects;

5 How many invalid objects in database?

SQL> Select object_name, object_type from dba_objects where status='INVALID';

6 Install oracle 10.2.0.2.0 server software on the new test server.

7 Download 10.2.0.4.0 patch and upgrade Oracle to 10.2.0.4.0

8 Copy parameter file (init file), control files, Redo log files and Data files to the corresponding location of new server.

9 Make required modifications in init file (change location of control, datafile, directory location etc...

10 Create new TRAXMP instance and password file in new server.

SQL>ORADIM NEW –SID TRAXMP
SQL> ORAPWD FILE=C:\ORACLE\PRODUCT\10.2.0.\DB_1\DATABASE\PWDTRAXP.ORA PASSWORD=******** ENTRIES=100

11 Startup oracle instance in mount mode using initfile.

SQL> STARTUP NOMOUNT PFILE=’C:\ORACLE\PRODUCT\10.2.0.\DB_1\DATABASE\INITTRAXP.ORA’;

SQL>ALTER DATABASE MOUNT;

12 In mount mode, change the location of Data file, Redo log file in the control file.

SQL> ALTER DATABASE RENAME FILE ‘LOCATION\OLD_FILE_NAME’ TO
‘NEW_LOATION\NEW_FILE_NAME’;

13 Open the database.

SQL>ALTER DATABASE OPEN;

14 Perform health checkup (confirm that DB is running in 10.2.0.4.0).

15 Install Oracle 11.1.0.7.0 Server software in new server.

16 Run pre-upgrade information script(utl111i.sql – present in ORACLE_HOME\db_1\RDBMS\admin directory) in database running under 10.2.0.4.0.

SQL>SPOOL C:\PREUPGRADE.TXT
SQL>@utl111i.sql;
SQL>SPOOL OFF;

17 Make required modifications to database as recommended by pre-upgrade script.

18 Change oracle_home path pointing to 11.1.0.7.0

C:\>SET ORACLE_HOME=’C:\ORACLE\PRODUCT\11.1.0\DB_1’

19 Create directory structure in 11.1.0.7 .0 and copy the data file, log file and control files.

Create adump, bdump, cdump, pfile, dump directory under C:\ORACLE\PRODUCT\11.1.0\admin

20 Delete old instance and recreate new instance.

C:\>ORADIM –DELSID SID_NAME – To delete instance
C:\>ORADIM –NEW –SID SID_NAME

21 Edit pfile (compatibility and directory locations).

Set compatibility = 11.1.0.7.0

22 Startup nomount database using pfile.

SQL> STARTUP NOMOUNT PFILE=’C:\ORACLE\PRODUCT\11.1.0.\DB_1\DATABASE\INITTRAXP.ORA’;

23 Keep database in mount mode.

SQL>ALTER DATABASE MOUNT;

24 Change the location of data files and Redolog files in controlfiles.

SQL> ALTER DATABASE RENAME FILE ‘LOCATION\OLD_FILE_NAME’ TO
‘NEW_LOATION\NEW_FILE_NAME’;

25 Shutdown database.

SQL>SHUTDOWN IMMEDIATE;

26 Startup database in upgrade mode.

SQL>STARTUP UPGRADE;

27 Run catupgrd.sql script which is in ORACLE_HOME/RDBMS/ADMIN directory for upgrade.

SQL>@C:\ORACLE\PRODUCT\11.1.0\DB_1\RDBMS\ADMIN\CATUPGRD.SQL;

28 Shutdown database.

SQL>SHUTDOWN IMMEDIATE;

29 Startup database normaly.

SQL>SET ORACLE_SID=SID_NAME;
SQL>STARTUP;

30 Run utlrp.sql script to find invalid objects (script which is in ORACLE_HOME/RDBMS/ADMIN directory)

SQL>@C:\ORACLE\PRODUCT\11.1.0\DB_1\RDBMS\ADMIN\UTLRP.SQL;

31 If any invalid objects observed, recompile such objects.

SQL>SELECT OBJECT_NAME, OBJECT_TYPE FROM DBA_OBJECTS WHERE STATUS=’INVALID’;

SQL> ALTER OBJECT_TYPE OBJECT_NAME COMPILE;

32 Perform complete health checkup of database.

Check the database hit ratios.
Check table space usage details.
Check application level compatibility for 11g
Check database performance metrics.

Once the actual migration or the Upgrade is completed, the following things needs to be done:

1. Compare the Number of objects in both the old one and the new database (in case if a migration has been done to a different server.
2. Check for the INVALID state of the objects and compiling the same.
3. Check for the disabled constraints and then enabling the same. Also, the triggers need to be checked and enabled.
4. Reorganization of the tables or indexes if it is required.
5. Do an Analyze of the schemas in order to gain good performance.
6. Check for the application access and also the Performance of the database.


6. EFFORT ESTIMATION


S.No. Activity Resource/Effort Requirement Responsibility Comments/Status
1 Taking a cold Backup of the old Database
2 Setting up and installation of the new Oracle Server
3 Transferring of the original Production Data
4 Creating an Empty Database(optional)
5 Imports/Upgrade Activity
6 Checking of Invalid Objects and compiling those objects
7 User testing of the application

7. Rollback Strategy
Any Migration or an upgrade that is done needs a rollback strategy which needs to be done in case if the new system implemented is not fulfilling the expectations by the users or the project team. In order for this, a rollback strategy needs to be identified and should be kept in place. Should there be an upgrade failure it will be necessary to revert back to the previous versions. It will be more difficult and time consuming to roll back from an in-place upgrade. A side-by-side upgrade will work better is simpler to rollback from.

The roll back strategy should be in such a way that either the database needs to be restored to the old status in the same server or we should have the correct copy of the database before starting the migration so that the old system can be made available to the users in a short span of time reducing the outage.

Procedure:

1. Take a Complete backup of the Oracle Home, Oracle Inventory and Database before the activity.
2. If the up gradation activity fails, it should be rolled back to 10.2.0.4.0 using the backup.

8. Risks and Risk Mitigation Process

1. Risk is low; if the up gradation fails or Application compatibility fails then it can
be rolled Back to 10.2.0.4.0 using backup.

No activity or migration is risk free as there is always a risk associated with any kind of migration that is being done. The following are some of the risks that might be faced during the migration:

1. Getting the correct time window or downtime of the Production databases for doing the migration.
2. Identifying the Proper tools or methodology to do the migration
3. Availability of the Proper disk space for migrating the database
4. Suitable hardware identification and sizing
5. Risks involved in getting the original data because of network connectivity.

9. Testing
Application tests and performance tests should be planned and implemented to confirm in advance that no major compatibility or performance problems will arise in the new system. This reduces the risk of migration failure and other risks following migration.

Minimum tests

All or parts of applications are transferred from the current system to the new system (or test environment). Tests are performed without enabling new functions. In
minimum tests, all possible potential problems cannot be discovered , but at least
problems related to application launching and invocation can be checked.

Functional tests

Functional tests include testing of all databases, network, and application components. These are conducted after new and existing functions of the system are upgraded. Functional tests confirm that individual system components and new functionality work properly as they did before the upgrade.

Integration tests

Integration tests check interactions among system components. Specifically, these tests assess the following points:
 Confirms that applications (Pro*C/C++, JDBC, ODBC) and other software causes no problems in the new software.
 Performs analysis to determine if changes in data type and data dictionary data
affect front-end applications.
 Checks connectivity when applications are connected through SQL*Net, Net8, or Oracle Net services.

Performance tests

To check performance, plan and carry out the following performance tests. Before performing the tests, you must obtain performance information on the current system based on the performance requirements of the new system. This will help determine whether the performance requirements of the new system are adequate and help identify factors leading to performance degradation, based on comparisons.

Confirming concurrent performance

To confirm concurrent performance, multiple factors comprising actual business
Processes are used to generate loads similar to those in the actual system and the
Performance of the overall system is analyzed. If the system fails to meet the required
Unit performance, confirming concurrent performance will not help improve
Performance. Additionally, the following problems not generated during confirmation
Of unit performance can also emerge during confirmation of concurrent performance.

• High CPU usage, CPU wait
• High disk usage, disk wait
• Exclusive control (lock) for files and databases
• Process wait due to inter-process communication

As described above, migration to a new system requires planning and confirmation of compatibility of the current system (applicability, extent of results of any incompatibilities, countermeasures), application tests, and performance tests. This increases required man-hours, entails higher costs, and results in system failures and other problems in various work processes. In our verification testing, we attempted to verify whether use of application tests, Database Replay to confirm concurrent performance, and SQL Performance Analyzer to confirm unit performance would reduce risks and facilitate the process of migration.

Once the migration or the upgrade of the database is completed, we need to rigorous testing on the new environment that has been developed. This involves active participation from the end users as well. During the testing phase, it is important that we check on the following things:

1. Performance of the new database
2. Validity of the objects in the database
3. Correctness and matching of the data in the tables, number of objects in the old and the new database
4. Access and the working of the application when compared to the old environment.

Recreate database using Full export backup

1 Summary:

This document gives a brief idea about recreating a database (exact replica) from existing
database using Import-Export Backup.

Export, Import are complementary utilities which allow to write data in an ORACLE-binary format from the database into operating system files and to read data back from those operating system files. EXPORT, IMPORT are used for the following tasks:
• backup ORACLE data in operating system files
• restore tables that where dropped
• save space or reduce fragmentation in the database
• move data from one owner to another
• Create replica of existing database.














2 How to Do:


Steps:

Information gathering from Source Database:

1. Connect to source database as a SYS user and collect information about

a. Global database name
b. Db_link details
c. control file , data file , redo log file and temp file details.
d. generate the querry to recreate db link in new database.
e. Collect information about synonyms,views,index details
f. Collect information about user account details and profile details.
g. Collect information about Oracle version.

Take a full export backup of database (Daily export backup is available frpm HP Openview).


2. Set up new server with required amont of RAM and hard disk capacity.
3. Install Operating system.
4. Install Oracle server software (version is same as of existing production).
5. Create a database manually with structure same as that of production database setup.(tablespace name must be identical).
6. create user accounts in new database.
7. Grant permissions to newly created user. Assign profile to user.
8. Import the data to new database.
9. Recreate synonyms, Db links, Views and Indexes in new database.
10. Manually check and confirm that data in new database is same as that of Old one.













Flowchart

















3. At Source Database

Information Gathering from source DB

Global DB Name:

SQL> select * from global_name;

DB Links:


SQL> select * from dba_db_links;


Control file details:

SQL> select name from v$controlfile;

Datafile details:

SQL> select file_name from dba_data_files;


SQL> select member from v$logfile;

Script to Recreate DB Link in new database after import (recreated DB)

SQL> select 'create DATABASE LINK '||owner#||'.'||NAME|| ' connect to '|| userid || ' identified by '|| password || ' using '||''''|| host ||''''||'; ' FROM sys.link$ order by owner#;


Collect User information from production db:

SQL> select ' alter user '||username||' identified by values ' || chr(39)||password||chr(39) || ';' from dba_users;


Get user profile information from production db :

SQL> select ' alter user '||username||' profile '||PROFILE||';' from dba_users;


Synonym details from Pproduction db:

SQL> Select 'CREATE SYNONYM '||owner||'.'||synonym_name||' FOR '||table_owner||'.'||table_name||'@'||db_link||';' from dba_synonyms where db_link is not null and table_owner is not null;

Export backup:

Take a full export backup of Source database.

Create directory backup

Sql > create directory backup as '/DISK01/backup';

$ expdp sys/test directory=backup dumpfile=exp01.dmp logfile=exp01.log full=y


At Target Database

recreate user account in recreated database after import :


SQL> create user MGMT_VIEW identified by values 'F25A184809D6458D';

Reset user profile :

SQL> select ' alter user '||username||' profile '||PROFILE||';' from dba_users;

SQL>alter user MGMT_VIEW profile DEFAULT;
.
Recreate synonym in rebuilded database after import:


SQL> Select 'CREATE SYNONYM '||owner||'.'||synonym_name||' FOR '||table_name||'@'||db_link||';' from dba_synonyms where db_link is not null and table_owner is null;

SQL>CREATE SYNONYM EXTTPS.PS_MAS_CHK_VW_HDR FOR PS_MAS_CHK_VW_HDR@FSPROD.WORLD;




Import Data in new database:

Import the data to newly created database.


$ impdp sys/test directory=backup dumpfile=exp01.dmp logfile=imp01.log full=y

Tuesday, March 16, 2010

Script to Monitor Current User Activity in the Database

set pagesize 66
col c1 for a9
col c1 heading "OS User"
col c2 for a9
col c2 heading "Oracle User"
col b1 for a9
col b1 heading "Unix PID"
col b2 for 9999 justify left
col b2 heading "SID"
col b3 for 99999 justify left
col b3 heading "SERIAL#"
col sql_text for a35
break on b1 nodup on c1 nodup on c2 nodup on b2 nodup on b3 skip 3
select c.spid b1, b.osuser c1, b.username c2, b.sid b2, b.serial# b3,
a.sql_text
from v$sqltext a, v$session b, v$process c
where a.address = b.sql_address
-- and b.status = 'ACTIVE' /* YOU CAN CHOOSE THIS OPTION ONLY TO SEE
-- ACTVE TRANSACTION ON THAT MOMENT */
and b.paddr = c.addr
and a.hash_value = b.sql_hash_value
order by c.spid,a.hash_value,a.piece
/

Friday, March 12, 2010

Creating a excel report

set feed off markup html on spool on
spool emp.xls
select * from noshow;
spool off
set markup html off spool off

SQL * PLUS Commands





















SQL*Plus FAQ - Oracle FAQ



























































































SQL*Plus FAQ





From Oracle FAQ





Jump to: navigation, search


SQL*Plus FAQ:



Contents







[edit] What is SQL*Plus and where does it come from?



SQL*Plus is a command line SQL and PL/SQL language interface and reporting tool that ships with the Oracle Database Client and Server software. It can be used interactively or driven from scripts. SQL*Plus is frequently used by DBAs and Developers to interact with the Oracle database.

If you are familiar with other databases, sqlplus is equivalent to:





SQL*Plus's predecessor was called UFI (User Friendly Interface). UFI was included in the first Oracle releases up to Oracle 4. The UFI interface was extremely primitive and, in today's terms, anything but user friendly. If a statement was entered incorrectly, UFI issued an error and rolled back the entire transaction (ugggh).



[edit] How does one use the SQL*Plus utility?



Start using SQL*Plus by executing the "sqlplus" command-line utility from the $ORACLE_HOME/bin directory. Some of the command line options:



userid/password@db -- Connection details

/nolog -- Do not login to Oracle. You will need to do it yourself.

-s or -silent -- start sqlplus in silent mode. Not recommended for beginners!

@myscript -- Start executing script called "myscript.sql"



Look at this example session:



sqlplus /nolog

SQL> connect scott/tiger

SQL> select * from tab;

SQL> disconnect

SQL> exit



Please note that one must prepare the environment before starting sqlplus.

Linux/ Unix example:



$ . oraenv

ORACLE_SID = [orcl] ? orcl

$ sqlplus scott/tiger



Windows Example:



Click on "Start" -> "Run" and enter "cmd"

C:> set ORACLE_SID=orcl

C:> sqlplus scott/tiger



or...



C:> sqlplus scott/tiger@orcl



[edit] What commands can be executed from SQL*Plus?



One can enter three kinds of commands from the SQL*Plus command prompt:

SQL*Plus commands

SQL*Plus commands are used to set options for SQL*Plus, format reports, edit files, edit the command buffer, and so on. SQL*Plus commands do not interact with the database. These commands do not have to be terminated with a semicolon (;) (as is the case with SQL commands). Examples:



SQL> CLEAR SCREEN

SQL> SHOW USER

SQL> SET PAGESIZE 100

SQL> START myscrip.sql



SQL commands

For more information see the Oracle SQL FAQ. Eg:



SQL> SELECT * FROM user_tables;



PL/SQL blocks

For more information see the Oracle PL/SQL FAQ. Eg:



BEGIN

dbms_output.put_line('Hello World!');

END;

/



[edit] What are the basic SQL*Plus commands?



Here is a list of some of the most frequently used SQL*Plus commands:



  • ACCEPT - Get input from the user

  • DEFINE - Declare a variable (short: DEF)

  • DESCRIBE - Lists the attributes of tables and other objects (short: DESC)

  • EDIT - Places you in an editor so you can edit a SQL command (short: ED)

  • EXIT or QUIT - Disconnect from the database and terminate SQL*Plus

  • GET - Retrieves a SQL file and places it into the SQL buffer

  • HOST - Issue an operating system command (short: !)

  • LIST - Displays the last command executed/ command in the SQL buffer (short: L)

  • PROMPT - Display a text string on the screen. Eg prompt Hello World!!!

  • RUN - List and Run the command stored in the SQL buffer (short: /)

  • SAVE - Saves command in the SQL buffer to a file. Eg "save x" will create a script file called x.sql

  • SET - Modify the SQL*Plus environment eg. SET PAGESIZE 23

  • SHOW - Show environment settings (short: SHO). Eg SHOW ALL, SHO PAGESIZE etc.

  • SPOOL - Send output to a file. Eg "spool x" will save STDOUT to a file called x.lst

  • START - Run a SQL script file (short: @)



[edit] What is AFIEDT.BUF?



AFIEDT.BUF is the SQL*Plus default edit save file. When you issue the command "ed" or "edit" without arguments, the last SQL or PL/SQL command will be saved to a file called AFIEDT.BUF and opened in the default editor.

In the prehistoric days when SQL*Plus was called UFI (User Friendly Interface) this file was named "ufiedt.buf", short for UFI editing buffer. When new features were added to UFI, it was the initially named Advanced UFI and the filename was changed to "aufiedt.buf" and then to "afiedt.buf". They presumably needed to keep the name short for compatibility with some of the odd operating systems that Oracle supported in those days. The name "Advanced UFI" was never used officially, as the name was changed to SQL*Plus before this version was released.

You can overwrite the default edit save file's name like this:



SET EDITFILE "afiedt.buf"



[edit] I'm unable to edit files. What is wrong?



One can edit SQL scripts and the command buffer (the last command entered) with the EDIT (or ED) command. However, sometimes one needs to select an editor before using this command. Examples:

Use the Unix/Linux vi-editor:



DEFINE _EDITOR=vi



Use the Notepad on Windows:



DEFINE _EDITOR=notepad



TIP: Add this command in your login.sql or glogin.sql scripts so it executes every time you start sqlplus.



[edit] How does one enable the SQL*Plus HELP facility?



To enable HELP for SQl*Plus, run the supplied "helpins" script in $ORACLE_HOME/bin. The "helpins" command will prompt you for the SYSTEM password and load the help data into the SYSTEM schema.

Alternatively you can load the help facility manually like this:



cd $ORACLE_HOME/sqlplus/admin/help

sqlplus system/manager @helpdrop.sql # Drop the HELP table

sqlplus system/manager @hlpbld.sql helpus.sql # Create the HELP table and load the data



If the HELP command is not supported on your operating system, you can access the help table with a simple script like this (let's call it help.sql):



select info

from system.help

where upper(topic)=upper('&1');



Whenever you need help, you can now run the help.sql script:



@help SELECT



[edit] What is the difference between ? and HELP?



There is no difference. Both "?" and HELP will read the SYSTEM.HELP table (if available) and shows help text on the screen.

To use the help facility, type HELP followed by the command you need to learn more about. For example, to get help on the SELECT statement, type:



HELP SELECT



One can also extend the help system by inserting information into the HELP table. Look at this example:



SQL> insert into help values ('MYTOPIC', 1, 'Detail line 1');

1 row created.



SQL> insert into help values ('MYTOPIC', 2, 'Detail line 2');

1 row created.



SQL> help MYTOPIC

Detail line 1

Detail line 2



SQL> ? MYTOPIC

Detail line 1

Detail line 2



[edit] What is the difference between @ and @@?



The @ (at symbol) is equivalent to the START command and is used to run SQL*Plus command scripts.



SQL> @myscript.sql



A single @ symbol runs a script in the current directory (or one specified with a full or relative path, or one that is found in your SQLPATH or ORACLE_PATH).

@@ will start a sqlplus script that is in the same directory as the script that called it (relative to the directory of the current script). This is normally used for nested command files. This technique is commonly used by scripts that call subscripts in the ?/rdbms/admin directory.



[edit] What is the difference between & and &&?



"&" is used to create a temporary substitution variable that will prompt you for a value every time it is referenced. Example:



SQL> SELECT sal FROM emp WHERE ename LIKE '&NAME';

Enter value for name: SCOTT

old 1: SELECT sal FROM emp WHERE ename LIKE '&NAME'

new 1: SELECT sal FROM emp WHERE ename LIKE 'SCOTT'

SAL

----------

3000



SQL> /

Enter value for name: SCOTT

old 1: SELECT sal FROM emp WHERE ename LIKE '&NAME'

new 1: SELECT sal FROM emp WHERE ename LIKE 'SCOTT'

SAL

----------

3000



"&&" is used to create a permanent substitution variable. Once you have entered a value (defined the variable) its value will used every time the variable is referenced. Example:



SQL> SELECT sal FROM emp WHERE ename LIKE '&&NAME';

Enter value for name: SCOTT

old 1: SELECT sal FROM emp WHERE ename LIKE '&&NAME'

new 1: SELECT sal FROM emp WHERE ename LIKE 'SCOTT'



SAL

----------

3000



SQL> /

old 1: SELECT sal FROM emp WHERE ename LIKE '&&NAME'

new 1: SELECT sal FROM emp WHERE ename LIKE 'SCOTT'

SAL

----------

3000



The "&&" will actually define the variable similarly to what the DEFINE command or OLD_VALUE/ NEW_VALUE clauses of a COLUMN statement would have done.



SQL> define

DEFINE NAME = "SCOTT" (CHAR)



[edit] What is the difference between ! and HOST?



Both "!" and "HOST" will execute operating system commands as child processes of SQL*Plus. The difference is that "HOST" will perform variable substitution (& and && symbols), whereas "!" will not. Examples:



SQL> ! whoami

oracle



SQL> DEFINE cmd="whoami"

SQL> HOST &&cmd

oracle



Note: use "$" under OS/390, VMS, and Windows environments, not "!".



[edit] Can one run commands when SQL*Plus starts up?



When SQL*Plus starts up, it looks for a global login script called glogin.sql in the $ORACLE_HOME/sqlplus/admin directory. If found, this script will be executed.

Thereafter, sqlplus will try to find a local login script called login.sql in the directory where you start sqlplus from, alternatively the directories listed in the SQLPATH environment variable. When found, sqlplus will execute it.

NOTE: From Oracle 10g SQL*Plus will attempt to execute glogin.sql and login.sql after each successful connection. This is handy if you want to change the sqlprompt to include the current user. Here is an example (g)login.sql file:



prompt Loading login.sql file...

set sqlprompt "&&_USER@&&_CONNECT_IDENTIFIER SQL>"

define _editor=vi



A bit of history: when SQL*Plus was still called UFI, this file was called login.ufi (located in $ORACLE_HOME/demo).



[edit] Can one set the SQL*Plus command prompt to something more useful?



One can change the default 'SQL> ' prompt by changing the SQLPROMPT setting. For example:



SET SQLPROMPT 'Enter SQLPlus Command> '



The following example scripts can be used to include the connected username and database name into the prompt:

For Oracle 10g and above:



set sqlprompt "_USER'@'_CONNECT_IDENTIFIER _PRIVILEGE> "



Pre 10g:



undefine usr db

col usr new_value usr

col db new_value db



set termout off

select lower(user) usr,

substr(global_name, 1, instr(global_name, '.')-1) db

from global_name

/

set termout on



set sqlprompt '&&usr.@&&db.> '



NOTE: For the above example it might be better to get the database name from v$database. However, not all users do have access to the v$database view.



[edit] How does one disable interactive prompting in SQL*Plus?



If you run a script that contains "&" symbols, SQL*Plus thinks that you want to prompt the user for a value. Some clients allow one to escape the ampersand character with a backslash, however, that doesn't work from SQL*Plus. Here is a couple of solutions:



SET ESCAPE ON

SET ESCAPE ""

SELECT 'You & me' FROM DUAL;



or



SET DEFINE ?

SELECT 'You & me' FROM DUAL;



Atanas Kebedjiev provided this solution:



SELECT 'You '||Chr(38)||' Me' FROM DUAL;



Note: You can disable substitution variable prompting altogether by issuing the SET DEFINE OFF or SET SCAN OFF command.

Homer Vargas provided this solution:

"&" sign should always be at the end of the string.



SELECT 'You &'||' me' FROM DUAL;



[edit] How does one trap errors in SQL*Plus?



Use the "WHENEVER SQLERROR ..." command to trap SQL and PL/SQL errors, and the "WHENEVER OSERROR ..." to trap operating system errors. Eg:



SQL> WHENEVER OSERROR  EXIT 9

SQL> WHENEVER SQLERROR EXIT SQL.SQLCODE



[edit] How does one trace (and explain) SQL statements from SQL*Plus?



Method 1: Autotrace Facility

When the AUTOTRACE setting is enabled, SQL*Plus will print an EXPLAIN PLAN and execution statistics after each SQL statement. Look at this example:



SQL> set autotrace on

SQL> select * from dept where deptno = 40;

DEPTNO DNAME LOC

---------- -------------- -------------

40 OPERATIONS BOSTON



Execution Plan

----------------------------------------------------------

0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=18)

1 0 TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (Cost=1 Card=1 Bytes=18)

2 1 INDEX (UNIQUE SCAN) OF 'PK_DEPT' (UNIQUE)



Statistics

----------------------------------------------------------

0 recursive calls

0 db block gets

2 consistent gets

0 physical reads

0 redo size

499 bytes sent via SQL*Net to client

503 bytes received via SQL*Net from client

2 SQL*Net roundtrips to/from client

0 sorts (memory)

0 sorts (disk)

1 rows processed



Follow these steps to enable this feature:



  • Run the PLUSTRCE.SQL script from the SYS database user. This script is located in the $ORACLE_HOME/sqlplus/admin directory.

  • Create a PLAN_TABLE table by running the UTLXPLAN.SQL script. This script is in $ORACLE_HOME/rdbms/admin.

  • Use the "SET AUTOTRACE ON" command to trace SQL execution. This will print an explain plan and high level trace information after your query results.



Method 2: DBMS_XPLAN Package



SQL> EXPLAIN PLAN FOR select * from dept where deptno = 40;

Explained.



SQL> set linesize 132



SQL> SELECT * FROM TABLE( dbms_xplan.display);



PLAN_TABLE_OUTPUT

---------------------------------------------------------------------------------------

Plan hash value: 2852011669



---------------------------------------------------------------------------------------

| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |

---------------------------------------------------------------------------------------

| 0 | SELECT STATEMENT | | 1 | 20 | 1 (0)| 00:00:01 |

| 1 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)| 00:00:01 |

|* 2 | INDEX UNIQUE SCAN | PK_DEPT | 1 | | 0 (0)| 00:00:01 |

---------------------------------------------------------------------------------------



Predicate Information (identified by operation id):

---------------------------------------------------



2 - access("DEPTNO"=40)



14 rows selected.



[edit] How can one prevent SQL*Plus connection warning messages?



When I go to SQl*Plus, I get the following errors:



Error accessing PRODUCT_USER_PROFILE

Warning: Product user profile information not loaded!

You may need to run PUPBLD.SQL as SYSTEM



This messages will stop appearing when you create the PRODUCT_USER_PROFILE table in the SYSTEM schema. This is performed by the PUPBLD.SQL script.

Go to the $ORACLE_HOME/sqlplus/admin directory, connect as SYSTEM and run @PUPBLD.SQL from the sql prompt.



[edit] Can one prevent users from executing devious commands?



Yes, command authorization is verified against the SYSTEM.PRODUCT_USER_PROFILE table. This table is created by the PUPBLD.SQL script. Note that this table is not used when someone signs on as user SYSTEM.

Eg. to disable all users whose names starts with OPS$ from executing the CONNECT command:



SQL> INSERT INTO SYSTEM.PRODUCT_USER_PROFILE 

VALUES ('SQL*Plus', 'OPS$%', 'CONNECT', NULL, NULL, 'DISABLED', NULL, NULL);



[edit] How does one restore session state in SQL*Plus?



Use the "STORE SET" command to write current settings (SHOW ALL) to a file. This file can later be executed to restore all settings. Look at the following example (Oracle8 and above):



SQL> STORE SET filename REPLACE

SQL> (do whatever you like)

SQL> @filename



[edit] How does one disable SQL*Plus formatting?



SQL*Plus tries to format data from the database into a human friendly format. This formatting can be disabled by issuing the following SET commands:



SET ECHO OFF

SET NEWPAGE 0

SET SPACE 0

SET PAGESIZE 0

SET FEEDBACK OFF

SET HEADING OFF

SET TRIMSPOOL ON

SET TAB OFF



These settings can also be abbreviated and entered on one line, eg.:



SET ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF



You may also want to run the "show all" command to display all the other sqlplus settings that can be changed.



[edit] Can one pass operating system parameters to SQL*Plus?



One can pass operating system variables to sqlplus using this syntax:



sqlplus username/password @cmdfile.sql var1 var2 var3



Parameter var1 will be mapped to SQL*Plus variable &1, var2 to &2, etc. Look at this example:



sqlplus scott/tiger @x.sql  '"test parameter"' dual



Where x.sql consists of:



select '&1' from &2;

exit 5;



Info received from Tim Kessler:

Since I occasionally get useful info from your side I felt it is appropriate to add the following:

Example passing the Windows User's Temp Path Location to sqlplus:



sqlplus username/password @cmdfile.sql %TEMP%



within @cmdfile.sql -



SPOOL &1\myscript.log

-- Your script commands

SPOOL OFF



[edit] Something's wrong with my CLOB/ NCLOB/ LONG column. Where is my data?



SQL*Plus by default only shows the first 80 bytes of any LONG, CLOB and NCLOB datatypes. The data is there, but since sqlplus is a command-line tool it tries not to print out too much data. You can override this to tell sqlplus exactly how many bytes you want to see:



SET LONG 32000

SELECT text FROM user_views WHERE rownum = 1;



[edit] How does one copy data from one database to another in SQL*Plus?



The SQL*Plus COPY command is one of the fastest ways of copying data between databases and schemas. This is also one of the few methods that will handle LONG columns correctly. Look at this example:



SQL> COPY FROM scott/tiger@db1 TO scott/tiger@db2 INSERT mytable USING select * from mytable;



From SQL*Plus help:



COPY

----



Copies data from a query to a table in the same or another

database. COPY supports CHAR, DATE, LONG, NUMBER and VARCHAR2.



COPY {FROM database | TO database | FROM database TO database}

{APPEND|CREATE|INSERT|REPLACE} destination_table

[(column, column, column, ...)] USING query



where database has the following syntax:

username[/password]@connect_identifier



Note that this command is no more enhanced since Oracle 8.0 and may be declared as obsolete in a future version (but is still there in 11gR2) but there is no replacement to easily copy tables with LONG column (LONG datatype is obsolete).



[edit] Can one generate HTML reports from SQL*Plus?



One can generate static HTML pages from SQL*Plus (8.1.6 and above) by setting the MARKUP option to HTML ON. This can be done by specifying -MARKUP "HTML ON" from command line, or with the "SET MARKUP HTML ON" command. Look at this example SQL Script:



set markup HTML on

spool index.html

select * from tab;

spool off

set markup HTML off



The spooled index.html file should look like this:



































TNAMETABTYPECLUSTERID
BONUSTABLE 
DEPTTABLE 
EMPTABLE 


Note: You can deploy this file on your web site or edit it in an HTML editor (like FrontPage or Dreamweaver). Another good idea is to develop a CSS to present the data more elegantly. One can also embed HTML tags in the select statement to create hyperlinks and add more HTML features.







































Thursday, March 11, 2010

Performance tuning basics








Question: I am new to Oracle tuning, and I want to know the steps for Oracle performance tuning.

Answer: As of Oracle 11g, Oracle has codified a top-down tuning approach, with the first steps being very broad, and successive steps becoming more focused. Oracle performance tuning is very complex, and where there are some generic steps for performance tuning, the world is not always that simple. Here are the steps for a top-down Oracle performance tuning approach:





Oracle tuning involves the following steps, with each step getting more specific and targeted:


Server & network tuning—This is always the first step, as not amount of tuning will help a poor server environment.

Instance tuning—Tuning the Oracle SGA is the next step, and all of the Oracle initialization parameters must be reviewed to ensure that the database has been properly configured for it's workload. In some cases, a database may have a bi-modal workload (online vs. batch) and the instance parms are adjusted as-needed during this step.

Object tuning—This step of performance tuning looks at the setting for Oracle tables and indexes. Table and index settings such as PCTFREE, PCTUSED, and FREELISTS can have a dramatic impact on Oracle performance.

SQL tuning—This is last step in tuning, and the most time-consuming tuning operation because there can be many thousands of individual SQL statements that access the Oracle database. If you have carefully optimized the workload as a whole from step 2, there you will only need to tune "outlier" SQL statements. Within this step, there are sub-steps:
Remove unnecessary large-table full-table scans—In this tuning step you evaluate the SQL based on the number of rows returned by the query. Standard b-tree indexes can be added to tables, and bitmapped and function-based indexes can also eliminate full-table scans.

Cache small-table full-table scans—In this step we ensure that a dedicated data buffer is available for the rows.

Verify optimal index usage—This step is critical because you may have "missing" indexes in your database, causing excessive I/O.

Materialize your aggregations and summaries for static tables - One features of the Oracle SQLAccess advisor is recommendations for new indexes and suggestions for materialized views.

Again, this is only a high-level overview of the Oracle performance tuning steps. For complete details on the steps for Oracle performance tuning, see my book "Oracle Tuning: The Definitive Reference".

Friday, March 5, 2010

RMAN quick ref

http://www.psoug.org/reference/rman.html

------------------------------------------------------------------------------------------------------------------------------------
Allocation
------------------------------------------------------------------------------------------------------------------------------------

ALLOCATE CHANNEL c1 DEVICE TYPE sbt
PARMS='SBT_LIBRARY=/mediavendor/lib/libobk.so ENV=(NSR_SERVER=tape_srv,NSR_
GROUP=oracle_tapes)';

ALLOCATE CHANNEL ch3 DEVICE TYPE DISK FORMAT '/disk1/%d_backups/%U';
ALLOCATE CHANNEL ch3 DEVICE TYPE sbt;
ALLOCATE AUXILIARY CHANNEL aux1 DEVICE TYPE DISK;

ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE DISK;

------------------------------------------------------------------------------------------------------------------------------------
CONFIGURE
------------------------------------------------------------------------------------------------------------------------------------

CONFIGURE CHANNEL DEVICE TYPE sbt
PARMS='SBT_LIBRARY=/mediavendor/lib/libobk.so
ENV=(NSR_SERVER=tape_svr,NSR_CLIENT=oracleclnt,NSR_GROUP=ora_tapes)'
FORMAT "BACKUP_%U";


OTHERS

CONFIGURE MAXSETSIZE TO 7500K;
CONFIGURE MAXSETSIZE = 100M;

CONFIGURE AUXNAME FOR DATAFILE 2 TO '/newdisk/datafiles/df2.df;'
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/oracle/oradata/trgt/snap_trgt.ctl';

CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 2;

clear

CONFIGURE EXCLUDE FOR TABLESPACE cwmlite CLEAR;
CONFIGURE AUXNAME FOR DATAFILE 2 CLEAR;
CONFIGURE CHANNEL DEVICE TYPE sbt CLEAR;
CONFIGURE CHANNEL 3 DEVICE TYPE DISK CLEAR;
CONFIGURE DEVICE TYPE DISK CLEAR;
CONFIGURE DEFAULT DEVICE TYPE CLEAR;


DUPLEXING

CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE sbt TO 2;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 2;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE sbt TO 2;


Device

CONFIGURE DEVICE TYPE sbt PARALLELISM 1;
CONFIGURE DEVICE TYPE DISK PARALLELISM 3;
CONFIGURE DEFAULT DEVICE TYPE TO sbt;
CONFIGURE DEVICE TYPE DISK PARALLELISM 2 BACKUP TYPE TO COPY;
CONFIGURE DEVICE TYPE 'SBT_TAPE' PARALLELISM 2 BACKUP TYPE TO BACKUPSET;

Channel+disk

CONFIGURE CHANNEL DEVICE TYPE DISK MAXPIECESIZE = 2G;
CONFIGURE CHANNEL DEVICE TYPE sbt RATE 1M;
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT = /tmp/%U;
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT '/save1/%U', '/save2/%U';
CONFIGURE CHANNEL DEVICE TYPE DISK MAXPIECESIZE = 2M;
CONFIGURE CHANNEL 3 DEVICE TYPE DISK MAXPIECESIZE = 900K;
CONFIGURE CHANNEL DEVICE TYPE sbt PARMS 'ENV=(NSR_DATA_VOLUME_POOL=first_pool)';

controlfile

CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP OFF;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/u02/%F';

Optimization

CONFIGURE BACKUP OPTIMIZATION ON;
CONFIGURE BACKUP OPTIMIZATION OFF;
CONFIGURE BACKUP OPTIMIZATION CLEAR;

------------------------------------------------------------------------------------------------------------------------------------
Backup
------------------------------------------------------------------------------------------------------------------------------------

DATABASE

BACKUP DATABASE;
BACKUP DATABASE FORMAT '/tmp/%U', '?/dbs/%U', '?/oradata/%U';
BACKUP DEVICE TYPE sbt COPY OF DATABASE;
BACKUP DEVICE TYPE sbt COPY OF DATABASE DELETE INPUT;
BACKUP FORMAT = 'UW_%d/%t/%s/%p' ARCHIVELOG LIKE '%arc_dest%';
BACKUP TAG 'weekly_full_db_bkup' DATABASE MAXSETSIZE 10M;
BACKUP AS COMPRESSED BACKUPSET DEVICE TYPE DISK COPIES 2 DATABASE FORMAT '/u01/db_%U', '/u02/db_%U';

controlfile

BACKUP DEVICE TYPE sbt CURRENT CONTROLFILE;
BACKUP CURRENT CONTROLFILE TO DESTINATION '/u01/backups';
BACKUP AS COPY CURRENT CONTROLFILE;


SPFILE

BACKUP SPFILE TO DESTINATION '/u01/backups';

TABLESPACE

BACKUP TABLESPACE users;
BACKUP TABLESPACE users FORMAT = '/tmp/users_%u%p%c';
BACKUP TABLESPACE tools MAXSETSIZE 5G;
BACKUP AS COPY TABLESPACE system, tools, users, undotbs;


DATAFILE

BACKUP DATAFILE 5,6,7;
BACKUP DATAFILE 5;
BACKUP DATAFILE 6;
BACKUP DATAFILE 7;
BACKUP DATAFILE 1 FORMAT '/u01/backups/%U', '/u02/backups/%U';
BACKUP DATAFILE 6 TO '/u01/backups', '/u02/backups';
BACKUP DEVICE TYPE DISK COPIES 3 DATAFILE 7 FORMAT '/tmp/%U','?/oradata/%U','?/%U';

ARCHIVELOG

BACKUP DEVICE TYPE sbt ARCHIVELOG ALL;
BACKUP NOT BACKED UP SINCE TIME 'SYSDATE-14' DATABASE PLUS ARCHIVELOG;
BACKUP ARCHIVELOG ALL;
BACKUP ARCHIVELOG FROM SEQUENCE 288 UNTIL SEQUENCE 388 THREAD 1 DELETE INPUT;
BACKUP DEVICE TYPE sbt ARCHIVELOG ALL FROM TIME 'SYSDATE-10' DELETE ALL INPUT;

PROXY

BACKUP DEVICE TYPE sbt PROXY DATAFILE 3;
BACKUP DEVICE TYPE sbt PROXY ONLY DATABASE;
BACKUP DEVICE TYPE sbt PROXY ONLY ARCHIVELOG ALL;

backupset

BACKUP DEVICE TYPE sbt BACKUPSET ALL;
BACKUP COPIES 2 DEVICE TYPE sbt BACKUPSET ALL;
BACKUP DEVICE TYPE sbt BACKUPSET COMPLETED BEFORE 'SYSDATE-7' DELETE INPUT;
BACKUP DEVICE TYPE sbt BACKUPSET ALL;
BACKUP DEVICE TYPE sbt BACKUPSET ALL DELETE INPUT;
backup backupset ;

BACKUP DEVICE TYPE DISK AS BACKUPSET DATABASE PLUS ARCHIVELOG;

BACKUP AS BACKUPSET DATAFILE 1;
BACKUP AS BACKUPSET (DATAFILE 3, 4, 5, 6, 7) (DATAFILE 8, 9);
BACKUP AS BACKUPSET DATAFILE 3, 4, 5, 6, 7, 8, 9;

BACKUP AS BACKUPSET DEVICE TYPE DISK COPIES 3 INCREMENTAL LEVEL 0 DATABASE;



BACKUP AS BACKUPSET
DATAFILE 1,2,3,4
CHANNEL ch1
CONTROLFILECOPY '/tmp/control01.ctl'
CHANNEL ch2
BACKUP AS BACKUPSET
ARCHIVELOG FROM TIME 'SYSDATE-14'
CHANNEL ch3;


TAG

BACKUP AS BACKUPSET TAG for_audit
COPY OF TABLESPACE users FROM TAG monday_users TABLESPACE SYSTEM FROM TAG monday_system;
BACKUP ARCHIVELOG ALL TAG first_copy;
DELETE ARCHIVELOG ALL BACKED UP 2 TIMES TO DEVICE TYPE sbt;
BACKUP DEVICE TYPE sbt DATAFILECOPY FROM TAG 'LATESTCOPY' FORMAT 'Datafile%f_Database%d';
BACKUP TAG 'weekly_full_db_bkup' DATABASE MAXSETSIZE 10M;

policy based


BACKUP DATABASE KEEP UNTIL TIME "TO_DATE('31-DEC-2007' 'dd-mon-yyyy')" NOLOGS;
BACKUP DATABASE NOT BACKED UP SINCE TIME 'SYSDATE-1';

BACKUP MAXSETSIZE 10G DATABASE PLUS ARCHIVELOG;
BACKUP NOT BACKED UP SINCE TIME 'SYSDATE-1' MAXSETSIZE 10M DATABASE PLUS ARCHIVELOG;

BACKUP TABLESPACE users KEEP FOREVER NOLOGS;

BACKUP MAXSETSIZE = 100M ARCHIVELOG ALL;
BACKUP ARCHIVELOG FROM TIME 'SYSDATE-1' UNTIL TIME 'SYSDATE';

BACKUP DURATION 3:30 DATABASE;
BACKUP DURATION 4:00 TABLESPACE users;
BACKUP DURATION 4:00 PARTIAL TABLESPACE users FILESPERSET 1;
BACKUP DURATION 4:00 PARTIAL MINIMIZE TIME DATABASE FILESPERSET 1;
BACKUP DURATION 4:00 PARTIAL MINIMIZE LOAD DATABASE FILESPERSET 1;

BACKUP DATABASE FORCE;
BACKUP ARCHIVELOG ALL FORCE;


EXCLUDING

CONFIGURE EXCLUDE FOR TABLESPACE cwmlite;
CONFIGURE EXCLUDE FOR TABLESPACE example;

BACKUP DATABASE NOEXCLUDE;
BACKUP TABLESPACE cwmlite, example;

CONFIGURE EXCLUDE FOR TABLESPACE cwmlite CLEAR;
CONFIGURE EXCLUDE FOR TABLESPACE example CLEAR;

BACKUP DATABASE
SKIP INACCESSIBLE
SKIP READONLY
SKIP OFFLINE;

------------------------------------------------------------------------------------------------------------------------------------

RESTORE
------------------------------------------------------------------------------------------------------------------------------------

RESTORE CONTROLFILE;
RESTORE CONTROLFILE FROM AUTOBACKUP;
RESTORE SPFILE FROM AUTOBACKUP;

RESTORE DATAFILE '?/oradata/trgt/tools01.dbf';

------------------------------------------------------------------------------------------------------------------------------------

recovery
------------------------------------------------------------------------------------------------------------------------------------

RECOVER DATABASE NOREDO;
RECOVER TABLESPACE users, tools UNTIL LOGSEQ 1300 THREAD 1

RECOVER DATABASE TEST
RECOVER DATABASE USING BACKUP CONTROLFILE UNTIL CANCEL TEST
RECOVER TABLESPACE users TEST
RECOVER DATABASE UNTIL CANCEL TEST


BLOCK RECOVERY

BLOCKRECOVER
DATAFILE 7 BLOCK 3
DATAFILE 2 BLOCK 235;

BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 19 FROM BACKUPSET;
BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 19 FROM DATAFILECOPY;
BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 199 FROM TAG = mondayam;
BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 19 RESTORE UNTIL 'SYSDATE-7';
BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 19 RESTORE UNTIL SCN 100;
BLOCKRECOVER DATAFILE 8 BLOCK 13 DATAFILE 2 BLOCK 19 RESTORE UNTIL SEQUENCE 7024;

BLOCKRECOVER CORRUPTION LIST RESTORE UNTIL TIME 'SYSDATE-10';

------------------------------------------------------------------------------------------------------------------------------------
MANAGING
------------------------------------------------------------------------------------------------------------------------------------


SHOWING

SHOW CHANNEL FOR DEVICE TYPE sbt;
SHOW DEFAULT DEVICE TYPE;
SHOW CHANNEL;
SHOW BACKUP OPTIMIZATION;
SHOW DATAFILE BACKUP COPIES;
SHOW EXCLUDE;
SHOW AUXNAME;
SHOW SNAPSHOT CONTROLFILE NAME;
show datafile backup copies;
show archivelog backup copies;
show controfile autobackup;
show device type;
show encryption algorithm;
show maxsetsize;
show retention policy;
show retention policy to redundancy;

CHECKING

CROSSCHECK BACKUPPIECE
CROSSCHECK BACKUPSET OF TABLESPACE UWDATA;
CROSSCHECK COPY OF ARCHIVELOG ALL;
CROSSCHECK CONTROLFILECOPY
CROSSCHECK DATAFILECOPY ALL;
CROSSCHECK FOREIGN ARCHIVELOG ALL;
CROSSCHECK PROXY 941;


BACKUP CHECK LOGICAL DATABASE;
BACKUP VALIDATE DATABASE ARCHIVELOG ALL;
BACKUP VALIDATE CHECK LOGICAL DATABASE ARCHIVELOG ALL;

LIST BACKUP;
LIST BACKUP SUMMARY;
LIST SCRIPT NAMES;
LIST GLOBAL SCRIPT NAMES;
LIST ALL SCRIPT NAMES;


Reduntancy

CONFIGURE RETENTION POLICY TO REDUNDANCY 2;
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS;
CONFIGURE RETENTION POLICY TO NONE;

CHANGE BACKUP TAG 'db_archive_1' UNAVAILABLE;
CHANGE BACKUPSET TAG year_end_2002 KEEP FOREVER NOLOGS;
CHANGE BACKUPSET TAG year_end_2002 NOKEEP;
CHANGE BACKUPSET 2 NOKEEP;

DELETION

DELETE NOPROMPT BACKUP OF DATABASE COMPLETED BEFORE 'SYSDATE-7';
DELETE ARCHIVELOG ALL COMPLETED AFTER 'SYSDATE-7';
DELETE BACKUP DEVICE TYPE sbt;
DELETE BACKUP DEVICE TYPE DISK;
DELETE COPY;
DELETE COPY TAG 'LATESTCOPY';
DELETE SCRIPT 'full_backup';
DELETE GLOBAL SCRIPT 'global_full_backup';

VALIDATE

VALIDATE ARCHIVELOG ALL
VALIDATE ARCHIVELOG LIKE ''
VALIDATE ARCHIVELOG FROM SCN
VALIDATE ARCHIVELOG BETWEEN SCN AND SCN
VALIDATE ARCHIVELOG UNTIL SCN
VALIDATE ARCHIVELOG FROM SEQUENCE [THREAD ]
VALIDATE ARCHIVELOG SEQUENCE [THREAD ]
VALIDATE ARCHIVELOG SEQUENCE BETWEEN AND
VALIDATE ARCHIVELOG UNTIL SEQUENCE [THREAD ]
TIME BETWEEN '' AND ''
UNTIL TIME ''


VALIDATE CONTROLFILECOPY ALL
VALIDATE CONTROLFILECOPY ''
VALIDATE CONTROLFILECOPY LIKE ''


VALIDATE COPY OF DATABASE
VALIDATE COPY OF DATAFILE ''
VALIDATE COPY OF DATAFILE
VALIDATE COPY OF TABLESPACE '



VALIDATE CURRENT CONTROLFILE
VALIDATE DATABASE
VALIDATE DATAFILE ''
VALIDATE DATAFILE
VALIDATE DB_RECOVERY_FILE_DEST
VALIDATE RECOVERY AREA
VALIDATE RECOVERY FILES
VALIDATE SPFILE
VALIDATE TABLESPACE


------------------------------------------------------------------------------------------------------------------------------------

OTHERS

------------------------------------------------------------------------------------------------------------------------------------


ENCRYTION

CONFIGURE ENCRYPTION FOR DATABASE ON;
CONFIGURE ENCRYPTION FOR TABLESPACE uwdata OFF;
SET ENCRYPTION ON
CONFIGURE ENCRYPTION FOR DATABASE OFF
CONFIGURE ENCRYPTION ALGORITHM 'AES256';
CONFIGURE COMPRESSION ALGORITHM 'ZLIB';
CONFIGURE ENCRYPTION CLEAR;

CATALOG BASED

REGISTER DATABASE;
RESYNC CATALOG;
REPORT SCHEMA;
CATALOG DATAFILECOPY '/disk1/old_datafiles/01_01_2003/users01.dbf';
CATALOG ARCHIVELOG '/disk1/arch_logs/archive1_731.dbf','/disk1/arch_logs/archive1_732.dbf';
CATALOG START WITH '/disk1/backups/';
UNREGISTER DATABASE;


OTHERS

SET NEWNAME FOR DATAFILE '?/oradata/trgt/tools01.dbf' TO '/tmp/tools01.dbf';
SWITCH DATAFILE '/tmp/tools01.dbf' TO DATAFILECOPY '?/oradata/trgt/tools01.dbf';
RESTORE SPFILE TO PFILE '?/oradata/test/inittrgta.ora' FROM AUTOBACKUP;
DUPLICATE TARGET DATABASE TO 'dupdb';
DUPLICATE TARGET DATABASE TO dupdb NOFILENAMECHECK UNTIL TIME 'SYSDATE-7';

INCREMENTAL

BACKUP INCREMENTAL LEVEL 0 DATABASE;
BACKUP INCREMENTAL LEVEL 1 DIFFERENTIAL TABLESPACE users;
BACKUP INCREMENTAL LEVEL 1 CUMULATIVE DATABASE;
BACKUP INCREMENTAL LEVEL 1 CUMULATIVE SKIP INACCESSIBLE DATABASE;