Tuesday, June 23, 2026

How to Read an Oracle AWR Report: A Step-by-Step Guide for DBAs

How to Read an Oracle AWR Report: A Step-by-Step Guide for DBAs

Oracle AWR report performance analysis dashboard showing top SQL and wait events

If you've been doing Oracle performance tuning for any length of time, you know that knowing how to read an Oracle AWR report is one of the most important skills in your toolkit. The Automatic Workload Repository (AWR) report is a snapshot-based diagnostic report that captures database statistics at regular intervals — and it contains just about everything you need to identify what's hurting your database. In this post, I'm going to walk through an AWR report from top to bottom the way I do it after 20 years of performance work, so you know exactly what to look at and in what order.

What Is the Oracle AWR Report?

The Oracle Automatic Workload Repository (AWR) collects, processes, and maintains performance statistics for problem detection and self-tuning purposes. It's available in Oracle 11g and later and requires the Oracle Diagnostic Pack license (or Enterprise Edition with the Diagnostic and Tuning Pack). In Oracle 19c, AWR has been enhanced with global AWR for multitenant environments (CDB-level AWR), but the structure of a single-instance AWR report has been stable for years.

AWR snapshots are taken by default every 60 minutes and retained for 8 days. You can adjust this:

-- Check current AWR settings
SELECT snap_interval, retention
FROM   dba_hist_wr_control;

-- Change snapshot interval to 30 minutes, retention to 14 days
BEGIN
  DBMS_WORKLOAD_REPOSITORY.modify_snapshot_settings(
    retention => 20160,   -- 14 days in minutes
    interval  => 30       -- 30 minutes
  );
END;
/

Generating the AWR Report

Before you can analyze anything, you need to generate the report. The quickest way on the command line:

-- Find snapshot IDs for your window of interest
SELECT snap_id, begin_interval_time, end_interval_time
FROM   dba_hist_snapshot
ORDER BY snap_id DESC
FETCH FIRST 20 ROWS ONLY;

-- Generate HTML AWR report between snap_id 1100 and 1105 for instance 1
@$ORACLE_HOME/rdbms/admin/awrrpt.sql

You'll be prompted for report type (text or HTML — always choose HTML for readability), the number of days to look back, and the begin/end snapshot IDs. For programmatic generation:

SELECT output
FROM   TABLE(
         DBMS_WORKLOAD_REPOSITORY.awr_report_html(
           l_dbid       => (SELECT dbid FROM v$database),
           l_inst_num   => 1,
           l_bid        => 1100,
           l_eid        => 1105
         )
       );

The AWR Report Header: Establishing Baseline Context

The first thing I look at on every Oracle AWR report analysis is the header. It tells you the scope and health of the snapshot window before you dig into anything else. Key fields:

  • DB Time: Total time all sessions spent doing database work during the interval. This is the denominator for everything that follows.
  • Elapsed Time: Wall-clock duration of the snapshot window.
  • DB CPU: Time spent on CPU (as opposed to waiting).
  • Avg Active Sessions (AAS): DB Time / Elapsed Time in seconds. If this number is consistently above your CPU count, you have a congestion problem.

Example header values that would concern me:

Snap Id      Snap Time         Sessions  Curs/Sess
---------    ---------------   --------  ---------
Begin: 1100  20-Jun-26 10:00:00   320      12.5
End:   1105  20-Jun-26 11:00:00   318      13.1

Elapsed:           60.05 (mins)
DB Time:          847.31 (mins)
DB CPU:           112.44 (mins)
Redo size:    4,521,034,240  bytes

Here, DB Time is 847 minutes over a 60-minute window — that means roughly 14 average active sessions (847/60). If this server has 16 CPUs and those sessions are CPU-bound, you're nearly saturated. If they're wait-bound, something else is the culprit. This ratio is the very first diagnostic signal you should internalize.

Load Profile: The Big Picture in Numbers

