Friday, November 20, 2009

Data Dictionary and Dynamic performance view

The Database Library is built on a Data Dictionary, which provides a complete description of record layouts and indexes of the database, for validation and efficient data access. You can use the data dictionary for automated database creation, including building tables, indexes, and referential constraints, and granting access rights to individual users and groups. The database dictionary supports the concept of Attached Objects, which allow database records to include compressed BLOBs (Binary Large Objects) containing images, text, sounds, video, documents, spreadsheets, or programmer-defined data types.

You can request information about the dictionary table


SELECT comments
FROM dictionary WHERE table_name='DICTIONARY'
COMMENTS
--------------------------------------------------------------------------------
Description of data dictionary tables and views

DBA_VIEWS


Description of dba_views
·   OWNER               Owner of the view
·   VIEW_NAME           Name of the view
·   TEXT_LENGTH         Length of the view text
·   TEXT                View text
·   TYPE_TEXT_LENGTH    Length of the type clause of the object view
·   TYPE_TEXT           Type clause of the object view
·   OID_TEXT_LENGTH     Length of the WITH OBJECT OID clause of the object view
·   OID_TEXT            WITH OBJECT OID clause of the object view
·   VIEW_TYPE_OWNER     Owner of the type of the view if the view is an object view
·   VIEW_TYPE           Type of the view if the view is an object view
·   SUPERVIEW_NAME      Name of the superif view is a subview



To get Full list of your Data Dictionary view run following query on your database.
SELECT *
from  dba_views
where owner = 'SYS'
      and view_name like 'DBA%';
ORDER BY view_name desc

[N.B: You can use TEXT field to view he information about the objects]

ALL_VIEWS


Description of all_views
·   OWNER               Owner of the view
·   VIEW_NAME           Name of the view
·   TEXT_LENGTH         Length of the view text
·   TEXT                View text
·   TYPE_TEXT_LENGTH    Length of the type clause of the object view
·   TYPE_TEXT           Type clause of the object view
·   OID_TEXT_LENGTH     Length of the WITH OBJECT OID clause of the object view
·   OID_TEXT            WITH OBJECT OID clause of the object view
·   VIEW_TYPE_OWNER     Owner of the type of the view if the view is an object view
·   VIEW_TYPE           Type of the view if the view is an object view
·   SUPERVIEW_NAME      Name of the superif view is a subview

You can also get Full list of your Data Dictionary view run following query.
select TEXT
from ALL_VIEWS
where owner='SYSTEM'

V$FIXED_TABLE


This Dynamic performance view Contains the name of all V$, X$ and GV$ tables.



Description of V$FIXED_TABLE
·   NAME          Name of the object
·   OBJECT_ID     Identifier of the fixed object
·   TYPE          Object type (TABLE | VIEW)
·   TABLE_NUM     Number that identifies the dynamic performance table if it is of type TABLE

To get Full list of Dynamic Performance View (V$) run following query
SELECT name
from   V$FIXED_TABLE
where  name like 'V$%';

When using these views you should have timed_statistics set to true in your init.ora file. This has minimal effect on performance and can be permanently left on (TIMED_STATISTICS=TRUE)

GV$ views are dynamic performance views in a parallel server environment. There is a GV$ view for almost every V$ view. These have an additional column INST_ID (instance number)

Managing Index

What is an Index?


An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.

Major Data Dictionary view to manage Index

DBA view describes indexes on all tables in the database. ALL view describes indexes on all tables accessible to the user. USER view is restricted to indexes owned by the user. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement.
·  DBA_INDEXES
·  ALL_INDEXES
·  USER_INDEXES

These views describe the columns of indexes on tables. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement. DBA_IND_EXPRESSIONS
·  DBA_IND_COLUMNS
·  ALL_IND_COLUMNS
·  USER_IND_COLUMNS

These views describe the expressions of function-based indexes on tables. DBA_IND_STATISTICS
·  ALL_IND_EXPRESSIONS
·  USER_IND_EXPRESSIONS

These views contain optimizer statistics for indexes.

INDEX_STATS Stores information from the last ANALYZE INDEX...VALIDATE STRUCTURE statement. INDEX_HISTOGRAM Stores information from the last ANALYZE INDEX...VALIDATE STRUCTURE statement. V$OBJECT_USAGE Contains index usage information produced by the ALTER INDEX...MONITORING USAGE functionality.
·  ALL_IND_STATISTICS
·  USER_IND_STATISTICS

Create an Index


Syntax: 
CREATE [UNIQUE] INDEX index_name
  ON table_name (column1, column2, . column_n)
  [ COMPUTE STATISTICS ];

Create a Function-Based Index


In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes.

The syntax for creating a function-based index is:
Syntax :
CREATE [UNIQUE] INDEX index_name
  ON table_name (function1, function2, . function_n)
  [ COMPUTE STATISTICS ];

SQL Code:

CREATE INDEX ename_idx ON emp (UPPER(emane));

Rebuild Index Syntax


Syntax: 
alter index index_name rebuild;

Rebuild Index of multiple users


SQL Code: 
Select  'alter index ' || OWNER ||'.'||INDEX_NAME || ' rebuild;'
from    all_indexes
Where   Owner = 'USER NAME'
    OR  Owner = 'USER NAME'

Collect Statistics on an Index


If you forgot to collect statistics on the index when you first created it or you want to update the statistics, you can always use the ALTER INDEX command to collect statistics at a later date.

The syntax for collecting statistics on an index is:
Syntax :
ALTER INDEX index_name
  REBUILD COMPUTE STATISTICS;

