Sunday, November 29, 2009

Auditing in Oracle Database

The Oracle Server provides several auditing options. For example, you can choose to audit certain types of SQL statements, such as INSERT or UPDATE statements. You can audit statements that use specific system privileges, such as CREATE TABLE or ALTER TABLE. You can also audit the unsuccessful attempts to perform some type of action in the database, such as failed login attempts. Auditing can be limited to a specific user or group of users, or can even be limited to actions performed on a specific schema object on a "by session" or "by access" basis.

The following three types of audits are provide by Oracle
 1. Session audits (LOGON,LOGOFF etc)
2. Database action and object audits and
3. DDL(CREATE, ALTER & DROP of objects)


The three main views to see the AUDIT Information are:

  • DBA_AUDIT_TRAIL - Standard auditing only (from AUD$).

  • DBA_FGA_AUDIT_TRAIL - Fine-grained auditing only (from FGA_LOG$) [For 10g].

  • DBA_COMMON_AUDIT_TRAIL - Both standard and fine-grained auditing   [For 10g].


To enable database auditing, you must provide a value for the AUDIT_TRAIL parameter.

The initialization parameters of audit facility of Oracle


SQL> SHOW PARAMETER AUDIT

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
audit_file_dest                      string      C:\ORACLE\PRODUCT\10.2.0\ADMIN
                                                 \ORCL\ADUMP
audit_sys_operations                 boolean     FALSE
audit_trail                          string      DB

Auditing is disabled by default, but can enabled by setting the AUDIT_TRAIL static parameter, which has the following allowed values.
AUDIT_TRAIL = { none | os | db | db,extended | xml | xml,extended }

DB              Auditing is enabled. Audit records will be written to the
SYS.AUD$ table.
OS             Auditing is enabled. Audit records will be written to an
audit trail in the operating system.
db,extended     As db, but the SQL_BIND and SQL_TEXT columns are also populated.
NONE           Auditing is disabled (default).
xml-            Auditing is enabled, with all audit records stored
as XML format OS files.
xml,extended    As xml, but the SQL_BIND and SQL_TEXT columns are also populated.
TRUE           This value is supported for backward-compatibility
with versions of Oracle;it is equivalent to the DB value.
FALSE           This value is supported for backward-compatibility
with versions of Oracle;it is equivalent to the NONE value.

In Oracle 10g Release 1, db_extended was used in place of db,extended. The XML options are new to Oracle 10g Release 2.



The AUDIT_SYS_OPERATIONS static parameter enables or disables the auditing of operations issued by users connecting with SYSDBA or SYSOPER privileges, including the SYS user. All audit records are written to the OS audit trail.

The AUDIT_FILE_DEST parameter specifies the OS directory used for the audit trail when the os, xml and xml,extended options are used. It is also the location for all mandatory auditing specified by the AUDIT_SYS_OPERATIONS parameter.

Audit in SYS.AUD$ desertion Table


Set audit_trail to DB in pfile (audit_trail = DB) .

Enable auditing and direct audit records to the database audit trail


SQL> ALTER SYSTEM SET audit_trail=db SCOPE=SPFILE;

System altered.

SQL> shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.

Total System Global Area  612368384 bytes
Fixed Size                  1250452 bytes
Variable Size             230689644 bytes
Database Buffers          377487360 bytes
Redo Buffers                2940928 bytes
Database mounted.

The command to begin auditing connects (login) attempts is:
AUDIT SESSION;

AUDIT SESSION WHENEVER SUCCESSFUL;

AUDIT SESSION WHENEVER NOT SUCCESSFUL;

To view the report of Audit session run the following query.
SQL Code:  
SELECT os_username,
username,
terminal,
returncode,
TO_CHAR(timestamp,   'DD-MON-YYYY HH24:MI:SS') LOGON_TIME,
TO_CHAR(logoff_time, 'DD-MON-YYYY HH24:MI:SS') LOGOFF_TIME
FROM dba_audit_session;

Disable Session Audit


NOAUDIT SESSION;

Audit a User


AUDIT CREATE TABLE BY scott;

Disable User Audit


NOAUDIT CREATE TABLE BY scott;

Audit a User Table


It is also possible to audit SELECT, INSERT, UPDATE, and DELETE operations on specific database tables. Depending on the type of audit you wish to conduct, you can include either the BY SESSION or BY ACCESS clause in the AUDIT command. This clause is available for both object audits and system-level action audits.

It denotes whether an audit record will be written once for each session (BY SESSION) or once for each time a schema objects is accessed (BY ACCESS).
AUDIT INSERT ON scott.emp1 BY SESSION;

AUDIT INSERT ON scott.emp2 BY ACCESS;


Disable User Table Audit


NOAUDIT INSERT ON scott.emp1;



Set audit_trail to OS file destination, in pfile (audit_trail = OS)

audit_file_dest = /u01/oracle/product/10.2.0/admin/orcl/adump