The Load Profile section gives you per-second and per-transaction rates for key workload metrics. I look at this to understand the type of workload:

  • Logical reads/sec (consistent gets + db block gets): High values with low physical reads → good buffer cache hit ratio. Extremely high values overall → possibly inefficient SQL doing too many block visits.
  • Physical reads/sec: Reads from disk. A spike here is worth investigating in Top SQL.
  • Parses/sec vs. Hard parses/sec: Hard parses are expensive. If hard parses are > 5-10% of total parses, you have a cursor-sharing or bind variable problem.
  • Executes/sec: The throughput rate.
  • Redo size/sec: Proxy for write-heaviness of the workload.

A red flag I've seen many times: a system where parses/sec ≈ executes/sec. That almost always means the application is not using bind variables or is reconnecting constantly. Every parse is wasted CPU that could be serving real work.

Instance Efficiency Percentages

This section is a quick sanity check. You want most of these above 99%:

  • Buffer Hit %: Should be >99% for OLTP. Below 95% warrants buffer cache investigation.
  • Execute to Parse %: Should be high (80%+). Low values → application re-parsing too often.
  • Library Hit %: Shared pool efficiency. Low values mean you're wasting time re-loading cursors.
  • Parse CPU to Parse Elapsd %: If this is low, parses are spending more time waiting than on CPU — shared pool latch contention or hard parse overload.
  • Redo NoWait %: Should be near 100%. Low values mean redo log groups are too small or I/O is too slow for log writes.

Top 10 Foreground Wait Events: The Real Story

This is where I spend most of my time on an AWR report analysis. The Top Wait Events section tells you what Oracle sessions spent the most time waiting for. Do not conflate "foreground" (session waits) with "background" waits — we focus on foreground for user impact.

Common wait events and what they mean:

  • db file sequential read: Single-block I/O reads — usually index lookups. High values mean your indexes are doing a lot of work (which can be fine) or you have I/O subsystem latency. Check avg wait time. Under 1ms is excellent; above 5ms is a concern on SSD storage.
  • db file scattered read: Multi-block I/O — full table or index fast full scans. High values → full scans, possibly missing indexes.
  • log file sync: Sessions waiting for their redo to be flushed to disk on COMMIT. Consistently high → redo log groups are on slow storage, or the application is committing too frequently.
  • enq: TX - row lock contention: Sessions blocked waiting for row locks. Application-level locking issue — commits are not happening often enough, or there's a hot row.
  • library cache: mutex X: Contention in the shared pool — often too many hard parses or too many versions of the same cursor (literally thousands of child cursors due to bind-sensitive plans).
  • latch: cache buffers chains: Hot blocks in the buffer cache — a block being read or modified constantly by many sessions. Usually points to a hot index block (right-hand side of a monotonically increasing index) or a segment header.
  • CPU time: Not really a wait — this is time on CPU. If CPU time is at the top of this list, you are CPU-bound. Check Top SQL for CPU-hungry statements.

Here's the mental model I use: calculate each wait event's percentage of total DB Time. If one event accounts for more than 20-25% of DB Time, it is the thing to fix first. Everything else is noise until that one is resolved.

Top SQL: Finding the Offenders

The AWR report includes several Top SQL subsections:

  • SQL ordered by Elapsed Time — the most important for overall throughput impact
  • SQL ordered by CPU Time — pure CPU consumers
  • SQL ordered by Gets — logical I/O heavy hitters
  • SQL ordered by Reads — physical I/O heavy hitters
  • SQL ordered by Executions — high-frequency statements
  • SQL ordered by Parse Calls — statements being re-parsed frequently

For each statement you identify, grab the SQL_ID and examine it further:

-- Pull the full SQL text from AWR history
SELECT sql_text
FROM   dba_hist_sqltext
WHERE  sql_id = '&sql_id';