Move Table and Index to Other Table Space


Assume that the name of the table space convention like user name and postfix by idx and ts
Syntax: 
ALTER TABLE schema.table_name MOVE TABLESPACE TABLESPACE_NAME;
 
SQL Code:
select 'ALTER TABLE ' || OWNER || '.' || TABLE_NAME || ' MOVE TABLESPACE ' || OWNER || ’ts’ ||';'
from ALL_TABLES
WHERE OWNER IN ('USER NAME', 'USER NAME', 'USER NAME');

Rebuild and move index to another tablespace. Also it can be used to migrate index to tablespace with diffrent blocksize.

If your table contains LONG column you must export and import data with exp/expdp, imp/impdb utilities.
Syntax: 
ALTER INDEX schema.index_name REBUILD TABLESPACE TABLESPACE_NAME;

SQL Code
select 'ALTER INDEX ' || OWNER || '.' || INDEX_NAME || ' REBUILD TABLESPACE ' || OWNER || 'idx’;'
from ALL_INDEXES
WHERE OWNER IN ('USER NAME', 'USER NAME', 'USER NAME');

ORA-01502 index 'string.string' or partition of such index is in unusable state

Cause: An attempt has been made to access an index or index partition that has been marked unusable by a direct load or by a DDL operation.

Action: DROP the specified index, or REBUILD the specified index, or REBUILD the unusable index partition.

This error code says your index is in an unusable state. It’s easy to find these indexes.

How to identify the index unusable


SQL Code:
select index_name, status, owner
from all_indexes
where STATUS = 'UNUSABLE';

How to rebuild index unusable


SQL Code:
select 'alter index '||owner||'.'||index_name||' rebuild;'
from dba_indexes
where STATUS = 'UNUSABLE';

Drop an Index


Syntax:
DROP INDEX index_name;

Wednesday, November 18, 2009

Monotoring Session and SQL in Oracle10g

Some dynamic performance view to manage oracle user session and SQL.
·        v$sqlarea
·        v$session
·       v$sess_io
·        v$session
·        v$sqltext

Finding currently running SQL
 Select sesion.sid,
        sesion.username,
        optimizer_mode,
        hash_value,
        address,
        cpu_time,
        elapsed_time,
        sql_text
  from  v$sqlarea sqlarea, v$session sesion
 where sesion.sql_hash_value = sqlarea.hash_value
   and  sesion.sql_address    = sqlarea.address
   and  sesion.username is not null

See the I/O being done by an active SQL statement
select sess_io.sid,
       sess_io.block_gets,
       sess_io.consistent_gets,
       sess_io.physical_reads,
       sess_io.block_changes,
       sess_io.consistent_changes
from   v$sess_io sess_io, v$session sesion
where  sesion.sid = sess_io.sid
 and  sesion.username is not null

SQL to show the full SQL executing for active sessions.
select sesion.sid,
       sql_text
from   v$sqltext sqltext, v$session sesion
where  sesion.sql_hash_value = sqltext.hash_value
   and sesion.sql_address    = sqltext.address
   and sesion.username is not null
order by sqltext.piece

Which sessions are active this SQL will help
Select sid,
       to_char(logon_time,'MMDDYYYY:HH24:MI') logon_time,
       username,
       type,
       status,
       process,
       sql_address,
       sql_hash_value
from   v$session
where  username is not null

Killing Oracle Sessions


SQL Command to Kill Session
ALTER SYSTEM KILL SESSION 'sid,serial#';
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

Killing your own session
alter session set events 'immediate crash';

Kill sessions from the UNIX level with this command
 
kill -9 spid

N.B: This is dangerous and should not normally be done. Pick the wrong OS process and you could crash your instance. There may also be time you need to bulk kill Oracle sessionsor kill all sessions in Oracle.

Simply selecting again v$session will get you the data needed
select 'ALTER SYSTEM KILL SESSION '''||SID||','||SERIAL#||'''IMMEDIATE;'
from v$session
where username = '<SomeUserName in upper caps>'
 and  STATUS = 'ACTIVE';

Here is a Package to manage oracle session
create or replace package manage_users as
  procedure kill_user(the_sid in number);
  procedure kill_user(the_user in varchar2);
end manage_users;
/
create or replace package body manage_users as
  procedure kill_user(the_sid in number) as
    v_str varchar2(50) := 'alter system kill session '||chr(39);
    v_serial number;
  begin
    dbms_output.put_line(chr(10));
    dbms_output.put_line('Session to be killed:');
    dbms_output.put_line('---------------------');
    select serial# into v_serial
    from v$session
    where sid = the_sid;
    v_str := v_str||the_sid||','||v_serial||chr(39)||';';
    dbms_output.put_line(v_str);
    exception
    when no_data_found then
      dbms_output.put_line('No such session.');
  end;
  procedure kill_user(the_user in varchar2) as
    v_str varchar2(50) := 'alter system kill session '||chr(39);
    v_statement varchar2(50);
    cursor user_cur is
    select sid, serial#
    from v$session
    where username = upper(the_user);
  begin
    dbms_output.put_line(chr(10));
    dbms_output.put_line('Sessions to be killed:');
    dbms_output.put_line('----------------------');
    for user_rec in user_cur loop
     v_statement := v_str||user_rec.sid||','||user_rec.serial#||chr(39)||';';
     dbms_output.put_line(v_statement);
     v_statement := null;
    end loop;
  end;
end manage_users;
/