Open your init.ora file and check the AUDIT_FILE_DEST parameter for the location of your operating system audit trail files.

Open the file in Unix system and If you are using Windows NT, then go to Start -> Programs -> Administrative Tools -> Event Viewer. In the menu bar of the Event Viewer, choose Log -> Application. Double click on the events listed.

To find out the name of the database action that corresponds to the numeric code of 100, query the AUDIT_ACTIONS data dictionary view.
SQL Code:
SELECT action, name
FROM audit_actions
WHERE action = 100;

Similarly, to discover the name of the privilege used to allow you to perform this database action, query the STMT_AUDIT_OPTION_MAP data dictionary view. While still logged on as user
SQL Code:
SELECT option#, name
FROM stmt_audit_option_map
WHERE option# = 5;

View Audit Trail


The audit trail is stored in the SYS.AUD$ table. Its contents can be viewed directly or via the following views:
SQL Code:
SQL> SELECT view_name
  2  FROM   dba_views
  3  WHERE  view_name LIKE 'DBA%AUDIT%'
  4  ORDER BY view_name;

VIEW_NAME
------------------------------
DBA_AUDIT_EXISTS
DBA_AUDIT_OBJECT
DBA_AUDIT_POLICIES
DBA_AUDIT_POLICY_COLUMNS
DBA_AUDIT_SESSION
DBA_AUDIT_STATEMENT
DBA_AUDIT_TRAIL
DBA_COMMON_AUDIT_TRAIL
DBA_FGA_AUDIT_TRAIL
DBA_OBJ_AUDIT_OPTS
DBA_PRIV_AUDIT_OPTS
DBA_REPAUDIT_ATTRIBUTE
DBA_REPAUDIT_COLUMN
DBA_STMT_AUDIT_OPTS

Oracle Database 11g Release 1 (11.1) Installation on Oracle Enterprise Linux 5.0

This article describes the installation of Oracle Database 11g Release 1 (11.1) on Oracle Enterprise Linux 5.0. Here I simulate the installation process based on my PC based server which has following hardware configuration:

  1. Intel 2.4 GHz x86 Processor.

  2. 80 GB SATA HDD

  3. GB physical memory


To make an easy and convenient installation process we documented installation Process in two phases. First of on we have to install Oracle Enterprise Linux Server 5.0 with required package and system parameter. After that in the second phase we simulated installation Process of Oracle 11g with respective screen shot which will help the beginner Administrator to understand their jobs easily. I hope, this article will help the novice and mid level Database/ System Administrator to understand what is the production standard installation of Oracle 11g for mid level traffic processing generally which will done by General Purpose or Transaction processing database template. Its me a great pleasure if this installation cook help someone meet their company requirement.



Part-1: Installing Oracle Enterprise Linux 5.0

Part-2: Configuring Linux for Oracle

  1. Creating the Oracle Group and User Account

  2. Creating Required Directories and Change the Owner Ship

  3. Verify Hardware Requirement

    1. Main Memory Requirements

    2. Disk Space Requirements




4. Software Requirements Checkin

1. Kernel Requirements


2. Package Requirements


5.    Configuring Kernel Parameters

6.    Configuring the oracle User's Environment

7.    Installing Oracle Database

8.    Post Instillation Task

Part-1: Installing Oracle Enterprise Linux 5.0




You may download Oracle Enterprise Linux 5.0 from oracle technology network. To download Oracle Enterprise Linux 5.0 Enterprise Edition uses the following link.

http://edelivery.oracle.com/linux