-- Review execution history and plan hash values
SELECT snap_id,
       executions_delta,
       elapsed_time_delta / NULLIF(executions_delta, 0) / 1e6 AS avg_elapsed_secs,
       rows_processed_delta / NULLIF(executions_delta, 0) AS avg_rows,
       plan_hash_value
FROM   dba_hist_sqlstat
WHERE  sql_id = '&sql_id'
ORDER  BY snap_id DESC;

-- Retrieve the actual execution plan used during the window
SELECT * FROM TABLE(
  DBMS_XPLAN.display_awr('&sql_id', format => 'ALLSTATS LAST')
);

The plan_hash_value column is gold. If you see a statement that had one plan hash value for months and suddenly switched to a new one right before a performance incident, you've found your culprit. Pin the old plan using SQL Plan Baselines — see our guide on Oracle SQL Plan Baselines for Performance Stability.

Memory Statistics: SGA and PGA

The SGA Breakdown and PGA sections confirm whether memory is sized correctly:

  • Buffer Cache Advisory: Shows estimated physical reads if the cache were larger or smaller. If the curve flattens before your current size, you're fine. If it's still steep at your current size, you need more buffer cache.
  • PGA Memory Advisory: Shows estimated PGA over-allocation factor. A factor >1 means Oracle had to spill sorts and hash joins to disk — you need more PGA.
  • Shared Pool Advisory: Tracks library cache hit ratios at different shared pool sizes.
-- Confirm PGA spill to disk from AWR
SELECT snap_id,
       cache_hit_percentage,
       over_alloc_count
FROM   dba_hist_pgastat
WHERE  name = 'cache hit percentage'
ORDER  BY snap_id DESC;

Common Pitfalls When Reading AWR Reports

Over the years I've seen DBAs make the same mistakes on Oracle AWR report analysis. Avoid these:

  1. Comparing across different snapshot intervals. A 30-minute AWR snapshot and a 60-minute AWR snapshot will show wildly different absolute numbers. Always normalize to per-second rates or look at percentages of DB Time.
  2. Ignoring "idle" wait events. Events like SQL*Net message from client and jobq slave wait are idle waits — the session is doing nothing. The AWR Top 10 shows all wait events; filter out idle ones when computing the percentage of active work.
  3. Fixing the second problem before fixing the first. The wait event at the top of the list is the one to fix. Don't go hunting for the third or fourth event while the number-one wait is still unresolved — fixing it may eliminate the downstream waits entirely.
  4. Tunnel vision on SQL without checking instance-level metrics. Sometimes the SQL looks fine but the storage is degraded, or a node is down in RAC and all connections are on one instance. The header and the Load Profile often tell this story before you even get to Top SQL.
  5. Generating AWR reports over windows that span a restart. Post-startup stats are not comparable to steady-state stats. Always check the header for instance start time and avoid snapshots that cross it.

A Quick Triage Workflow

When I open an AWR report under pressure — because the business is calling and production is slow — I use this 5-minute triage sequence:

  1. Header → AAS. Is AAS above CPU count? If yes, resource saturation. If no, latency problem.
  2. Top Wait Events → #1 event. What are sessions waiting for? This is the primary constraint.
  3. Load Profile → Hard Parses. Are hard parses unusually high? If yes, application or shared pool problem.
  4. Top SQL by Elapsed Time → Top 1-3 statements. Grab SQL_IDs, check execution plans.
  5. Instance Efficiency → Buffer Hit %, Redo NoWait %. Quick confirmation of cache and redo health.

In most cases, five minutes of this process narrows the problem to one of three buckets: bad SQL, resource saturation, or I/O subsystem degradation. Everything else is a follow-up investigation.

Conclusion

Knowing how to read an Oracle AWR report efficiently is what separates a reactive DBA from a proactive one. The report contains an enormous amount of data, but the sequence matters: start with the header to understand workload intensity, move to wait events to understand the primary constraint, then drill into Top SQL to find the specific statements driving that constraint. Combined with the advisory sections for memory and the Load Profile for workload characterization, you have a complete picture of database health in a single document.