SQL> exec manage_users.kill_user('scott');
Sessions to be killed:
----------------------
alter system kill session '141,8';
alter system kill session '142,213';
alter system kill session '145,37';
PL/SQL procedure successfully completed.
SQL> exec manage_users.kill_user(141);
Session to be killed:
---------------------
alter system kill session '141,8';
PL/SQL procedure successfully completed.

Oracle Error : ORA-00018: maximum number of sessions exceeded


Cause: All session state objects are in use.


Action: Increase the value of the SESSIONS initialization parameter.


SELECT 'Currently, '
|| (SELECT COUNT(*) FROM V$SESSION) || ' out of '
|| DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX)
|| ' connections are used.' AS USAGE_MESSAGE
FROM V$LICENSE VL

How to Solve the Problem
Alter system set sessions=200 scope=spfile;

shutdown immediate;

startup;

Tuesday, November 17, 2009

Use oradim in Linux

There is no Utility tool like oradim in Linux/Unix. But only processes and these processes are automatically activated when the instance is started, and removed when the instance is shut down.

To start a new instance, say for example newsid, you create an initnewsid.ora file, use the initnewsid.ora for create a new instance

How to Create new sid by using oradim in Windows environment
C:\Documents and Settings\Master>oradim -NEW -SID newsid
C:\Documents and Settings\Master>set ORACLE_SID=newsid
C:\Documents and Settings\Master>sqlplus "/as sysdba"

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Nov 18 00:26:38 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup nomount pfile=<complete path for initnewsid.ora>

How to Create new sid in Linux environment
$ export ORACLE_SID=newsid
$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Nov 18 00:26:38 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup nomount pfile=<complete path for initnewsid.ora>

Startup and shutdown using oradim in windows
oradim -Startup -sid orcl
oradim -Shutdown -sid orcl

Startup and shutdown using Linux
$ export ORACLE_SID=orcl
$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Tue Sep 5 16:38:30 2009
Copyright (c) 1982, 2005, Oracle.  All rights reserved.
Connected to an idle instance.
SQL> startup/shutdown immediate

Help Line :


ORADIM -h

SQL Optimazition

Cost Based Optimizer (CBO)


This method is used if internal statistics are present. The CBO checks several possible execution plans and selects the one with the lowest cost, where cost relates to system resources. Cost-based optimization uses statistics stored with database objects to help evaluate which set of indexes and joins to follow. As long as you keep the statistics current, the optimizer would usually choose the fastest path possible. There are also some comments called optimizer hints. In Oracle 10g by default Cost Base Optimizer is used.
 
select value from v$parameter where name='optimizer_mode'

By default optimizer_mode set to CHOOSE, which means Cost Base Optimization.
 

Plan Table


The explain plan process stores data in the PLAN_TABLE.

 



SQL> CONN sys/password AS SYSDBA
Connected
SQL> @$ORACLE_HOME/rdbms/admin/utlxplan.sql
SQL> GRANT ALL ON sys.plan_table TO public;

AUTOTRACE Parameter to view the SQL Execution Plane


SET TIMING ON
SET AUTOTRACE ON

SELECT e.ename, d.dname
FROM   scott.emp e, scott.dept d
WHERE  e.deptno = d.deptno
  AND  e.ename  = 'KING';

Autotrace Enabled
Shows the execution plan as well as statistics of the statement.
ENAME      DNAME         
---------- --------------
KING       ACCOUNTING    

1 rows selected

Plan hash value: 351108634

----------------------------------------------------------------------------------------
| Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |         |     1 |    22 |     4   (0)| 00:00:01 |
|   1 |  NESTED LOOPS                |         |     1 |    22 |     4   (0)| 00:00:01 |
|*  2 |   TABLE ACCESS FULL          | EMP     |     1 |     9 |     3   (0)| 00:00:01 |
|   3 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     1 |    13 |     1   (0)| 00:00:01 |
|*  4 |    INDEX UNIQUE SCAN         | PK_DEPT |     1 |       |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("E"."ENAME"='KING')
   4 - access("E"."DEPTNO"="D"."DEPTNO")

   Statistics
-----------------------------------------------------------
               0  recursive calls
               0  db block gets
               9  consistent gets
               0  physical reads
               0  redo size
             800  bytes sent via SQL*Net to client
             414  bytes received via SQL*Net from client
               4  SQL*Net roundtrips to/from client
               1  sorts (memory)
               0  sorts (disk)
180ms elapsed

 



Here Cost (%CPU) is (4+4+3+1+0) 12

 

View Execution Plan or EXPLAIN PLAN


EXPLAIN PLAN FOR
  SELECT e.ename, d.dname
  FROM   scott.emp e, scott.dept d
  WHERE  e.deptno = d.deptno
  AND  e.ename  = 'KING';

EXPLAIN PLAN succeeded.

Also get the output from utlxpls.sql or utlxplp.sql

Source : @$ORACLE_HOME/rdbms/admin/utlxpls.sql
Source : @$ORACLE_HOME/rdbms/admin/utlxplp.sql

We use the DBMS_XPLAN.DISPLAY function to display the execution plan

SET LINESIZE 130
SET PAGESIZE 0
SELECT *
FROM   TABLE(DBMS_XPLAN.DISPLAY);
 

Rule Based Optimizer (RBO)


This method is used if the server has no internal statistics relating to the objects referenced by the statement. This method is no longer recommended by Oracle and will be duplicated in future releases.

 



To change the optimization mode
Alter session set OPTIMIZER_MODE = RULE