Installation Process:

  1. Boot the server using the first CD.

    • You may need to change your BIOS settings to allow booting from the CD.



  2. The boot screen appears with the boot: prompt at the bottom of the screen.

    • Select Enter to continue with a graphical install on the console.



  3. CD Found



  • Skip these options.



  1. Click on Next.

  2. What language could you like to use during the installation process.

    • Accept the default.



  3. Select the appropriate keyboard for the system Configuration

    • Accept the default. (U.S English).





  1. Disk Portioning Step



  • Select Remove all partition on Selected device and create default layout the system  and Click on Next

  • The disk on the first controller (/dev/sda) will hold all Linux software and contains the following partitions:

  • /boot partition  - 256MB

  • Swap Partition -2 GB [Set this to at least twice the amount of RAM in the system But if the Physical RAM equal to 4 GB or greater then choose swap size exactly as memory size.]

  • root (/) partition  -  19 GB This partition will be used for everything, including /usr, /tmp,  /opt, /home, and more. This approach is purely to simplify installation for the purposes of this guide. A more robust partitioning scheme would separate these directories onto separate file systems.

  • /u01 – 18 GB -   For Oracle Home Directory

  • /u02 - 18GB -   For Oracle Data Directory.

  • /var – 19 GB

  • Click on Next

  • Click on Next



  1. Required installation media



  • Three CD Required to Successful installation of Oracle Enterprise Linux.

  • If you have three disk then Click on Continue



  1. Boot Loader Configuration





    • Accept the default and Click on Next.



  1. Network Configuration

    • It is usually best to configure database servers with a static IP address. To do so, click on Edit.

    • A pop-up window appears. Uncheck the Configure using DHCP box, and enter the IP Address and NetMask for the server. Be sure that Activate on boot is checked, and click on OK.

    • Enter Static IP Address , Prefix (Net Mask) in your required IP Block

    • In the Hostname box, select manually and enter the hostname.

    • In the Miscellaneous Settings box, enter the remaining network settings.

      • Enter Geteway, Primary DNS ,  Secondary DNS

      • Click on Next





  2. Please Click into the map to chose a region

    • Select Asia/Dhaka

    • Click on Next



  3. Provide Root Password and Conform

    • Click on Next



  4. Package Installation

    • Chose Customize now and Click on Next.



  5. Package Group Selection

    • Desktop Environment

      • GEOME Desktop Environment



    • Applications

      • Editor

      • Graphical Internet

      • Text-based Internet



    • Development

      • Development Libraries

      • Development Tools



    • Server

      • Server Configuration Tools



    • Base System

      • Base

      • Administration Tools

      • System Tools

      • X Window System





  6. Click on Next.

  7. Reboot The System

  8. Welcome

    • Click on Forward

    • License  Agreement

      • Select Yes, I agree to the License Agreement  and Click on Forward



    • Firewall

      • Chose Disabled Firewall and Click on Forward

      • A Popup window will appear Click on Yes for Confirmation



    • SE Linux

    • Chose Disabled to SELinux Settings.

    • Click on Forward

    • A Popup window will appear Click on Yes.

    • Kdump

      • Accept Default and Click on Forward



    • Data and Time

      • Set the Date Time and Click on Forward



    • Create User

      • Skip this options and Click on Forward









    • Sound Card

      • You may Test your sound card by playing a Test Sound

      • Click on Forward



    • Additional CD

      • Skip this options and Click on Finish





  1. Click on OK button to reboot the system


Part-2: Configuring Linux for Oracle


You may download Oracle 11g from oracle technology network. To download Oracle Database 11g Release 1 (11.1.0.6.0)
Standard Edition, Standard Edition One, and Enterprise Edition use the following link.

http://www.oracle.com/technology/software/products/database/oracle11g/111060_linuxsoft.html

1. Creating the Oracle Group and User Account

  • Use the following command to add The Oracle Inventory group (oinstall) and OSDBS (dba) Group:


        [root@testdb ~]#  groupadd oinstall
        [root@testdb ~]#  groupadd dba


  • Use the following command to add a user whish is The Oracle software owner (oracle)


        [root@testdb ~]# useradd oracle


  • Use the following command to specify oinstall as the primary group and dba as the secondary group for oracle User.


        [root@testdb ~]# usermod -g oinstall -G dba oracle


  • Finaly use the following command to Check the Oracle user and user group:


        [root@testdb ~]# id oracle
        uid=500(oracle) gid=500(oinstall) groups=500(oinstall),501(dba)


  • Use the following command to set the password of the oracle user:


        [root@testdb ~]# passwd oracle
        Changing password for user oracle.
        New UNIX password:
        Retype new UNIX password:
        passwd:all authentication tokens updated successfully.


  • Use the Following Command determine whether the An unprivileged user (nobody) user exists or Not :


        [root@testdb ~]# id nobody
        uid=99(nobody) gid=99(nobody) groups=99(nobody)

If this command displays information about the nobody user, then you do not

need to create the nobody user.

  • If the nobody user does not exist, then enter the following command to create it:


        # useradd nobody

2. Creating Required Directories and Change the Owner Ship



  • Create directories with names similar to the following, and specify the correct owner, group, and permissions for them:


1. The Oracle base directory (For Oracle Home directory)

2. An optional Oracle data file directory

  • Oracle Recommand that the base directory and data file directory will be different mount point. if you do not create the mount point during the operation system installation then use the following command to create a directory.


mkdir -p /mount_point/app/

For example :
        [root@testdb ~]# mkdir -p /u01/app


  • To set the appropriate owner, group use the following command :


        [root@testdb ~]# chown -R oracle.oinstall /u01
        [root@testdb ~]# chown -R oracle.oinstall /u02


  • To permissions on the directory use the following command :


        [root@testdb ~]# chmod -R 775 /u01
        [root@testdb ~]# chmod -R 775 /u02

3. Verify Hardware Requirements



  • Main Memory Requirements

  • Disk Space Requirements


Main Memory Requirements

  • At least 1 GB of Physical RAM Requirement , To determine the physical RAM size, use the following command:


        [root@testdb ~]# cat /proc/meminfo | grep Mem
        MemTotal:      1018368 kB
        MemFree:         43884 kB


  • Swap Spase


For 512 MB RAM,Swap Space Required Double the size of RAM