If you found this Oracle AWR report tutorial useful, drop a comment below — I'd especially love to hear about specific wait events you're struggling to interpret. And if you want posts like this delivered to you twice a week, subscribe to oratab19c.blogspot.com. Next up: SQL Plan Baselines for locking in good execution plans and preventing unplanned regressions.

Thursday, July 8, 2021

IBM DB2 - Database drop commands

 IBM DB2 - Database drop commands 


Removing The Old Database:

Login into db2inst2 Login and execute the below commands
db2 disconnect all
db2 deactivate database <<Database Name>>
db2 drop database <<Database Name >>

prompting back to directory: 

rm –Rf HBMEXP(Old Extracted Folder)
rm –Rf HBMDATABASE1(where the old db2 DB available)










IBM DB2 - Database Creation Steps

IBM DB2 - Database Creation Steps 

Below provided are the steps I have used to create a database in IBM db2 database engine. 


Connect to db2 prompt after installation:

$ db2

(c) Copyright IBM Corporation 1993,2007

Command Line Processor for DB2 Client 10.1.0

You can issue database manager commands and SQL statements from the command prompt. For example:

    db2 => connect to sample

    db2 => bind sample.bnd

db2 => db2start

DB20000I  The DB2START command completed successfully.

db2 =>



*****************************************************************
Create a new database with the name  'database1'

$ db2 create db database1 on /glotus4/db2/db1 using codeset UTF-8 territory US pagesize 4096 dft_extent_sz 2;

DB20000I  The CREATE DATABASE command completed successfully.

$ db2 connect to database1;

   Database Connection Information


 Database server        = DB2/AIX64 10.1.0

 SQL authorization ID   = DASUSR2

 Local database alias   = DATABASE1


$ db2 create database partition group dpg_32k;

DB20000I  The SQL command completed successfully.

$ db2 create bufferpool bp_32k size 1000 automatic  pagesize 32 k;

DB20000I  The SQL command completed successfully.

$

***************************************************************
Set all the database parameters:

$ db2 update db cfg using DBHEAP AUTOMATIC;

DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.

$ db2 update db cfg using APPLHEAPSZ 4096;

DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.

$ db2 update db cfg using APP_CTL_HEAP_SZ 1024;

DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.

SQL1363W  Database must be deactivated and reactivated before the changes to one or more of the configuration parameters will be effective.

$ db2 update db cfg using LOGFILSIZ 10240;

DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.

SQL1363W  Database must be deactivated and reactivated before the changes to one or more of the configuration parameters will be effective.

$ db2 update db cfg using AUTO_RUNSTATS OFF;

DB20000I  The UPDATE DATABASE CONFIGURATION command completed successfully.

$ db2 disconnect all;

DB20000I  The SQL DISCONNECT command completed successfully.

$ db2 connect to database1;

   Database Connection Information

 Database server        = DB2/AIX64 10.1.0

 SQL authorization ID   = DASUSR2

 Local database alias   = DATABASE1

$ db2 create bufferpool bpool size 500 pagesize 32K;

DB20000I  The SQL command completed successfully.

**********************************************************
Create tablespaces on the database:

$ db2 CREATE TEMPORARY TABLESPACE TEMPSPACE2 pagesize 32k EXTENTSIZE 80 bufferpool bpool;

DB20000I  The SQL command completed successfully.

$ db2 create large tablespace DATA in dpg_32k pagesize 32 k extentsize 2 bufferpool bp_32k AUTORESIZE YES INCREASESIZE 5 PERCENT MAXSIZE NONE;

DB20000I  The SQL command completed successfully.

$ db2 create large tablespace INDEX in dpg_32k pagesize 32 k  extentsize 2 bufferpool bp_32k AUTORESIZE YES INCREASESIZE 5 PERCENT MAXSIZE NONE;

DB20000I  The SQL command completed successfully.