SET TIMING ON
SET AUTOTRACE ON

SELECT e.ename, d.dname
FROM   scott.emp e, scott.dept d
WHERE  e.deptno = d.deptno
  AND  e.ename  = 'KING';

Autotrace Enabled
Shows the execution plan as well as statistics of the statement.
ENAME      DNAME          
---------- --------------
KING       ACCOUNTING    

1 rows selected

Plan hash value: 351108634

------------------------------------------------
| Id  | Operation                    | Name    |
------------------------------------------------
|   0 | SELECT STATEMENT             |         |
|   1 |  NESTED LOOPS                |         |
|*  2 |   TABLE ACCESS FULL          | EMP     |
|   3 |   TABLE ACCESS BY INDEX ROWID| DEPT    |
|*  4 |    INDEX UNIQUE SCAN         | PK_DEPT |
------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("E"."ENAME"='KING')
   4 - access("E"."DEPTNO"="D"."DEPTNO")

Note
-----
   - rule based optimizer used (consider using cbo)

   Statistics
-----------------------------------------------------------
               0  recursive calls
               0  db block gets
               9  consistent gets
               0  physical reads
               0  redo size
             801  bytes sent via SQL*Net to client
             402  bytes received via SQL*Net from client
               4  SQL*Net roundtrips to/from client
               1  sorts (memory)
               0  sorts (disk)
290ms elapsed

 

Monday, November 16, 2009

How to determine Oracle Database And OS version

The following query determine you the database version
SQL> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
PL/SQL Release 10.2.0.1.0 - Production
CORE    10.2.0.1.0      Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 – Production

Alternatively, you can query from product_component_version.
SQL> col product for a40
SQL> col version for a11
SQL> col status for a15
SQL> select * from product_component_version;
PRODUCT                                  VERSION     STATUS
---------------------------------------- ----------- ---------------
NLSRTL                                   10.2.0.1.0  Production
Oracle Database 10g Enterprise Edition   10.2.0.1.0  Prod
PL/SQL                                   10.2.0.1.0  Production
TNS for 32-bit Windows:                  10.2.0.1.0  Production

By using export import data pump command you can determine client version
C:\>expdp help=y
Export: Release 10.2.0.1.0 - Production on Wednesday, 04 February, 2009 1:33:23
Copyright (c) 2003, 2005, Oracle. All rights reserved.

C:\>impdp help=y
Import: Release 10.2.0.1.0 - Production on Wednesday, 04 February, 2009 1:32:44
Copyright (c) 2003, 2005, Oracle. All rights reserved.
Both in case of Data Pump Export and Import first few digits show it version.

How to determine database compatibility level


COMPATIBILITY allows you to use a new release of Oracle, while at the same time guaranteeing backward compatibility with an earlier release.
In order to determine your current database compatibility level you can query from view database_compatible_level.
SQL> col value for a11
SQL> col description for a50
SQL> select * from database_compatible_level;
VALUE          DESCRIPTION
-----------    -----------------------------------------------------------------
10.2.0.1.0     Database will be completely compatible with this software version

Alternatively you can check your initialization parameter COMPATIBLE setting.
SQL> show parameter compatible
NAME                                 TYPE        VALUE
------------------------------------ ----------- -------------------
compatible                           string      10.2.0.1.0

You can also query from v$parameter.
SQL> select value from v$parameter where name='compatible';

VALUE
-----------
10.2.0.1.0

Listener Version


$ lsnrctl version

Version of OPATCH


$ perl $ORACLE_HOME/OPatch/opatch.pl version

Sun Solaris Version


$ cat /etc/release

RedHat Linux Version


vi /etc/redhat-release

Perl Version


$ perl -v
Or
$ perl -version

Java Version


$ java -version

Version of Installed packages on Solaris


$ pkginfo -igrep perl

Version of Installed packages on Linux


$ rpm -qagrep

Kernel Version of Unix


$ uname -a

Bit of Operating System


$ isainfo -b

Bit of your Oracle Software


To check if your Oracle Binary is 32 bit or 64 bit you can use the file command on any of the oracle executable like
$ file $ORACLE_HOME/bin/oracle

Finding Oracle data block size


SQL> SHOW PARAMETER DB_BLOCK_SIZE

Finding O/S block size


df -g grep "block size" (in Solrieas)

Check my Operating System 64-bit?

Solaris


$/usr/bin/isainfo –kv

Linux


$uname -m

Saturday, November 14, 2009

PL/SQL Packages DBMS_UTILITY

PL/SQL Packages DBMS_UTILITY


Source : {ORACLE_HOME}/rdbms/admin/dbmsutil.sql


COMPILE_SCHEMA Compile all procedures, functions, packages, and triggers in the specified schema.
Syntax 
DBMS_UTILITY.COMPILE_SCHEMA (
   schema VARCHAR2);
Code examples
EXEC DBMS_UTILITY.compile_schema('SCOTT');

ANALYZE_SCHEMA Analyze all the tables, clusters, and indexes in a schema.
Syntax
DBMS_UTILITY.ANALYZE_SCHEMA (
   schema           VARCHAR2,
   method           VARCHAR2,
   estimate_rows    NUMBER   DEFAULT NULL,
   estimate_percent NUMBER   DEFAULT NULL,
   method_opt       VARCHAR2 DEFAULT NULL);