For 1024 MB RAM, Swap Space Required 1.5 times the size of RAM

  • To determine the physical RAM size, use the following command:


        [root@testdb ~]# cat /proc/meminfo | grep SwapTotal
        SwapTotal:     2096472 kB



Disk Space Requirements

  • Oracle Recommend For Enterprise Edition you may need 3.47 GB, Enterprise Edition require 1.5 GB of disk Space for Data file. To determine the amount of free disk space in MB on the system, use the following command :


[root@testdb ~]# df -m /u01/
Filesystem           1M-blocks      Used Available Use% Mounted on
/dev/hda7                17439      3624     12915  22% /u01  

[root@testdb ~]# df -m /u02/
Filesystem           1M-blocks      Used Available Use% Mounted on
/dev/hda6                17439      1777     14763  11% /u02

[NB: /u01 is use for Oracle Software and /u01 is use for Oracle Database file]

4. Software Requirements Checking




Kernel Requirements

  • To determine whether the required kernel is installed, use the following command. A sample output displayed by running this command on a Oracle Enterprise Linux 5.0 system:


        [root@testdb ~]# uname –r
        2.6.18-8.el5

Package Requirements

  • The following or later version of packages for Oracle Enterprise Linux 5.0


        1. binutils-2.17.50.0.6-2.el5                 Disk-01
        2. compat-libstdc++-33-3.2.3-61               Disk-02
        3. elfutils-libelf-0.125-3.el5        Disk-02
        4. elfutils-libelf-devel-0.125        Disk-02
        5. glibc-2.5-12                       Disk-02
        6. glibc-common-2.5-12                        Disk-01
        7. glibc-devel-2.5-12                         Disk-02
        8. gcc-4.1.1-52                       Disk-02
        9. gcc-c++-4.1.1-52                           Disk-02
        10. libaio-0.3.106                            Disk-01
        11. libaio-devel-0.3.106                      Disk-02
        12. libgcc-4.1.1-52                           Disk-01
        13. libstdc++-4.1.1                           Disk-01
        14. libstdc++-devel-4.1.1-52.e15              Disk-02
        15. make-3.81-1.1                             Disk-01
        16. sysstat-7.0.0                             Disk-03
        17. unixODBC-2.2.11                           Disk-02
        18. unixODBC-devel-2.2.11                     Disk-02


  • To determine whether the required packages are installed, use commands similar to the following:


        # rpm -qa | grep <package_name>

        Example:
        [root@testdb ~]# rpm -qa | grep binutils
        binutils-2.17.50.0.6-2.el5


  • To Find the Packege in the CD-ROM(Oracle Entriprece Linux) use the Commands similer


        # ls -la /media/cdrecorder/Server | grep <package_name>


  • To install, use commands similar to the following:


        # rpm -ivh <package_name>


5. Configuring Kernel Parameters


[root@testdb ~]# sysctl -a | grep sem
kernel.sem = 250        32000   100     128

[root@testdb ~]# sysctl -a | grep shm
vm.hugetlb_shm_group = 0
kernel.shmmni = 4096
kernel.shmall = 268435456
kernel.shmmax = 4294967295

[root@testdb ~]# sysctl -a | grep file-max
fs.file-max = 6553600

[root@testdb ~]# sysctl -a | grep ip_local_port_range
net.ipv4.ip_local_port_range = 1024     65000

[root@testdb ~]# sysctl -a | grep rmem_
net.core.rmem_default = 4194304
net.core.rmem_max = 4194304

[root@testdb ~]# sysctl -a | grep wmem_
net.core.wmem_default = 262144
net.core.wmem_max = 262144
vm.lowmem_reserve_ratio = 256   256     32


  • Using any text editor, create or edit the /etc/sysctl.conf file, and add or edit lines similar to the following:


kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
net.core.rmem_default = 4194304
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 262144

· Enter the following command to change the current values of the kernel parameters:
   [root@testdb ~]# /sbin/sysctl –p

Review the output from this command to verify that the values are correct
 N.B: For Safety to make sure the change effect you may restart the system.

6. Configuring the oracle User's Environment


Oracle Enterprise Linux 5.0 user environment is preconfigured. So skip this option.

If you are not disabling the firewall during the setup of Oracle Enterprise Linux 5.0 then follow the following step to disable in GUI as root user.
For Oracle Enterprise Linux System -> Administration -> Security Level and Firewall

| Firewall Options -> Firewall: Disable

| SE Linux -> SE Linux Settings: Disable

7. Installing Oracle Database



  1. 1.Login in Oracle User in X Window System.



[root@testdb ~]$ hostname
testdb.dnsgroup.net
[root@testdb ~]$ xhost + testdb.dnsgroup.net
testdb.dnsgroup.net bigen added to access control list
[root@testdb ~]$ xterm

To Unzip the unzip the zip file use the following Command
# unzip linux_11gR1_database.zip