$

**********************************************************
Grant privileges to the user:

$ db2 GRANT DBADM, CREATETAB, BINDADD, CONNECT, CREATE_NOT_FENCED_ROUTINE, IMPLICIT_SCHEMA, LOAD, CREATE_EXTERNAL_ROUTINE,  QUIESCE_CONNECT, SECADM ON DATABASE TO USER db2inst2;

DB20000I  The SQL command completed successfully.

$

$ db2 grant use of tablespace DATA to user db2inst2;

DB20000I  The SQL command completed successfully.

$ db2 grant use of tablespace INDEX to user db2inst2;

DB20000I  The SQL command completed successfully.

$


db2 => db2 catalog tcpip node database1 remote <ip address> server 50000 

*****************************************************
Catalog the ip and node details 

catalog tcpip node database1 remote <ip address> server 50000 

catalog tcpip node database1 remote <ip address> server 1525

catalog dcs database database1 as database1

catalog database database1 as database1 at node SAN_NODE authentication dcs

connect to database1 user dasusr1: Database Connection Information Database server = DB2/AIX64 9.5.0 SQL authorization ID = < schema_name > Local database alias = <database name>

*****************************************************
Created node must be displayed upon testing:

db2 => LIST NODE DIRECTORY

Node Directory

Number of entries in the directory = 2

Node 1 entry:

 Node name                      = DATABASE1

 Comment                        =

 Directory entry type           = LOCAL

 Protocol                       = TCPIP

 Hostname                       = <ip address>

 Service name                   = 50000


db2 => db2 LIST DATABASE DIRECTORY

SQL0104N  An unexpected token "db2" was found following "BEGIN-OF-STATEMENT".

Expected tokens may include:  "SELECT".  SQLSTATE=42601

db2 => LIST DATABASE DIRECTORY

System Database Directory

Number of entries in the directory = 1

Database 1 entry:

 Database alias                       = DATABASE1

 Database name                        = DATABASE1

 Node name                            = DATABASE1

 Database release level               = f.00

 Comment                              =

 Directory entry type                 = Remote

 Catalog database partition number    = -1

 Alternate server hostname            =

 Alternate server port number         =





Tuesday, July 6, 2021

Space Reclamation Procedure for Oracle tables - Move tablespace

 Space Reclamation Procedure for oracle objects: move tablespace

There are various space reclamation procedures available for the oracle database and the tables. Below is one of the methodologies to move all the tables and objects to the new tablespace. Though I have run it successfully in an environment, I remember correcting it while running it. 


Pre-requisites:

1. Run it in test environment before running it in any important environment.

2. Have enough space in the new tablespace before initiating the scripts. 

3. If a lob segment is not moved, then that particular table's data has to be moved to a new table created. 

4. Always connect to the schema to be moved to run the scripts. Must not run as a 'SYS' user. 

5. Tablespaces 'TBSDATA' and 'TBSINDEX' were created for the below example. 

TEMP TABLES:

CREATE TABLE RECLAIM_SEGMENTS AS SELECT * FROM USER_SEGMENTS;

CREATE TABLE COMPLETED_TABLES AS SELECT SEGMENT_NAME FROM USER_SEGMENTS WHERE 1=2;

CREATE TABLE NOT_COMPLETED AS SELECT SEGMENT_NAME FROM USER_SEGMENTS WHERE 1=2;


PL/SQL PROCEDURE: 

SET SERVEROUTPUT ON

BEGIN

FOR cur_rec IN (SELECT SEGMENT_NAME, SEGMENT_TYPE FROM  RECLAIM_SEGMENTS )

LOOP

BEGIN

EXECUTE IMMEDIATE 'ALTER TABLE  ' || cur_rec.SEGMENT_NAME || ' enable row movement ';

EXECUTE IMMEDIATE 'ALTER TABLE  ' || cur_rec.SEGMENT_NAME || ' MOVE TABLESPACE TBSLIVEDATA  parallel 20 nologging ';