Code examples
exec DBMS_UTILITY.ANALYZE_SCHEMA('SCOTT','COMPUTE');
exec DBMS_UTILITY.ANALYZE_SCHEMA('SCOTT','ESTIMATE', estimate_rows => 1000);
exec DBMS_UTILITY.ANALYZE_SCHEMA('SCOTT','ESTIMATE', estimate_percent => 25);
exec DBMS_UTILITY.ANALYZE_SCHEMA('SCOTT','DELETE')

[N.B: Do not collect stats for either the SYS or SYSTEM schemas.]



ANALYZE_DATABASE Analyze all the tables, clusters, and indexes in a database.
Syntax
DBMS_UTILITY.ANALYZE_DATABASE (
   method           VARCHAR2,
   estimate_rows    NUMBER   DEFAULT NULL,
   estimate_percent NUMBER   DEFAULT NULL,
   method_opt       VARCHAR2 DEFAULT NULL);
Code examples
exec DBMS_UTILITY.ANALYZE_DATABASE('COMPUTE');

ANALYZE_PART_OBJECT Equivalent to ANALYZE_DATABASE use for partition table.
Syntax
dbms_utility.analyze_part_object (
schema        IN VARCHAR2 DEFAULT NULL,
object_name   IN VARCHAR2 DEFAULT NULL,
object_type   IN CHAR DEFAULT 'T',
command_type  IN CHAR DEFAULT 'E',
command_opt   IN VARCHAR2 DEFAULT NULL,
sample_clause IN VARCHAR2 DEFAULT 'sample 5 percent');
Code examples
--assumes a partitioned table named 'part_tab'
exec dbms_utility.analyze_part_object('UWCLASS', 'PART_TAB', 'T', 'E', 'V');

FORMAT_ERROR_STACK Function Format the current error stack.
Syntax
DBMS_UTILITY.FORMAT_CALL_STACK
  RETURN VARCHAR2;
Code examples
CREATE TABLE error_log (
      timestamp     DATE,
      username      VARCHAR2(30),
      instance      NUMBER,
      database_name VARCHAR2(50),
      error_stack   VARCHAR2(2000)
      );

CREATE OR REPLACE TRIGGER LogErrors
      AFTER SERVERERROR ON DATABASE
    BEGIN
      INSERT INTO error_log
        VALUES (SYSDATE, SYS.LOGIN_USER, SYS.INSTANCE_NUM, SYS.DATABASE_NAME, DBMS_UTILITY.FORMAT_ERROR_STACK);
    END LogErrors;

DBMS_UTILITY.FORMAT_ERROR_BACKTRACE In Oracle Database 10g, Oracle added DBMS_UTILITY.FORMAT_ERROR_BACKTRACE, which can and should be called in your exception handler. It displays the call stack at the point where an exception was raised, even if the function is called in a PL/SQL block in an outer scope from that where the exception was raised. Thus, you can call DBMS_UTILITY.FORMAT_ERROR_BACKTRACE within an exception section at the top level of your stack and still find out where the error was raised deep within the call stack.
Syntax
DBMS_UTILITY. FORMAT_ERROR_BACKTRACE
  RETURN VARCHAR2;

FORMAT_CALL_STACK Function Format the current call stack.
 
Code examples
CREATE OR REPLACE PROCEDURE error_test1 AS
    BEGIN
       RAISE VALUE_ERROR;
    END error_test1;
    /

CREATE OR REPLACE PROCEDURE error_test2 AS
    BEGIN
       error_test1;
    EXCEPTION
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE('FORMAT_CALL_STACK ->' || DBMS_UTILITY.FORMAT_CALL_STACK);
          DBMS_OUTPUT.PUT_LINE('FORMAT_ERROR_STACK->' || DBMS_UTILITY.FORMAT_ERROR_STACK);
    END error_test2;
    /

SQL> SET SERVEROUTPUT ON
SQL> exec error_test2
FORMAT_CALL_STACK ->----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
2F226BE0         6  procedure SYSTEM.ERROR_TEST2
2F222E7C         1  anonymous block

FORMAT_ERROR_STACK->ORA-06502: PL/SQL: numeric or value error
PL/SQL procedure successfully completed.

IS_CLUSTER_DATABASE Function Is this database running in cluster database mode.
Syntax
DBMS_UTILITY.IS_CLUSTER_DATABASE
  RETURN NUMBER;
Code examples
SET SERVEROUTPUT ON
BEGIN
  IF DBMS_UTILITY.is_cluster_database THEN
    dbms_output.put_line('Clustered');
  ELSE
    dbms_output.put_line('Not Clustered');
  END IF;
END;
/

GET_TIME Function Current time in 100th's of a second.
Syntax
DBMS_UTILITY.GET_TIME
  RETURN NUMBER;
Code examples
BEGIN
  dbms_output.put_line( 'Start Time: ' || dbms_utility.get_time );
  dbms_lock.sleep(seconds => 10);
  dbms_output.put_line( 'End Time:   ' || dbms_utility.get_time );
END;
/
Start Time: 1119218
End Time:   1120218

PORT_STRING Function Return a string that uniquely identifies the version of Oracle and the operating system.
Syntax
DBMS_UTILITY.PORT_STRING
   RETURN VARCHAR2;
Code examples
SELECT DBMS_UTILITY.port_string
FROM   dual;

DB_VERSION Version information for the database.
Syntax
DBMS_UTILITY.DB_VERSION (
   version       OUT VARCHAR2,
   compatibility OUT VARCHAR2);
Code examples
SET SERVEROUTPUT ON
DECLARE
  v_version  VARCHAR2(100);
  v_compatibility  VARCHAR2(100);