After unzip to run the Oracle Universal Installer use the following command
    [oracle@testdb database]$./runInstaller


  1. 2. Select a Product to Install




  1. Select Advanced Installation

  2. Click on Next




  1. 3. Specify Inventory Directory and Credentials.




  1. Inventory Directory: /u01/app/oraInventory

  2. Operating System group name:  oinstall

  3. Click on Next





  1. 4. Select Installation Type



  • Select Enterprise Edition (3.18 GB)

  • Click on Next



  1. 5. Loading Product Information



  • Oracle Base : /u01/app/oracle

  • Software Location


Name : OraDb11g_home

Path : /u01/app/oracle/db11g

  • Click on Next




  1. 6. Product Specific Prerequisite Checks



  • All the checks should pass without difficulty. If one or more checks fail, correct the problem before proceeding.

  • Click on Retry to Recheck.

  • Click on Next


[NB. If checking pass then Status Will be Succeeded]

  1. 7. Select Configuration Option



  • Select Create Database Option.

  • Click on Next.



  1. 8. Select Database Configuration



  • Select General Purpose / Transaction Processing.

  • Click on Next.



  1. 9. Specify Database Configuration Options



  • Global Database Name : testcpdb.dnsgroup.net

  • SID : testcpdb

  • Click on Next




10. Specify Database Config Details (Memory)

  • Chose Enable Automatic Memory Management.

  • Click on Next.


[NB. Configure your Memory according to your requirements.]



11. Specify Database Config Details (Character Sets)

  • Choose from the list of Character Set: Unicode Standard UTF-8 AL32UTF8.

  • Click on Next


[NB. You Can Choose Character Set according to your requirements]

12. Specify Database Config Details (Security)

  • Accept Default

  • Click on Nest.


[N.B: Oracle recommends the default settings]

13. Specify Database Config Details (Sample Schemas)

  • Accept Default

  • Click on Nest.




14. Select Database Management Options.

  • Select Use Database Control for Database Management.

  • Click on Next.


15. Specify Database Storage Option

  • Select File System

  • Specify Database file location : /u02/oradata

  • Click on Next.




16. Specify Backup and Recovery Options

  • Select Do not enable Automated backups

  • Clock on Next.


17. Specify Database Schema Passwords

  • Select Use the same password for all the accounts

  • Enter the Password and Confirm.

  • Clock on Next.


18. Privileged Operating System Groups

  • Database Administrator (OSDBA) Group      : oinstall

  • Database Operator (OSOPER) Group          : oinstall

  • ASM administrator (OSASM) Group            : oinstall

  • Click on Next.






19. Oracle Configuration Manager Registration

  • If you have Metalink Account then you can Registration your database, otherwise skip this option.

  • Click on Next.


20. Summary

  • A summary of the products being installed is presented.

  • Click on Install.


21. Install

  • The Installation process of Oracle 11g 11.1.0.6.0 is running automatically.

  • After Finishing 100% Configuration assistants will appear.


22. Configuration assistants

  • The Oracle Net Configuration Assistant and Oracle Database Configuration assistant will run automatically.


23. Database Configuration Assistant

  • Copying database file, Creating and starting Oracle Instance, Completing Database creation process will run automatically.


24. Database Configuration Assistant

  • This window Provide you some information about your database.

  • You can Change user account password and unlock by Click on Password Manager.

  • Click on OK.


25. Execute Configuration Scripts

  • Execute orainstRoot.sh and root.sh as root user.

  • To Switch root user Open a Terminal and Type su root

  • Click on OK.


26. End of Instillation

  • Make note of the URLs presented in the summary, and click on Exit when ready.




27. Exit

  • Click on Yes to Exit.


8. Post Installation Task



  1. Edit the /etc/oratab file setting the restart flag for each instance to 'Y'


[root@testdb ~]# vi /etc/oratab
testcpdb:/u01/app/oracle/db11g:Y



  1. Now you have to write a Script to Automatic Startup and Shutdown Oracle Database.


[root@testdb ~]# su – oracle

[Let Consider that dbora.sh is a script to Automatic Startup and Shutdown the Database in oracle home directory which will be written by the reader for automation of the Oracle Database and other processes relating to the Oracle 11g.]

for more detail please visits http://tamimdba.wordpress.com/category/oracle10g/dbora-script-for-rhel

  1. Add the following code in to the oracle bash_profile


[oracle@testdb ~]$ vi /home/oracle/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=/u01/app/oracle/db11g/
export ORACLE_SID= testcpdb
export DBIN=$ORACLE_HOME/bin

PATH=$PATH:$HOME/bin:$ORACLE_HOME:$DBIN

export PATH

4. Add the following code in to the /etc/hosts file.
127.0.0.1       localhost.localdomain   localhost
172.168.0.95    testdb.dnsgroup.net     testdb

[root@testdb ~]# cat /etc/hosts
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1       localhost.localdomain   localhost
172.168.0.95    testdb.dnsgroup.net     testdb

