Tuesday, September 13, 2011

Startup Restrict Mode


Sometimes it is necessary to do work on a database without any other users being logged in. It is possible to restrict the database session in such a case. When the database starts in restricted mode only users with restricted session privileges can get access to the database even though it is technically in open mode.

Enable / Disable Restricted Session

SQL> startup restrict 
ORACLE instance started.
Total System Global Area 504366872 bytes
Fixed Size 743192 bytes
Variable Size 285212672 bytes
Database Buffers 218103808 bytes
Redo Buffers 307200 bytes
Database mounted.
Database opened.

Startup the database in restricted mode

The alter system command can be used to put the database in and out of restricted session once it is open:

SQL> alter system enable restricted session;
system altered

SQL> alter system disable restricted session;
system altered

NOTE:   Find and disconnect users connected during restricted session. Any users connected to the database when restricted session is enabled will remain connected and need to be manually disconnected

To check which users are connected to the database run the following:

SQL> SELECT username, logon_time, process from v$session;
USERNAME LOGON_TIM PROCESS
----------------- ------------ -------------------
SYS      17-NOV-10       1310796
              17-NOV-10      1343899


By querying the process id you can then issue a kill -9 <process_id> at the operating system level to disconnect the connected user. The blank usernames in v$session refer to background database processes.

Check if database in restricted mode, If you are unsure whether the database is in restricted session or not you can run the following query to check:

SQL> SELECT logins from v$instance;

LOGINS
----------
RESTRICTED

Tuesday, September 6, 2011

ORA-01940: Cannot drop user that is currently connected

SQL> drop user username cascade;
drop user username cascade
*
ERROR at line 1:
ORA-01940: cannot drop a user that is currently connected

Solution 

Make sure the user is logged out, then re-execute the command.

If you are permitted to kill the session of that user then find out the connected user sid and serial# by,

SQL> select sid, serial# from v$session where username = 'USERNAME';

   SID    SERIAL#                
---------- ----------
   268       1268
   315       1223

If RAC use GV$SESSION view to get instance#

NOTE:   Before killing session you may wish to lock the account for further connection attempts. This is extremely necessary to drop users who automatically establish session like to drop an application user or to drop a user who performs batch jobs.

SQL> Alter user username account lock;

Now kill the connected session.

SQL> alter system kill session '268,1268';           (use @instance# if RAC db)
       System altered

SQL> alter system kill session '315,1223';
      System altered

And then drop the user.


SQL> drop user username cascade;
          User dropped


Moving a table from one tablespace to another


There are couple of ways in which a table can be moved to a different tablespace:
   a) One of them is to perform export/import 
   b) Another is to use ‘ALTER TABLE’ command with ‘MOVE tablespace’ clause

If you move a table from one tablespace to another, you need to REBUILD the Related indexes if those indexes are on same tablespace

      1)  Check indexes for a table

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
Ind_name            tab_name            valid

2)     Check the tablespace in which our table is located

SQL> select tablespace_name,table_name from user_tables where table_name=’TAB_NAME’;


3)    Now moving to another tablesapce

SQL>  ALTER TABLE tab_name MOVE TABLESPACE new_tablespace;


4)    Now check the status of the index again

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
Users                 tab_name             Unusable
                                                                              

5)    Rebuild the index in order to make the index valid

SQL>  ALTER INDEX ind_name REBUILD;
 index altered


6)    Check the status of the index again

SQL> SELECT INDEX_NAME, TABLE_NAME,STATUS FROM ALL_INDEXES WHERE TABLE_NAME = ‘ tab_name’;

Index_name       table_name           status
-----------------       ------------------       ----------
ind_name               tab_name           valid

Friday, September 2, 2011

Manually uninstalling oracle



Windows

In the past I've had many problems uninstalling all Oracle products from Windows systems. Here's my last resort method:
Uninstall all Oracle components using the Oracle Universal Installer (OUI).

Run regedit.exe and delete the HKEY_LOCAL_MACHINE/SOFTWARE/ORACLE key. This contains registry entires for all Oracle products.