BEGIN
  DBMS_UTILITY.db_version (version => v_version, compatibility => v_compatibility);
  DBMS_OUTPUT.put_line('Version: ' || v_version || '  Compatibility: ' || v_compatibility);
END;
/

CURRENT_INSTANCE Function Return the current connected instance number.
Syntax
DBMS_UTILITY.CURRENT_INSTANCE
   RETURN NUMBER;
Code examples
SELECT DBMS_UTILITY.current_instance
FROM   dual;

ACTIVE_INSTANCES Active instance numbers and names
Syntax
DBMS_UTILITY.IS_CLUSTER_DATABASE
  RETURN NUMBER;
Code examples
SET SERVEROUTPUT ON
DECLARE
  v_instance_table  DBMS_UTILITY.instance_table;
  v_instance_count  NUMBER;
BEGIN
  DBMS_UTILITY.active_instances (instance_table => v_instance_table,instance_count => v_instance_count);

  IF v_instance_count > 0 THEN
    FOR i IN 1 .. v_instance_count LOOP
      DBMS_OUTPUT.put_line(v_instance_table(i).inst_number || ' = ' || v_instance_table(i).inst_name);
    END LOOP;
  END IF;
END;
/

EXEC_DDL_STATEMENT Execute the DDL statement in parse_string.
Syntax
DBMS_UTILITY.EXEC_DDL_STATEMENT (
   parse_string IN VARCHAR2);
Code examples
BEGIN
dbms_utility.exec_ddl_statement('create table emp_test as select * from scott.emp');
END;
/

GET_PARAMETER_VALUE Function  Get an init.ora parameter.
Syntax
DBMS_UTILITY.GET_PARAMETER_VALUE (
   parnam IN     VARCHAR2,
   intval IN OUT BINARY_INTEGER,
   strval IN OUT VARCHAR2)
  RETURN BINARY_INTEGER;

Code examples
DECLARE
  parnam VARCHAR2(256);
  intval BINARY_INTEGER;
  strval VARCHAR2(256);
  partyp BINARY_INTEGER;
BEGIN
  partyp := dbms_utility.get_parameter_value('db_block_size',intval, strval);
  dbms_output.put('parameter value is: ');
  IF partyp = 1 THEN
    dbms_output.put_line(strval);
  ELSE
    dbms_output.put_line(intval);
  END IF;
  IF partyp = 1 THEN
    dbms_output.put('parameter value length is: ');
    dbms_output.put_line(intval);
  END IF;
  dbms_output.put('parameter type is: ');
  IF partyp = 1 THEN
    dbms_output.put_line('string');
  ELSE
    dbms_output.put_line('integer');
  END IF;
END;
/
parameter value is: 8192
parameter type is: integer

COMMA_TO_TABLE Convert a comma-separated list of names into a PL/SQL table of names.
Syntax
DBMS_UTILITY.COMMA_TO_TABLE (
   list   IN  VARCHAR2,
   tablen OUT BINARY_INTEGER,
   tab    OUT UNCL_ARRAY);
Code examples
CREATE TABLE c2t_test (readline VARCHAR2(200));

INSERT INTO c2t_test VALUES ('"1","Mainframe","31-DEC-2001"');
INSERT INTO c2t_test VALUES ('"2","MPP","01-JAN-2002"');
INSERT INTO c2t_test VALUES ('"3","Mid-Size","02-FEB-2003"');
INSERT INTO c2t_test VALUES ('"4","PC","03-MAR-2004"');
INSERT INTO c2t_test VALUES ('"5","Macintosh","04-APR-2005"');
COMMIT;

SELECT * FROM c2t_test;

CREATE TABLE test_import (
src_no NUMBER(5),
src_desc VARCHAR2(20),
load_date DATE);

CREATE OR REPLACE PROCEDURE load_c2t_test IS

c_string VARCHAR2(250);
cnt      BINARY_INTEGER;
my_table dbms_utility.lname_array;

BEGIN
  FOR t_rec IN (SELECT * FROM c2t_test)
  LOOP
    dbms_utility.comma_to_table(t_rec.readline, cnt, my_table);

    my_table(1) := TRANSLATE(my_table(1), 'A"','A');
    my_table(2) := TRANSLATE(my_table(2), 'A"','A');
    my_table(3) := TRANSLATE(my_table(3), 'A"','A');

    INSERT INTO test_import
    (src_no, src_desc, load_date)
    VALUES
    (TO_NUMBER(my_table(1)), my_table(2), TO_DATE(my_table(3)));
  END LOOP;
  COMMIT;
END load_c2t_test;
/

exec load_c2t_test;

SELECT * FROM test_import;

TABLE_TO_COMMA Converts a PL/SQL table of names into a comma-separated list of names.
Syntax
DBMS_UTILITY.TABLE_TO_COMMA (
   tab    IN  UNCL_ARRAY,
   tablen OUT BINARY_INTEGER,
   list   OUT VARCHAR2);

NAME_RESOLVE Resolve the given name.
Syntax
DBMS_UTILITY.NAME_RESOLVE (
   name          IN  VARCHAR2,
   context       IN  NUMBER,
   schema        OUT VARCHAR2,
   part1         OUT VARCHAR2,
   part2         OUT VARCHAR2,
   dblink        OUT VARCHAR2,
   part1_type    OUT NUMBER,
   object_number OUT NUMBER);

NAME_TOKENIZE Parse the given name.
Syntax
DBMS_UTILITY.NAME_TOKENIZE (
   name    IN  VARCHAR2,
   a       OUT VARCHAR2,
   b       OUT VARCHAR2,
   c       OUT VARCHAR2,
   dblink  OUT VARCHAR2,
   nextpos OUT BINARY_INTEGER);