9. Oracle Enterprise Manager



  • To Start the Oracle Enterprise Management Server use the following command.

  • To Stop the Oracle Enterprise Management Server use the following command.


[root@testdb ~]# emctl start dbconsole
[root@testdb ~]# emctl stop dbconsole

10. Oracle SQL Developer


To Run Oracle SQL Developer use the following command as Oracle user in X Window System.
[oracle@testdb ~]$ cd /u01/app/oracle/db11g/sqldeveloper/

[oracle@testdb sqldeveloper]$ sh sqldeveloper.sh



For Oracle 10g


Click here 

Friday, November 20, 2009

Managing Tablespace

What is an Oracle Tablespace?


A tablespace is a logical storage unit – multiple application objects (e.g. tables) can be stored in one tablespace. A tablespace can be online or offline (not accessible), and can contain one or more datafiles, each of which can be online or offline.

There is no relationship between a tablespace and a schema. Objects in the same schema can be in different tablespaces, and a tablespace can hold objects from different schemas.

Locally Managed Tablespaces (LMT’s) : When creating an LMT, the storage parameters NEXT, PCTINCREASE, MINEXTENTS, MAXEXTENTS, and DEFAULT STORAGE are not required (invalid syntax). An LMT can have either uniform or variable extent sizes. Variable extents are determined automatically by the system. When you create the tablespace, the UNIFORM or AUTOALLOCATE (system-managed) clause specifies the type of allocation.

For uniform extents, you can specify an extent size or use the default size, which is 1 MB. Temporary tablespaces that manage their extents locally can only use this type of allocation.

For system-managed extents, you can specify the size of the initial extent and Oracle determines the optimal size of additional extents, with a minimum extent size of 64 KB. This is the default for permanent tablespaces.

The following statement creates a locally managed tablespace named test_ts and specifies AUTOALLOCATE:
SQL Code :
CREATE TABLESPACE test1_ts DATAFILE '/u02/oracle/data/test1_ts.dbf' SIZE 50M
    EXTENT MANAGEMENT LOCAL AUTOALLOCATE;
Automatic segment-space management
SQL Code :
CREATE TABLESPACE test2_ts DATAFILE '/u02/oracle/data/test2_ts.dbf' SIZE 50M
    EXTENT MANAGEMENT LOCAL
    SEGMENT SPACE MANAGEMENT AUTO;

Dictionary Managed Tablespaces: A tablespace that uses the data dictionary to manage its extents has incremental extent sizes, which are determined by the storage parameters INITIAL, NEXT, and PCTINCREASE. These can be adjusted to control the extent sizes. When additional space is needed, the NEXT and PCTINCREASE parameters determine the sizes of new extents.

As an example, the following statement creates the tablespace tbsa, with the following characteristics:

The data of the new tablespace is contained in a single datafile, 50M in size.

The tablespace is explicitly created as a dictionary-managed tablespace by specifying EXTENT MANAGEMENT DICTIONARY.

The default storage parameters for any segments created in this tablespace are specified.

The following statement creates the tablespace tbsb:
SQL Code :
CREATE TABLESPACE tbsb
    DATAFILE '/u02/oracle/data/tb01.dbf' SIZE 50M
    EXTENT MANAGEMENT DICTIONARY
    DEFAULT STORAGE (
        INITIAL 50K
        NEXT 50K
        MINEXTENTS 2
        MAXEXTENTS 50
        PCTINCREASE 0);

Temporary tablespace: Locally managed temporary tablespaces have temporary datafiles (tempfiles), which are similar to ordinary datafiles except that:

  • You cannot create a tempfile with the ALTER DATABASE statement.

  • You cannot rename a tempfile or set it to read-only.

  • Tempfiles are always set to NOLOGGING mode.

  • When you create or resize tempfiles, they are not always guaranteed allocation of disk space for the file size specified. On certain file systems (for example, UNIX) disk blocks are allocated not at file creation or resizing, but before the blocks are accessed.


Create Temporary Tablespace
SQL Code :
CREATE TEMPORARY TABLESPACE test_temp TEMPFILE '/u02/oracle/data/test_temp01.dbf'
     SIZE 20M REUSE
   EXTENT MANAGEMENT LOCAL UNIFORM SIZE 16M;

System Tablespace: Every Oracle database contains a tablespace named SYSTEM, which Oracle creates automatically when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. All data stored on behalf of stored PL/SQL program units (procedures, functions, packages, and triggers) resides in the SYSTEM tablespace.

The SYSTEM tablespace is always online when the database is open.

Data Dictionary Objects to get information about tablespace
Tablespaces                    ts$, dba_tablespaces ,
user_tablespaces, Tablespace

Quotas               tsq$, dba_ts_quotas, user_ts_quotas

Data Files         dba_data_files, v_$backup_datafile,
v_$datafile,
v_$datafile_copy, v_$datafile_header

Free Space       dba_free_space