Delete any references to Oracle services left behind in the following part of the registry:

HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Ora*

It should be pretty obvious which ones relate to Oracle.
Reboot your machine.

Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
Delete the "C:\Program Files\Oracle" directory.
Empty the contents of your "c:\temp" directory.
Empty your recycle bin.

At this point your machine will be as clean of Oracle components as it can be without a complete OS reinstall.
Remember, manually editing your registry can be very destructive and force an OS reinstall so only do it as a last resort.

If some DLLs can't be deleted, try renaming them, the after a reboot delete them.

                                                                  ( OR )

Oracle11g introduce new utility "deinstall" to uninstall/deinstall oracle database with configuration files.

run deinstall.bat file $ORACLE_HOME/deinstall/deinstall.bat

and give the prompt details then system will remove all the related files/services/folder.

if oci.dll not delete during deinstall process then restart system and delete manually.


UNIX

Uninstalling all products from UNIX is a lot more consistent. If you do need to resort to a manual uninstall you should do something like:
Uninstall all Oracle components using the Oracle Universal Installer (OUI).

Stop any outstanding processes using the appropriate utilities:

#  oemctl  stop  oms  user/password
#  agentctl  stop
#  lsnrctl  stop

Alternatively you can kill them using the kill -9 pid command as the root user.

Delete the files and directories below the $ORACLE_HOME:
#  cd   $ORACLE_HOME
#  rm  -Rf  *

With the exception of the product directory, delete directories below the $ORACLE_BASE.
#  cd  $ORACLE_BASE
#  rm  -Rf  admin  doc  jre  o*

Delete the /etc/oratab file. If using 9iAS delete the /etc/emtab file also.
                  #  rm  /etc/oratab /etc/emtab





Thursday, August 25, 2011

11G NEW FEATURES



RENAME ASM DISK GROUP:

11gR2 introduced renamedg utility to rename diskgroups. Before you use the command, ensure that ASM diskgroup is dismounted.

Below is syntax for the command.
 
renamedg 
[phase={ one|two |both } ] dgname=diskgroup
newdgname=newdiskgroup [config=configfile]
[ asm_diskstring=discoverystring, discoverystring ... ]
[ clean={true|false} ] [ check={true|false} ]
[ confirm={true|false}] [ verbose={ true|false} ]
[ keep_voting_files={true|false}]
 

Basically we have two phases of using renamedg command,
phase 1  à generates a configuration file to be used by phase 2.
In phase 2 à actual renaming of diskgroup is done.

Example:

renamedg dgname=data newdgname=dg asm_diskstring='/dev/oracleasm/disks/VOL*'  verbose=true


CASE sensitive passwords:

In Oracle 11g passwords are case sensitive by default. We can enable or disable this feature by setting the SEC_CASE_SENSITIVE_LOGON parameter. 

The SEC_CASE_SENSITIVE_LOGON parameter is a dynamic parameter. In the earlier version of the oracle like 10g & 9i passwords were not case sensitive

SYS@orcl11g>  show parameter SEC_CASE_SENSITIVE_LOGON
 
 
NAME                                             TYPE               VALUE
------------------------------------           -----------       -----------------------
sec_case_sensitive_logon             boolean          TRUE


Creating spfile/pfile from memory

Now we can even create a spfile/pfile from memory. It is a new feature in the 11g. Prior to 11g, we were able to create spfile from pfile or pfile from spfile.

Syntax:

CREATE SPFILE FROM MEMORY;
CREATE PFILE  FROM MEMORY;

Examples:
SYS@orcl11g>CREATE SPFILE='D:\backup\ORCL11G\spfile_bkp_18Jan2010.ora' FROM MEMORY;
File created.

SYS@orcl11g>CREATE PFILE='D:\backup\ORCL11G\pfile_bkp_18Jan2010.ora' FROM MEMORY;
File created.


Read-Only Table :

 