EXECUTE IMMEDIATE 'ALTER TABLE  ' || cur_rec.SEGMENT_NAME || ' MOVE LOB(XMLRECORD) STORE AS (TABLESPACE TBSDATA)  parallel 20 nologging ';

BEGIN

FOR cur_index in (select INDEX_NAME from DBA_INDEXES where table_name='' || cur_rec.SEGMENT_NAME  || ''   and INDEX_NAME NOT LIKE '%SYS%'  and INDEX_NAME NOT LIKE '%LOB%'    and owner='USER')

LOOP

EXECUTE IMMEDIATE 'ALTER INDEX  ' || cur_index.INDEX_NAME ||' REBUILD TABLESPACE TBSINDEX  parallel 10 nologging ';

END LOOP;

END;

EXECUTE IMMEDIATE 'INSERT INTO COMPLETED_TABLES  VALUES (''' || cur_rec.SEGMENT_NAME || ''')';

EXECUTE IMMEDIATE 'DELETE FROM RECLAIM_SEGMENTS WHERE SEGMENT_NAME ='''|| cur_rec.SEGMENT_NAME || '''';

EXECUTE IMMEDIATE 'ALTER TABLE  ' || cur_rec.SEGMENT_NAME || ' disable row movement ';

Commit;

EXCEPTION

WHEN OTHERS THEN

EXECUTE IMMEDIATE 'INSERT INTO NOT_COMPLETED  VALUES (''' || cur_rec.SEGMENT_NAME || ''')';

DBMS_OUTPUT.put_line('FAILED: COULD NOT BE ALTERED ' || cur_rec.SEGMENT_TYPE || ' "' || cur_rec.SEGMENT_NAME || '"');

END;

END LOOP;

END;

/


Monday, July 5, 2021

PL/SQL procedure to Drop all the objects from the oracle user

Procedure to drop the objects from a Oracle Schema : 

Below is the pl/sql procedure to drop the user objects using condition. 
Use it with EXTREME CAUTION, as the below steps of procedure drops the objects from the connected user. 


STEP 1: 
Create a temporary table with object_name and object_type as the columns, create a combined index as it gives better performance. 

SQL 1: create table DEV1_OBJECTS_DEL as select object_name, object_type from user_objects; 
SQL 2: create unique index ix_DEV_OBJECTS on DEV1_OBJECTS_DEL( object_name, object_type ) parallel 10; 


STEP 2: 
Run the below procedure, the procedure refers to the 'DEV1_OBJECTS_DEL' table and drops the objects in the table. 


PL/SQL 1: 
----------------------------------------------------------------------------------------- 
SET SERVEROUTPUT ON;
DECLARE
cursor cur is SELECT object_name, object_type FROM  DEV1_OBJECTS_DEL;
BEGIN
FOR cur_rec IN CUR LOOP
BEGIN
EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '"';
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END LOOP;
END;
/
---------------------------------------------------------------------------------------------- 

NOTE: SYS objects and SYSTEM generated constraints cannot be dropped using the procedure, you need to drop it manually. 

Happy Coding.

Saturday, November 23, 2019

Steps to create a database using windows cmd prompt:


Steps to create a database using windows cmd prompt:

Pre-requisite:
1. Oracle Database must be installed:
2. Basic knowledge of script and database is must.
3. Run the below scripts in ORACLE HOME path. 


Step 1:
Set dbname and parameters

set /p ORACLE_HOME=Enter the ORACLE_HOME path:
cd %ORACLE_HOME%
cd ../jjj../..
cd oradata
set /p name=Enter the database name:
mkdir %name%
cd %name%
echo "YOUR FILES WILL BE STORED ON THIS DIRECTORY: %cd%"
mkdir diag


Step 2:
Create file 1.sql:

echo startup pfile='%cd%\init%name%.ora' nomount; > 1.sql
echo create spfile from pfile='%cd%\init%name%.ora'; >> 1.sql


Step 3:
Create init.ora file with parameters and values

echo pga_aggregate_target=922746880 > init%name%.ora
echo sga_target=2751463424 >> init%name%.ora
echo compatible='11.2.0.0.0' >> init%name%.ora
echo control_files='%cd%/control01.ctl','%cd%\control02.ctl' >> init%name%.ora
echo db_block_size=8192 >> init%name%.ora
echo db_name=%name% >> init%name%.ora
echo diagnostic_dest='%cd%\diag' >> init%name%.ora
echo processes=600 >> init%name%.ora
echo undo_tablespace='undotbs' >> init%name%.ora
echo open_cursors=5000 >> init%name%.ora

Step 3:
Create file 2.sql with create database query.

echo CREATE DATABASE "%name%" > 2.sql
echo LOGFILE GROUP 1 '%cd%\redo01.log' SIZE 50M BLOCKSIZE 512, GROUP 2 '%cd%\redo02.log' SIZE 50M BLOCKSIZE 512, GROUP 3 '%cd%\redo03.log' SIZE 50M BLOCKSIZE 512
echo DATAFILE '%cd%\system01.dbf' size 500m REUSE >> 2.sql
echo SYSAUX DATAFILE '%cd%\sysaux01.dbf' SIZE 325M REUSE >> 2.sql
echo UNDO TABLESPACE undotbs DATAFILE '%cd%\undotbs01.dbf' SIZE 900M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED >> 2.sql
echo DEFAULT TABLESPACE users DATAFILE '%cd%\users01.dbf' SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED >> 2.sql
echo DEFAULT TEMPORARY TABLESPACE tempts1 TEMPFILE '%cd%\temptbs01.dbf' SIZE 200M REUSE; >> 2.sql

echo CREATE TABLESPACE T24DATA DATAFILE '%cd%\T24DATA.DBF' SIZE 500M AUTOEXTEND ON MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO; > tablespace.sql
echo CREATE TABLESPACE T24INDEX DATAFILE '%cd%\T24INDEX.DBF' SIZE 500M AUTOEXTEND ON MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO; >> tablespace.sql


Step 4:
Create file user.sql with privileges 

echo CREATE USER t24 IDENTIFIED BY t24 DEFAULT TABLESPACE T24DATA QUOTA UNLIMITED ON T24DATA QUOTA UNLIMITED ON T24INDEX; > user.sql
echo grant connect to t24; >> user.sql
echo grant resource to t24; >> user.sql
echo grant query rewrite to t24; >> user.sql
echo grant create synonym to t24; >> user.sql
echo grant drop any procedure to t24; >> user.sql
echo grant create any table to t24; >> user.sql
echo grant select any table to t24; >> user.sql
echo grant update any table to t24; >> user.sql
echo grant insert any table to t24; >> user.sql
echo grant delete any table to t24; >> user.sql
echo grant drop any table to t24; >> user.sql
echo grant create any index to t24; >> user.sql
echo grant alter any index to t24; >> user.sql
echo grant drop any index to t24; >> user.sql
echo grant create any view to t24; >> user.sql
echo grant drop any view to t24; >> user.sql
echo grant create any directory to t24; >> user.sql
echo grant exp_full_database to t24; >> user.sql
echo grant imp_full_database to t24; >> user.sql
echo @%ORACLE_HOME%/rdbms/admin/catblock.sql >> user.sql
echo grANT EXECUTE ON DBMS_LOCK TO T24; >> user.sql

Step 5:

Create file run.sql with order of files to run 


echo @1.sql; > run.sql
echo @2.sql; >> run.sql
echo @%ORACLE_HOME%/rdbms/admin/catalog.sql; >> run.sql
echo @%ORACLE_HOME%/rdbms/admin/catproc.sql; >> run.sql
echo CONNECT system/system as sysdba; >> run.sql
echo @%ORACLE_HOME%/sqlplus/admin/pupbld.sql; >> run.sql
echo startup force >> run.sql
echo @tablespace.sql; >> run.sql
echo @user.sql; >> run.sql


Update the %name% with actual db name you are going to create and run the below steps. :

ORADIM -NEW -SID %name%
set ORACLE_SID=%name%

sqlplus / as sysdba < run.sql

Thursday, May 17, 2018

Linux script file to create database in Oracle

To create oracle database, user and tablespace in linux, use the below script file. Please go through the script file carefullly before executing or creating the database, as the values of sga_target and pga_aggregate_target are provided very less


kasi.sh : 

cd $ORACLE_HOME
ORACLEHOME=$ORACLE_HOME
cd ../../..
cd oradata
echo "Please enter the database name"
read name
mkdir $name
cd $name
dir_path=`pwd`;
echo "YOUR FILES WILL BE STORED ON THIS DIRECTORY: $dir_path"

cat > 1.sql <<EOF
startup pfile='$dir_path/init$name.ora' nomount;
create spfile from pfile='$dir_path/init$name.ora';
EOF

cat > init$name.ora <<EOF
pga_aggregate_target=922746880
sga_target=2751463424
compatible='11.2.0.0.0'
control_files='$dir_path/control01.ctl','$dir_path/control02.ctl'
db_block_size=8192
db_name='$name'
diagnostic_dest='$ORACLE_BASE/diag'
processes=600
undo_tablespace='undotbs'
open_cursors=5000
EOF

cat > create$name.sql <<EOF
CREATE DATABASE "$name"
LOGFILE
  GROUP 1 '$dir_path/redo01.log'  SIZE 50M BLOCKSIZE 512,
  GROUP 2 '$dir_path/redo02.log'  SIZE 50M BLOCKSIZE 512,
  GROUP 3 '$dir_path/redo03.log'  SIZE 50M BLOCKSIZE 512
DATAFILE '$dir_path/system01.dbf' size 500m REUSE
SYSAUX DATAFILE '$dir_path/sysaux01.dbf' SIZE 325M REUSE
UNDO TABLESPACE undotbs DATAFILE '$dir_path/undotbs01.dbf' SIZE 900M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED
DEFAULT TABLESPACE users DATAFILE '$dir_path/users01.dbf' SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED
DEFAULT TEMPORARY TABLESPACE tempts1 TEMPFILE '$dir_path/temptbs01.dbf' SIZE 200M REUSE;
EOF

cat > tablespace.sql << EOF
CREATE TABLESPACE DATA DATAFILE '$dir_path/DATA.DBF' SIZE 500M AUTOEXTEND ON MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;
EOF

cat > user.sql << EOF
CREATE USER user1 IDENTIFIED BY pass1 DEFAULT TABLESPACE DATA QUOTA UNLIMITED ON DATA;
grant connect to user1;
grant resource to user1;
grant query rewrite to user1;
grant create synonym to user1;
grant drop any procedure to user1;
grant create any table to user1;
grant select any table to user1;
grant update any table to user1;
grant insert any table to user1;
grant delete any table to user1;
grant drop any table to user1;
grant create any index to user1;
grant alter any index to user1;
grant drop any index to user1;
grant create any view to user1;
grant drop any view to user1;
grant create any directory to user1;
grant exp_full_database to user1;
grant imp_full_database to user1;
@?/rdbms/admin/catblock.sql;
grANT EXECUTE ON DBMS_LOCK TO user1;
EOF

export $ORACLE_SID=$name;
sqlplus -s /nolog << EOF
CONNECT / as sysdba;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@1.sql;
@create$name.sql;
@?/rdbms/admin/catalog.sql;
@?/rdbms/admin/catproc.sql;
conn system/manager;
@?/sqlplus/admin/pupbld.sql;
startup force;
@tablespace.sql;
@user.sql;
shut immediate
EOF