Segments         dba_segments, v_$segment_statistics

Extents             dba_extents

Blocks               v_$database_block_corruption

Groups             dba_tablespace_groups

SYSAUX Tablespace    v_$sysaux_occupants

Temp Tablespace      dba_temp_files

Undo Tablespace      dba_rollback_segs, dba_undo_extents,
v_$rollstat, v_$undostat

Transportable Tablespaces      transport_set_violations

Dictionary Management          fet$, uet$

Monitoring Tablespace

To list the names and default storage parameters of all tablespaces in a database
SQL Code:
SELECT TABLESPACE_NAME "TABLESPACE",
   INITIAL_EXTENT "INITIAL_EXT",
   NEXT_EXTENT "NEXT_EXT",
   MIN_EXTENTS "MIN_EXT",
   MAX_EXTENTS "MAX_EXT",
   PCT_INCREASE
FROM DBA_TABLESPACES;
----------------------------------------------------------------------
SQL Code:
SELECT tablespace_name,
       block_size,
       status,
       contents,
       retention,
       extent_management,
       allocation_type,
       plugged_in,
       segment_space_management
FROM dba_tablespaces;
----------------------------------------------------------------------
SQL Code:
SELECT tablespace_name,
ROUND(SUM(total_mb)-SUM(free_mb)) CUR_USE_MB,
ROUND(SUM(total_mb)) CUR_SZ_MB,
ROUND((SUM(total_mb)-SUM(free_mb))/SUM(total_mb)*100) CUR_PCT_FULL,
ROUND(SUM(max_mb) - (SUM(total_mb)-SUM(free_mb))) FREE_SPACE_MB,
ROUND(SUM(max_mb)) MAX_SZ_MB, ROUND((SUM(total_mb)-SUM(free_mb))/SUM(max_mb)*100) PCT_FULL
FROM (
  SELECT tablespace_name, SUM(bytes)/1024/1024 FREE_MB,
  0 TOTAL_MB, 0 MAX_MB
  FROM dba_free_space
  GROUP BY tablespace_name
  UNION
  SELECT tablespace_name, 0 CURRENT_MB,
  SUM(bytes)/1024/1024 TOTAL_MB,
  SUM(DECODE(maxbytes,0,bytes, maxbytes))/1024/1024 MAX_MB
FROM dba_data_files
  GROUP BY tablespace_name)
GROUP BY tablespace_name
----------------------------------------------------------------------
SQL Code:
SELECT  dd.tablespace_name tablespace_name,
        dd.file_name file_name,
        dd.bytes/1024 TABLESPACE_KB,
        SUM(fs.bytes)/1024 KBYTES_FREE,
        MAX(fs.bytes)/1024 NEXT_FREE
FROM    sys.dba_free_space fs, sys.dba_data_files dd
WHERE   dd.tablespace_name = fs.tablespace_name
        AND dd.file_id = fs.file_id
GROUP BY dd.tablespace_name, dd.file_name, dd.bytes/1024
ORDER BY dd.tablespace_name, dd.file_name;
----------------------------------------------------------------------
SQL Code:
SELECT file_name, tablespace_name, ROUND(bytes/1024000) MB
FROM dba_data_files
ORDER BY 1;

Displaying Statistics for Free Space (Extents) of Each Tablespace
SQL Code:
SELECT TABLESPACE_NAME "TABLESPACE", FILE_ID,
   COUNT(*)    "PIECES",
   MAX(blocks) "MAXIMUM",
   MIN(blocks) "MINIMUM",
   AVG(blocks) "AVERAGE",
   SUM(blocks) "TOTAL"
   FROM DBA_FREE_SPACE
GROUP BY TABLESPACE_NAME, FILE_ID;

To list the names, sizes, and associated tablespaces of a database
SQL Code:
SELECT  FILE_NAME, BLOCKS, TABLESPACE_NAME
   FROM DBA_DATA_FILES;

Monitoring Free Space of a database
SQL Code:
SELECT  BLOCK_ID, BYTES, BLOCKS
     FROM  DBA_FREE_SPACE
     WHERE TABLESPACE_NAME = 'USERS'
     ORDER BY BLOCK_ID;

BLOCK_ID               BYTES                  BLOCKS               
---------------------- ---------------------- ----------------------
417                    1835008                224

Coalescing Free Space
Syntax:
ALTER TABLESPACE <tablespace name> COALESCE;

Availability of Datafiles or Tempfiles
Syntax: 
  ALTER TABLESPACE ... DATAFILE {ONLINE|OFFLINE}
  ALTER TABLESPACE ... TEMPFILE {ONLINE|OFFLINE}
SQL Code:
ALTER TABLESPACE users OFFLINE NORMAL;

Dropping Tablespace

The following statement drops the users tablespace, including the segments in the tablespace
SQL Code:
DROP TABLESPACE users INCLUDING CONTENTS;