In Oracle 11g we can make a table read-only. It is a new feature in the Oracle 11g. Earlier we were able to make a non-system tablespace read-only. The Oracle 11g goes one step further and allows us to make a table read-only.

We have a new column called
 'read_only' in dba_tables, user_tables and all_tables views which tells whether a table is read only or not.

We will not be able to execute DML statements like INSERT, UPDATE and DELETE on a read-only table. And all so we cannot add/remove columns.
 

Syntax:
  
ALTER TABLE table_name READ ONLY;
ALTER TABLE table_name READ WRITE;


Examples:
 
SCOTT@orcl11g>DROP TABLE test_tbl;

Table dropped.


SCOTT@orcl11g>CREATE TABLE test_tbl AS SELECT * FROM dual;
Table created.


SCOTT@orcl11g>SELECT * FROM test_tbl;

D
-
X


SCOTT@orcl11g>INSERT INTO test_tbl VALUES ('A');
1 row created.

SCOTT@orcl11g>ALTER TABLE test_tbl READ ONLY;
Table altered.


SCOTT@orcl11g>SELECT table_name,read_only FROM user_tables WHERE table_name='TEST_TBL';

TABLE_NAME                     READ_ONLY
------------------------------ ----------
TEST_TBL                       YES


SCOTT@orcl11g>INSERT INTO test_tbl VALUES ('A');
INSERT INTO test_tbl values ('A')
            *
ERROR at line 1:
ORA-12081: update operation not allowed on table "SCOTT"."TEST_TBL"


SCOTT@orcl11g>UPDATE test_tbl SET dummy='Y' WHERE dummy='X';
UPDATE test_tbl SET dummy='Y' WHERE dummy='X'
       *
ERROR at line 1:
ORA-12081: update operation not allowed on table "SCOTT"."TEST_TBL"


SCOTT@orcl11g>DELETE FROM test_tbl;
DELETE FROM test_tbl
            *
ERROR at line 1:
ORA-12081: update operation not allowed on table "SCOTT"."TEST_TBL"


SCOTT@orcl11g>ALTER TABLE test_tbl ADD (name varchar2(10));
ALTER TABLE test_tbl ADD (name varchar2(10))
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "SCOTT"."TEST_TBL"


SCOTT@orcl11g>ALTER TABLE test_tbl DROP COLUMN name;
ALTER TABLE test_tbl DROP COLUMN name
*
ERROR at line 1:
ORA-12081: update operation not allowed on table "SCOTT"."TEST_TBL"


SCOTT@orcl11g>ALTER TABLE test_tbl READ WRITE;

Table altered.


SCOTT@orcl11g>INSERT INTO test_tbl VALUES('A');

1 row created.

SCOTT@orcl11g>


Invisible index :

Invisible index is a new feature of Oracle 11g. If we create an invisible index Oracle optimizer will not use it. This can be used to test a query without effecting the application. We can also make an index invisible/visible by using ALTER INDEX index_name [visible/invisible].

Syntax:

CREATE INDEX index_name ON table_name(column_name) INVISIBLE;
ALTER INDEX index_name INVISIBLE;
ALTER INDEX index_name VISIBLE;

Examples:
SYSTEM@orcl11g>show parameter optimizer_use_invisible_indexes 

NAME                                                                TYPE                 VALUE
------------------------------------                     -----------        --------------------
optimizer_use_invisible_indexes             boolean           FALSE


SYSTEM@orcl11g> desc test


Name Null? Type

----------------------------------------------------- -------- ------------
N NUMBER
NAME VARCHAR2(10)


SYSTEM@orcl11g>create index idx1 on test(n) invisible;
Index created.

SYSTEM@orcl11g>select owner,index_name,visibility from dba_indexes  where visibility = 'INVISIBLE';

OWNER                        INDEX_NAME              VISIBILIT
---------------                 ---------------------            ---------
SYSTEM                             IDX1                        INVISIBLE


SYSTEM@orcl11g>   select * from test where n=5;

N            NAME
------     ----------
5               H