Code examples
declare
        v_a      varchar2(30);
        v_b      varchar2(30);
        v_c      varchar2(30);
        v_dblink varchar2(30);
        v_next   number;

        type vcArray is table of varchar2(255);
        v_names vcArray := vcArray( 'tamimdba@gmail.com','tamim@oracledba','tamim.xyz' );
   begin
       for i in 1 .. v_names.count
       loop
       begin
           dbms_utility.name_tokenize(name   => v_names(i),
                                      a      => v_a,
                                      b      => v_b,
                                      c      => v_c,
                                      dblink => v_dblink,
                                      nextpos=> v_next );

           dbms_output.put_line( 'name    ' || v_names(i) );
           dbms_output.put_line( 'A       ' || v_a );
           dbms_output.put_line( 'B       ' || v_b );
           dbms_output.put_line( 'C       ' || v_c );
           dbms_output.put_line( 'dblink  ' || v_dblink );
           dbms_output.put_line( 'next    ' || v_next || ' ' || length(v_names(i)));
       exception
           when others then
               dbms_output.put_line( 'name    ' || v_names(i) );
               dbms_output.put_line( sqlerrm );
       end;
       end loop;
   end;

GET_HASH_VALUE Function Compute a hash value for the given string.
Syntax
DBMS_UTILITY.GET_HASH_VALUE (
   name      VARCHAR2,
   base      NUMBER,
   hash_size NUMBER)
  RETURN NUMBER;
Code examples
begin
   dbms_output.put_line ( dbms_utility.get_hash_value( to_char(1), 0, 1024 ) );
end;

DATA_BLOCK_ADDRESS_FILE Function Get the file number part of a data block address.
Syntax
DBMS_UTILITY.DATA_BLOCK_ADDRESS_FILE (
   dba NUMBER)
  RETURN NUMBER;

MAKE_DATA_BLOCK_ADDRESS Function Create a data block address given a file number and a block number.
Syntax
DBMS_UTILITY.MAKE_DATA_BLOCK_ADDRESS (
   file  NUMBER,
   block NUMBER)
  RETURN NUMBER;
Code examples
SELECT dbms_utility.make_data_block_address(4, 6)
FROM dual;

DATA_BLOCK_ADDRESS_BLOCK Function Get the block number part of a data block address.
Syntax
DBMS_UTILITY.DATA_BLOCK_ADDRESS_BLOCK (
   dba NUMBER)
  RETURN NUMBER;
Code examples
SELECT file_name, file_id
FROM dba_data_files;

SELECT dbms_utility.data_block_address_file(16777222)
FROM dual;

Friday, November 13, 2009

Setting default browser from Control Panel


You can set the default browser in Windows 2000 (SP3+) Windows XP (SP1+) and Windows Vista using the "Set Program Access and Defaults" feature (renamed "Set Program Access and Computer Defaults" in Windows Vista).

Based on the operating system you can get the Set Program Access and Defaults option in the following way.

On Windows 2000: "Start -> Control Panel -> Add or Remove Programs -> Set Program Access and Defaults"

On Windows XP: "Start -> Control Panel -> Add or Remove Programs -> Set Program Access and Defaults -> Custom"

On Windows Vista: "Start -> Default Programs -> Set Program Access and Computer Defaults -> Custom"

Expand the section and under "Choose a default Web browser" select the radio button as you want as default browser and then select ok.

Wednesday, November 11, 2009

Size Of SGA

Size Of SGA =
(DB_BLOCK_SIZE × BD_BLOCK_BUFFERS) +
LOG_BUFFER + SHARED_POLL_SIZE + JAVA_POLL_SIZE

To approximate size of the SGA (Shared Global Area), use following formula:
DB_CACHE_SIZE + DB_KEEP_CACHE_SIZE + DB_RECYCLE_CACHE_SIZE + DB_nk_CACHE_SIZE +
SHARED_POOL_SIZE + LARGE_POOL_SIZE + JAVA_POOL_SIZE + LOG_BUFFERS + 1MB

NOTE: ADD IN EACH DB_nk_CACHE_SIZE. THERE CAN BE UP TO 4
DB_nk_CACHE_SIZE (2, 4, 8, 16, 32k) DEFINED. ONE OF THE BLOCK SIZES IS
THE DEFAULT BLOCK SIZE AND ITS CACHE SIZE IS DEFINED BY DB_CACHE_SIZE.

Fixed portion: The size of the fixed portion is constant for a release and a plattform of Oracle, that is, it cannot be changed through any means such as altering the initialization parameters

Variable portion: The variable portion is called variable because its size (measured in bytes) can be changed. The variable portion consists of:

Large pool (optional) Provides working space for rman (although rman will also work without large pool).

Shared pool The shared pool is used for objects that are shared among all users. For example: table definitions, PL/SQL definitions, cursors and so on.The shared pool can further be subdivided into:

  • Control structures

  • Character sets

  • Dictionary cache


The dictionary cache stores parts of the data dictionary because Oracle has to query the data dictionary very often as it is fundamental to the functioning of Oracle.

  • Library cache


The library cache is further divided into

  • Shared SQL Area,

  • PL/SQL Procedures and

  • Control Structures (Latches and Locks).


The size of the Shared Pool is essentially governed by the initialization parameter shared_pool_size (although shared_pool_size is usually smaller than the size of the shared pool, see here) and db_block_buffers (which plays a role for this size because the database buffer cache must be administered.)