The following statement drops the USER tablespace and its associated datafiles:
SQL Code:
DROP TABLESPACE users INCLUDING CONTENTS AND DATAFILES;

Get SQL Code of a tablespace
SQL Code: 
SELECT dbms_metadata.get_ddl('TABLESPACE', 'USERS')
FROM dual;

To see the default tablestace information
SQL Code: 
SELECT *
FROM props$
WHERE name LIKE '%DEF%'

TABLESPACE INFORMATION

Tablespace Name – Name of the tablespace

Initial Extent – Default initial extent size

Next Extent – Default incremental extent size

Min Extents – Default minimum number of extents

Max Extents – Default maximum number of extents

PCT Increase – Default percent increase for extent size

Status – Tablespace status: ONLINE, OFFLINE, or INVALID (tablespace has been dropped)

Contents – Type of tablespace. This column will have ‘TEMPORARY’ (v7.3+) for dedicated temporary tablespaces, and ‘PERMANENT’ for  tablespaces that can store both temporary sort segments and permanent objects.
 
SQL Code:
Select TABLESPACE_NAME,
     INITIAL_EXTENT,
     NEXT_EXTENT,
     MIN_EXTENTS,
     MAX_EXTENTS,
     PCT_INCREASE,
     STATUS,
     CONTENTS
from  dba_tablespaces
order by TABLESPACE_NAME

Coalesced Exts

Tablespace Name – Name of tablespace

Total Extents – Total number of free extents in tablespace

Extents Coalesced – Total number of coalesced free extents in tablespace

% Extents Coalesced – Percentage of coalesced free extents in tablespace

Total Bytes – Total number of free bytes in tablespace

Bytes Coalesced – Total number of coalesced free bytes in tablespace

Total Blocks – Total number of free oracle blocks in tablespace

Blocks Coalesced – Total number of coalesced free Oracle blocks in tablespace

% Blocks Coalesced – Percentage of coalesced free Oracle blocks in tablespace
SQL Code:
Select TABLESPACE_NAME,
     TOTAL_EXTENTS,
     EXTENTS_COALESCED,
     PERCENT_EXTENTS_COALESCED,
     TOTAL_BYTES,
     BYTES_COALESCED,
     TOTAL_BLOCKS,
     BLOCKS_COALESCED,
     PERCENT_BLOCKS_COALESCED
from  dba_free_space_coalesced
order by TABLESPACE_NAME

Usage

Tablespace Name – Name of the tablespace

Bytes Used – Size of the file in bytes

Bytes Free – Size of free space in bytes

Largest – Largest free space in bytes

Percent Used – Percentage of tablespace that is being used – Careful if it is more than 85%
 
SQL Code:
Select a.TABLESPACE_NAME,
     a.BYTES bytes_used,
     b.BYTES bytes_free,
     b.largest,
     round(((a.BYTES-b.BYTES)/a.BYTES)*100,2) percent_used
from      
     (
            select  TABLESPACE_NAME,
                    sum(BYTES) BYTES
            from    dba_data_files
            group   by TABLESPACE_NAME
     )
     a,
     (
            select  TABLESPACE_NAME,
                    sum(BYTES) BYTES ,
                    max(BYTES) largest
            from    dba_free_space
            group   by TABLESPACE_NAME
     )
     b
where  a.TABLESPACE_NAME=b.TABLESPACE_NAME
order  by ((a.BYTES-b.BYTES)/a.BYTES) desc

Users Default (SYSTEM)

Username – Name of the user

Created – User creation date

Profile – Name of resource profile assigned to the user

Default Tablespace – Default tablespace for data objects

Temporary Tablespace – Default tablespace for temporary objects

Only SYS, SYSTEM and possibly DBSNMP should have their default tablespace set to SYSTEM.
 
SQL Code:
select USERNAME,
     CREATED,
     PROFILE,
     DEFAULT_TABLESPACE,
     TEMPORARY_TABLESPACE
from dba_users
order by USERNAME

Objects in SYSTEM Tablespac
Owner – Owner of the object
Object Name – Name of object
Object Type – Type of object
Tablespace – Tablespace name
Size – Size (bytes) of object
Any user (other than SYS, SYSTEM) should have their objects moved out of the SYSTEM tablespace

SQL Code:
Select OWNER,
     SEGMENT_NAME,
     SEGMENT_TYPE,
     TABLESPACE_NAME,
     BYTES
from  dba_segments
where TABLESPACE_NAME = 'SYSTEM'
and   OWNER not in ('SYS','SYSTEM')
order  by OWNER, SEGMENT_NAME

Freespace/Largest Ext

Tablespace – Name of the tablespace

Total Free Space – Total amount (bytes) of freespace in the tablespace

Largest Free Extent – Largest free extent (bytes) in the tablespace
SQL Code:
select TABLESPACE_NAME,
       sum(BYTES) Total_free_space,
       max(BYTES) largest_free_extent
from   dba_free_space
group  by TABLESPACE_NAME

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