Execution Plan
----------------------------------------------------------
Plan hash value: 1357081020

-------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 20 | 3 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| TEST | 1 | 20 | 3 (0)| 00:00:01 |
--------------------------------------------------------------------------

SYSTEM@orcl11g>alter index idx1 visible;
Index altered.

SYSTEM@orcl11g>  select * from test where n=5;

N           NAME
---------- ----------
5          H

Execution Plan
----------------------------------------------------------
Plan hash value: 1175071277
------------------------------------------------------------------------------------

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

---------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 20 | 2 (0)| 00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| TEST | 1 | 20 | 2 (0)| 00:00:01 |
|* 2 | INDEX RANGE SCAN | IDX1 | 1 | | 1 (0)| 00:00:01 |
---------------------------------------------------------------------------------

Use 1: Adding an index
You think adding an index will improve a query but you are not sure. Just create an invisible index. Test the query and decide.

Use 2: Dropping an index
You want to drop an index but don’t know how it will affect the application. Make that index invisible and analyze the performance. If it is not affecting the performance of the application, you can drop it.


crs_stat has been deprecated in 11gR2

 

While reading whats new and whats deprecated in Oracle 11gR2, I came across of the following:
Command crs_stat has been deprecated  in 11gR2, do not use it anymore, to find out all user resource state use, $GRID_HOME/bin/crsctl stat res -t 
               By the way, in 11gR2 or above, you can use the below command to find out the clusterware process state:      $GRID_HOME/bin/crsctl stat res -t -init


Wednesday, August 24, 2011

Row Migration & Row chaining


What is Row Chaining
-----------------------------


Row Chaining happens when a row is too large to fit into a single database block. For example, if you use a 8KB block size for your database and you need to insert a row of 16KB into it, Oracle will use 2/3 blocks and store the row in chain of data blocks for that segment. And Row Chaining happens only when the row is being inserted.

you can show the block size of database by

SQL> conn / as sysdba
SQL> show parameter db_block_size



What is Row Migration
---------------------
­­­­-----------

Row Migration Occurs when a row that originally fitted into one data block is updated so that the overall row length increases, and the block's free space is already completely filled. In this case, Oracle migrates the data for the entire row to a new data block, assuming the entire row can fit in a new block. Oracle preserves the original row piece of a migrated row to point to the new block containing the migrated row: the rowid of a migrated row does not change.



How can identified Row Chaining and row migration
-------------------------------------------------------------------------


There are 3 ways :-     1) by Analyze command
                                    2) USER_TABLES
                                    3) V$SYSSTAT


FIND & KILL A SESSION

SQL>   SELECT b.tablespace,b.segfile#,b.segblk#,b.blocks,a.sid,a.serial#,a.username,a.osuser, a.status
            FROM v$session a,v$sort_usage b WHERE a.saddr = b.session_addr;
 
TABLESPACE  SEGFILE#    SEGBLK#     BLOCKS  SID   SERIAL#       USERNAME       OSUSER    STATUS
----------------      -----------         ------------        -------      -----     ---------            --------------            --------         -------
TEMP                     0               5515776        128        76     19519          NI_EXT_STR    nibansal         INACTIVE
TEMP                     0               5456512        128        289    4221            VSL9                  visingh           KILLED
TEMP                     0               5438976        128        290    39365         SCOTT1           NBANSAL        KILLED
TEMP                     0               5456384        128        497    1926             AN13                akaushal         KILLED

The command for killing a session :

SQL> ALTER SYSTEM KILL SESSION ' sid,  serial# ';     (or)
SQL> ALTER SYSTEM KILL SESSION ' sid,  serial# '  immediate;

Example:


SQL> ALTER SYSTEM KILL SESSION '76,19519' ;
       (or)
SQL> ALTER SYSTEM KILL SESSION '76,19519'  IMMEDIATE;

For Windows:        C:>  orakill ORACLE_SID spid

For  UNIX :         $   KILL -9 spid;       (get SPID from V$PROCESS)
Auto Scroll Stop Scroll