v$db_object_cache displays objects (=tables, indexes, clusters, synonym definitions, PL/SQL procedures/packages and triggers) that are cached in the library cache.

The size for the variable portion is roughly equal to the result of the following statement:
select   sum(bytes)
from     v$sgastat
where    pool in ('shared pool', 'java pool', 'large pool');



Redo log buffer Redo Buffers is roughly equal to the parameter log_buffer.

Database buffer cache It's size is equal to db_block_size * db_block_buffers.

(Note: db_block_buffers is deprecated as of 9i, so if the init parameter db_cache_size) is set, the buffer cache's size will be set according to this value.

UGA If the instance is running in MTS mode, there'se also a UGA: user global area Showing information about the SGA You can use v$sga to show the amount of these sizes or alternatively use SHOW SGA in sql*plus.

The following initialization parameters affect the size of the SGA:

  • db_block_buffers

  • db_block_size

  • db_cache_size

  • db_keep_cache_size

  • db_recycle_cache_size

  • java_pool_size

  • large_pool_size

  • log_buffer

  • shared_pool_size

  • streams_pool_size




Limiting the size of the SGA for a user: The amount of SGA that a user can use can be limitted through profiles. Use the private_sga option in the create profile statement.

Dynamic SGA : Dynamic SGA allows to change the size of the buffer cache, the large pool, the shared pool and the process private memory on the fly, that is without shutting down the instance.





Granule size The granule size of the components can be found out with v$sga_dynamic_components.

Peeking into SGA The x$ tables are an sql interface to the SGA and allow to peek into the SGA.

Shared server vs dedicated server The request and response queues and other parts that are found in the pga as dedicated server are found in the sga when the server is a shared server.

Protecting data structures As the SGA is, after all, a shared area, and more than one process can perform read and write operations on the SGA, Oracle has to make sure that those operations don't get in their ways. This is ensured with locks and latches.

Locking SGA into memory On platform that support it, the init parameter lock_sga can be set to true, which will lock the entire SGA into physical memory.

(Source www.adp-gmbh.ch)

Automate the Sizing of SGA in Oracle 10g


SGA _TARGET provides the following:

  • Single parameter for total SGA size

  • Automatically sizes SGA components

  • Memory is transferred to where most needed

  • Uses workload information

  • Uses internal advisory predictions

  • STATISTICS_LEVEL must be set to TYPICAL


Enable SGA_TARGET


SQL> show parameter sga_target

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
sga_target                           big integer 0

SQL> show parameter sga_max_size

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
sga_max_size                         big integer 600M

As we can see out automatic SGA tuning is not enabled so we can enable it by setting the SGA_TARGET parameter value.
SQL> alter system set sga_target=500m;
System altered.
SQL> show parameter sga_target

NAME                                 TYPE        VALUE
------------------------------------ ----------- -------
sga_target                           big integer 500M

Resize SGA_TARGET



  • SGA_TARGET is dynamic

  • Can be increased till SGA_MAX_SIZE

  • Can be reduced till some component reaches minimum size

  • Change in value of SGA_TARGET affects only automatically sized components


SQL> show parameter sga_max_size
NAME                                 TYPE        VALUE
------------------------------------ ----------- -----------
sga_max_size                         big integer 600M

SQL> show parameter sga_target
NAME                                 TYPE        VALUE
------------------------------------ ----------- -----------
sga_target                           big integer 500M

WE can resize it to only 600m if we will try to increase it from 600m we will get error.
SQL> alter system set sga_target=605m;
alter system set sga_target=605m *
ERROR at line 1:
ORA-02097: parameter cannot be modified because specified value is invalid
ORA-00823: Specified value of sga_target greater than sga_max_size

For that we must first increase our SGA_MAX_SIZE parameter value.But we must restart out instance because its STATIC parameter.
SQL> alter system set sga_max_size=500 scope=spfile;
System altered.
or
SQL> ALTER SYSTEM SET sga_max_size='524288000'scope=SPFILE  --sga_max_size set to 500MB
System altered.
SQL> startup force
ORACLE instance started.
Total System Global Area 1000189952 bytes
Fixed Size                  1337492 bytes
Variable Size             624953196 bytes
Database Buffers          369098752 bytes
Redo Buffers                4800512 bytes
Database mounted.
Database opened.
SQL> show parameter sga_max_size
NAME                                 TYPE        VALUE
------------------------------------ ----------- --------
sga_max_size                         big integer 500M

SQL> alter system set sga_target=450m;
System altered.

Disable SGA_TARGET


We can Disable our automatic SGA tuning by setting the parameter SGA_TARGET to value digit 0.
SQL> alter system set sga_target=0;

System altered.

To Take SGA Information Run following query.


SQL> select NAME,BYTES/(1024*1024) as "Size In MB",RESIZEABLE  from v$sgainfo

Monday, November 9, 2009

Enabling Archive Log

Enabling the Archive Log in Oracle 10g

SQL> shutdown immediate;



SQL> startup mount exclusive;



SQL> alter database archivelog;

SQL> alter database open;

SQL> SELECT group#, thread#, sequence#, archived, status, first_time
FROM v$log;

SQL> alter system switch logfile;

SQL> SELECT group#, thread#, sequence#, archived, status, first_time
FROM v$log;

SQL> alter system switch logfile;

SQL> SELECT group#, thread#, sequence#, archived, status, first_time
FROM v$log;

SQL> SELECT dbid, name FROM v$database;