Sub Queries In Oracle Database

Subquery or inner query or nested query is a query .sql subquery is usually added in the where clause of the sql statement.
The subquery can be nested inside a select,insert,update or delete statement or inside another query.
You can use the comparison operators such as  > , < , or = . the comparison operator can also be a multiple-row operator such as  IN , ANY , or ALL.
The inner query executes first before its parent query so that the result of inner query can be passed to the outer query.
Types Of Subqueries :-
Single row subquery
Multiple row subquery
Correlated subquery
SINGLE ROW SUBQUERY :-
Queries that return only one row from the inner select statement.
Select statement :
SQL > select * from tablename where columnname=(select columnname from tablename where columnname = ’value’);
Example :-
SQL > select * from t1 where id = (select id from t1 where salary =4500);
Insert statement :
Syntax :-
SQL > insert into tablename1 select * from tablename2 where columnname = (select columnname from tablename2 where columnname=’value’);
Example :-
SQL > insert into t1 select * from emp where empno = (select empno from emp where sal=800);
Update statement :
Syntax :-
SQL > update tablename1 set columnname=value where columnname = (select * from  tablename where columnname=value);
Example :-
SQL > update emp set sal=2000 where empno=(select * from t1where sal=800);
Delete statement :
Syntax :-
SQL >  delete from tablename where columnname =(select columnname from tablename where columnname=’value’);
Example :-
SQL > delete from emp where empno=(select empno from t1 where ename=’SMITH’);
MULTI ROW SUBQUERY
Queries that return more than one row from the Inner SELECT statement.
Types of operators
Operators   
                       Meaning
In                                
Any      

All      
Equal to any member in the list
Compare value to each value returned by the subquery
Compare value to every value returned by the subquery
                    
IN
SQL > select * form tablename where columnname in (select columnname from tablename where columnname=’values’);
Example :-
SQL > select * from emp where sal in (select sal from emp where deptno=10);
ANY
You can use the ANY operator to compare a value with any value in a list. You must place an =, , >, <, = operator before ANY in your query
Syntax :-
SQL > select * form tablename where columnname =any (select columnname from tablename where columnname=’values’);
Example :-
SQL > select * from emp where sal =any(select sal from emp where deptno=20);
ALL
Syntax :-
SQL > select * form tablename where columnname < all (select columnname from tablename where columnname=’values’);
Example :-
SQL > select * from emp where sal < all(select sal from emp where deptno=20);
Correlated subqueries
Correlated subqueries are used for row-by-row processing. Each subquery is executed once for every row of the outer query.
Syntax :-
SQL > select columnname,columnname from table1  where columnname operator (select columnname, from table2   where columnname=’values’);
Example :-
SQL > select a.name,a.salary from emp a where a.deptno =(select  deptno from dept b where b.deptno=10);

Setup Transparent Data Encryption In Oracle

TDE makes sure that the data is stored in encrypted form and when the data is accessed, it automatically decrypt it and it all happens transparently so it does not require even a single line of code at the application or database end.
setup Transparent Data Encryption:
First of all we need to define wallet location. Open your sqlnet.ora file and define the wallet location which can be any directory at the database server.
$ cd /d01/apps/oracle/network/admin
$ mkdir tde_wallet
$ vi sqlnet.ora
ENCRYPTION_WALLET_LOCATION =
(SOURCE=
  (METHOD=file)
(METHOD_DATA=
   (DIRECTORY=/d01/apps/oracle/network/admin/tde_wallet)))
Create a Secure Wallet to hold the Master Encryption Key:
$ sqlplus / as sysdba
SQL> alter system set encryption key authenticated by “ImOracle”;       
System altered.
                                               
Data with and without TDE:
create tablespace ts_tde
datafile ‘/d01/apps/oradata/oraxpo/ts_tde01.dbf’
size 20m autoextend on next 5m
extent management local
segment space management auto;
create user tde_test
identified by test
default tablespace ts_tde
quota unlimited on ts_tde;
grant connect,resource to tde_test;
We have a user named tde_test with a default tablespace ts_tde whose datafile.
conn tde_test/test
create table tde (sensitive_data varchar2(50));
insert into tde values (‘This is very sensitive data’);
commit;
select * from tde;
 SENSITIVE_DATA
————————————————–
This is very sensitive data
SQL> conn / as sysdba
Connected.
Flush the buffer_cache so that blocks in DB Buffer cache go to the datafile.
SQL> alter system flush buffer_cache;
System altered.
Now we create a table with a column encrypted transparently:
$ sqlplus tde_test/test
SQL> drop table tde purge;
Table dropped.
There are 4 encryption algorithms available for TDE.
  3DES168
  AES128
  AES192
  AES256
AES192 is the default.
create table tde (sensitive_data varchar2(50) encrypt using ‘3DES168’);
insert into tde values (‘This is very sensitive data’);
commit;
select * from tde;
SENSITIVE_DATA
——————————-
This is very sensitive data
As you see the data entered in an encrypted column is accessible in clear text.
And that is why this encryption is called Transparent Data Encryption.
SQL> conn / as sysdba
Connected.
SQL> alter system flush buffer_cache;
System altered.
SQL> select table_name , column_name , ENCRYPTION_ALG , SALT
 2  from dba_encrypted_columns;
TABLE_NAME COLUMN_NAME    ENCRYPTION_ALG             SAL
————– —————– —————————– —
TDE         SENSITIVE_DATA 3 Key Triple DES 168 bits key YES
DBA_ENCRYPTED_COLUMNS gives you a list of all encrypted columns in the database.
Open and Close the wallet:
$ sqlplus / as sysdba
The database was restarted so the wallet is closed at this moment.
Any query on encrypted columns will throw an error.
SQL> select * from tde_test.tde;
select * from tde_test.tde
                   *
ERROR at line 1:
ORA-28365: wallet is not open
Let’s open the wallet and notice you will need a password to open the wallet.
SQL> alter system set encryption wallet open authenticated by “ImOracle”;
System altered.
SQL> select * from tde_test.tde;
 
SENSITIVE_DATA
————————————————–
This is very sensitive
 This is how we close the wallet.
SQL> alter system set encryption wallet close;
System altered.
SQL> select * from tde_test.tde;
select * from tde_test.tde
                   *
ERROR at line 1:
ORA-28365: wallet is not open

Step To Configure Oracle Flashback In Asm Database

1. Ensure db_recovery_file_dest is set.
sqlplus ‘/ as sysdba’
SQL> alter system set db_recovery_file_dest=’+’ SCOPE=spfile;
2. Ensure db_recovery_file_dest_size is set
SQL> alter system set db_recovery_file_dest_size=100G SCOPE=spfile;
3. Stop and start the database
sqlplus ‘/ as sysdba’
SQL> shutdown immediate;
SQL> startup mount;
If flashback to any previous point in time is required, then turn flashback on using the following command
SQL> alter database flashback on;
SQL> alter database open;
SQL> alter system set db_flashback_retention_target=2880;
NOTES
Set the db_recovery_file_dest to an appropriate location for the flashback recovery files.
Set the db_recovery_file_dest_size to an appropriate size for the amount and size of the testing required.
Set the db_flashback_retention_target to an appropriate time, in mins, to retain flashbackability.
Only run alter database flashback on; if there is a requirement to flashback to ANY previous point in time.
Determine if Flashback Database is Already Enabled.
sqlplus ‘/ as sysdba’
SQL> select flashback_on from v$database;
Creating and Using Flashback Restore points.
This worked example assumes the database is using ASM to manage its storage.
Createing a Restore point
Create a restore point whenever the database is at a state that it may needed to be flashed back to. Use the optional GUARANTEE FLASHBACK DATABASE clause to ensure that the restore point is not aged out of the flashback recovery area (FRA) as dictated by the db_flashback_retention_target parameter.
1. You may want to create the restore point in mount mode. If so, put the database into mount mode now.
2. Create a restore point
sqlplus ‘/ as sysdba’
SQL> create restore point [GUARANTEE FLASHBACK DATABASE];
Rolling Back to a Restore Point
1. Identify the Restore point
sqlplus ‘/ as sysdba’
SQL> select name, time,guarantee_flashback_databse from v$restore_point;
SQL> quit
2. For a non RAC environment use the following commands to flashback to a restore point.
sqlplus ‘/ as sysdba’
SQL> shutdown immediate;
SQL> startup mount;
SQL> flashback database to restore point ;
SQL> alter database open resetlogs;
3. For RAC instances use the following commands.
One one of the nodes run, srvctl stop database -d -o immediate
sqlplus ‘/ as sysdba’
SQL> startup mount;
SQL> flashback database to restore point ;
SQL> alter database open resetlogs;
SQL> shutdown immediate;
srvctl start database -d
Run crs_stat -t to confirm that the database is backup okay.
NOTES
Any tables created and updated without the LOGGING option will be suseptable to block curruption errors when the database is flashed back. These can be remedied by issuing the TRUNCATE TABLE command against the affected object(s).
Dropping a Restore Point
Restore points can be dropped with the database open using the following commands
sqlplus ‘/ as sysdba’
SQL> drop restore poijnt ;
Monitoring Flashback Logging
After enabling flashback logging, Oracle keeps track of the amount of logging generated. This can be queried from v$flashback_database_log, the estimate gets better with age. Note that this is the size of the flashback logs only and does not include space used by archive logs and RMAN backups.
sqlplus ‘/ as sysdba’
SQL> select estimated_flashback_size/1024/1024/1024 “EST_FLASHBACK_SIZE(GB)” from v$flashback_database_log;
Finding the Earliest Flashback Point
Querying V$flashback_database_log will show you the earliest point you can flashback your database to based on the size of the FRA and the currently available flashback logs.
sqlplus ‘/ as sysdba’
SQL> alter session set nls_date_format=’dd/mm/yy hh24:mi:ss’;
SQL> select oldest_flashback_scn,oldest_flashback_time from v$flashback_database_log;
Disabling Flashback Database
Full any previous point in time flashback can be disabled with the database open. Any unused Flashback logs will be automatically removed at this point and a message detailing the file deletion written to the alert log.
sqlplus ‘/ as sysdba’
SQL> ALTER DATABASE FLASHBACK OFF;
mostly comming Errors
ORA-38754: FLASHBACK DATABASE not started; required redo log is not available
Cause:-
Oracle needs to have the required archive logs in the archive destination at the time of flashback.
Solution:-
 rman target /
  run{
     allocate channel t1 device type ‘sbt_tape’;
     FLASHBACK DATABASE TO RESTORE POINT ;
     }

Reclaiming Oracle Disk Space,Datafile.Tablespace,Tables

Very often DBAs are requested( by user or by force to optimze space requirement or performance) to re-org tables and indexes to get free space after a mass housekeeping of application or after some weeks of application run. In order to take back space from datafile/tablespace DBA can do one or many of few standard things:
1. move table to same or different tablespace. Rebuild of indexes is must after move of table as rowid of rows are changed.
2. do export and import of table. Need business outage.
3. rebuild only indexes(with/without online) to claim free space of indexes only.
4. alter table table_name shrink space cascade; This will try to put blocks togather starting from start of first free block in the datafile. Cascade option will take care of indexes, so no need to rebuild indexes in this case.
5. online re-org of tablespace/tables with exception for tables with data type long and raw.

The Oracle extents are mapped to OS data blocks. The mapping can be revealed by dba_free_space and dba_extents. We can check the actual layout of segments and free space in datafile by below command:
select file_id, block_id first_block, block_id+blocks-1 last_block,
segment_name
from dba_extents
where tablespace_name = ‘BHUSHAN_DATA’
union all
select file_id, block_id, block_id+blocks-1, ‘free’
from dba_free_space
where tablespace_name = ‘BHUSHAN_DATA’
order by file_id, first_block
/
We can play around with above query to get information of each segment, related datafile etc.
There are 2 types of Fragmentation in Oracle:
1.Honeycomb fragmentation:
This is the fragmentation when free space is side by side. Honeycomb fragmentation donot bother you much until it is at the very beginning of the datafile. Mostly Shrink space cascade for the segment which is live before honeycomb fragmentation gets you rid of this fragmentation.
2.swiss cheese fragmentation:
This is the fragmentation when the free extents are separated by live segments.
If we query any tablespace with above shared script, we may get something like :
       20       73400      73407 BHUSHAN00
       20       73408      73415 free
       20       73416      73423 BHUSHAN00
Mostly, we have combination of both fragmentation and thats make it challenging.
Often DBA fire any of the re-org command without analyzing the order in which we should do so as to take benefit to the max and get the re-org done completely.
In my scenario, I had 15 indexes on a datafile in a tablespace. The total size on segments was 500mb and total size of datafile was 15000mb. Still I was not able to claim any space to OS for other datafile. There was lot of fragmentation for sure which got revealed on running above mentioned query.
After my effort I could claim all 11000mb.
The best approach i found was:
find the order in which extents for segment is scattered in datafile. Start rebiuld index/shrink table from the bottom or top where you find more free blocks.
Oracle has several tools to help reclaim disk space:
  1. alter database datafile xxx.dbf resize yym; – This will remove space that the physical “end” if the datafile, and the command will not work if any segments extend beyond your resize boundary.
  2. alter tablespace xxx coalesce – This command will reclaim space from honeycomb fragmentation  
Oracle leaves the high-water mark alone after rows are deleted, and you can reclaim space at the table level with these techniques, all of which lower the high water mark for the table, thereby freeing-up the space:
  1. export-import – For a complete reorganization and space reclamation, export/import allows you to restructure your files and reclaim lost space.
  2. dbms_redefinition – This procedure will reorganize a table while it remains online for updates.
  3. alter table xxx shrink – If you were 10g and beyond you could use “alter table xxx shrink space compact;” syntax.
  4. You can look at the coalesce table syntax.  Unlike the “deallocate unused space” syntax which removes space above the high-water mark, “coalesce” puts together discontiguous fragmented extents.  There are two type of space fragmentation in Oracle.
First is the honeycomb fragmentation, when the free extents are side by side, and the “Swiss Cheese” fragmentation, when the extents are separated by live segments.
alter table xxx coalesce;
You can also deallocate unused space.  Oracle notes that the “deallocate unused space” clause is used to to explicitly deallocate unused space at “the end” of a segment and makes that space available for other segments within the tablespace.
alter table xxx deallocate unused space;
alter index xxx deallocate unused space;
Internally, Oracle deallocates unused space beginning from the end of the objects (allocated space) and moving downwards toward the beginning of the object, continuing down until it reaches the high water mark (HWM).  For indexes, “deallocate unused space” coalesces all leaf blocks within same branch of b-tree, and quickly frees up index leaf blocks for use.

Tablespace Level Fragmentation — Defragmentation/Shrink A Big Tablespace In Oracle

The most efficient/effective way to defrag/shrink a big tablespace in oracle is to migrate the tables/indexes to new tablespaces.
Here below are the steps:
Step 1.find tablespace “benz” whether fragmented or not
Step 2.Login with dba account and create new tablespaces for the database user.
Sample SQL:
create tablespace BENZ2 datafile ‘/opt/oracle/storage/BENZ2.dbf’ size 256m autoextend on next 128m maxsize unlimited;

Step 3.Login with the db owner username/password
Step 4.Migrate the tables
Generate the table migration script
spool /tmp/username/moveTables.sql
select ‘alter table ‘ || SEGMENT_NAME || ‘ move tablespace BENZ2;’
FROM dba_Segments a,
dba_data_files b
WHERE b.file_id=a.relative_fno
and a.tablespace_name=‘BENZ’ and segment_type=‘TABLE’
order by FILE_NAME,segment_name;
spool off;
Step 5.Migrate the Indexes
Generate the index migration script
spool /tmp/username/MoveIndex.sql
select ‘alter index ‘ || SEGMENT_NAME || ‘ rebuild tablespace BENZ2;’
FROM dba_Segments a,
dba_data_files b
WHERE b.file_id=a.relative_fno
and a.tablespace_name=‘BENZ’ and segment_type=‘INDEX’
order by FILE_NAME,segment_name;
spool off;
Step 6. Migrate the LOB/LOBSegments if possible
spool /tmp/username/MoveLob.sql
select ‘ALTER TABLE ‘ || table_name || ‘ move lob(‘ || COLUMN_NAME || ‘) STORE AS (TABLESPACE BENZ2);’
from dba_tab_columns
where owner=‘BENZ’ and data_type=‘CLOB’;
spool off;
Step 7.check if anything missing in the original tablespace
set lin 300
col owner format A26
col segment_name format A26
col segment_type format A26
col tablespace_name format A26
col relative_fno format 99999
col file_name format A50
SELECT owner, segment_name, segment_type,a.tablespace_name, a.relative_fno, b.file_name
FROM dba_Segments a,
dba_data_files b
WHERE b.file_id=a.relative_fno
and a.tablespace_name=‘BENZ’
order by FILE_NAME,segment_name;
Step 8. Never forget to change the default tablespace of the user to the new one
ALTER USER default tablespace BENZ2;
Step 9.change tablespace offline
alter tablespace BENZ offline;

Ora-00020: Maximum Number Of Processes (1100), Exceeded Ora-01012: Not Logged On

The below error may trigger when you hit with max sessions exceeded
ERROR at line 1:
ORA-01012: not logged on
What is the cause of this ORA-00020 error and how do I fix it?
Answer:  The ORA-00020 is a serious production error because a user cannot connect.
The ORA-00020 is caused by two things:
1.      Disconnected processes:  Rogue “zombie” connections  to Oracle that are idle (not working).  To fix this, use the ALTER SYSTEM KILL command.  You may also need to kill session at the OS level with the KILL -9 or the ORAKILL command.
2.      Too few process buckets:  Oracle limits the number of connected processes with the processes parameter, and you may get the ORA-00020 error as the natural result in growth of system usage.
To fix this, increase the processes parameter, usually doubling the value to allow for future growth.
The OERR command shows these details for the ORA-00020 error:
ORA-00020: maximum number of processes (string) exceeded
Cause: All process state objects are in use.
Action: Increase the value of the PROCESSES initialization parameter
Show parameter process

ORA-01261: Parameter Db_Recovery_File_Dest Destination String Cannot Be Translated ORA-01262: Stat Failed On A File Destination Directory Linux-X86_64 Error: 2: No Such File Or Directory

While I start my database with my initialization parameter it fails with oracle error
Solution :-
su oracle
run environment variable
sqlplus / as sysdba

SQL>create pfile from spfile;

Then remove or comment below line in pfile
db_recovery_file_dest
Save and exit

su oracle

run environment variable
sqlplus / as sysdba

SQL>startup mount;
ORACLE instance started.
Total System Global Area 1068937216 bytes
Fixed Size 2166536 bytes
Variable Size 427819256 bytes
Database Buffers 624951296 bytes
Redo Buffers 14000128 bytes

it should became the mount stage then open the DB as follows
SQL>alter database open;
Database altered.

Maximum Key Length (3215) Exceeded While Doing Rebuild Ora-00604,Ora-01450: In Oracle

SQL> Alter index SAI.TESTVALUE_IDX rebuild online;
Alter index SAI.TESTVALUE_IDX rebuild online *
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-01450: maximum key length (3215) exceeded
Cause of the Problem
When creating an index the total length of the index cannot exceed a certain value. Primarily this value depends on DB_BLOCK_SIZE.
If 2K block size then maximum index key length=758
If 4K block size then maximum index key length=1578
If 8K block size then maximum index key length=3218
If 16K block size then maximum index key length=6498
How the maximum index key length is measured by?
Maximum index key length=Total index length (Sum of width of all indexed column + the number of indexed columns) +Length of the key (2 bytes) +ROWID (6 bytes) +the length of the rowid (1 byte)
The index key size is limited by the value of db_block_size, because a key value may not span multiple blocks. So, based on the size of the block size of index depends. In fact, it is required that any index block must contain at least TWO index entries per block.
So we can say that the maximum key length for an index will be less than half of the DB_BLOCK_SIZE. But we know that in a block there also needed space for PCTFREE, INITRANS and space for block overhead (Block Header, ROW Directory, Table Directory, etc.). After considering these bytes the actual space that can be used for the Index key is actually just over 1/3 of the DB_BLOCK_SIZE.

Solution of the Problem
1) Increase your database block size. Create a tablespace with bigger block size and create index on that tablespace.
2) If you have index on multiple columns then you can split index to single or 2 columns so that size does not extended over it can handle.
3) Rebuild the index without online clause. That is ALTER INDEX index_name REBUILD;
Because the online rebuild of the index creates a journal table and index. This internal journal IOT table contains more columns in its index. This is a feature of online rebuild. This time the error arises because that current value of the initialization parameter db_block_size is not large enough to create internal journal IOT.

Fragmentation Defragementation In Table Level

The rows are split into more than one block is called fragmentation. it decrease the block accesses and it slow the database performance. fragmentation are two type one is table fragmentation and second is index fragmentation.
TABLE FRAGMENTATION:
Each table have the blocks and it stored in the data files. The data will store in the block level. When the data split into more than one blocks is called table fragmentation. The table get more update and delete statement means table will get fragmentation.
When table getting full table scan in the that time oracle will read the data upto HWM (HIGH WATER MARK LEVEL). HWM is using to find used block and free block in table.
ROW CHAINING:
When inserting the row, in that time the block does not have any space means oracle allocate the next block for that inserting its called the row chaining.
ROW MIGRATION:                          
When updating the row in block the update not fit into the existing block it go to another block is called row migration. it based on pctfree. Because pctfree it low means the block get row migration.
FINDING THE FRAGMENTATION IN TABLE:
  • Create one table and add 2 column in that table.
  • Insert  max 1000000 records in that table and commit it.
  • Now do some delete operation in that table and analyze the table using estimate or compute statistics or dbms_space.space_usage package.
  • Now check the info in dba_tables using query
(SELECT chain_cnt FROM user_tables WHERE table_name = ‘ROW_MIG_CHAIN_DEMO’;)
  • Its  show the num_rows and chain_cnt, if u get any values in chain_cnt means fragmentation is accured.
  • Using dbms_space.space_usage
Steps to Check and Remove Table Fragmentation:-
1. Gather table stats:
To check exact difference in table actual size (dba_segments) and stats size (dba_tables). The difference between these value will report actual fragmentation to DBA. So, We have to have updated stats on the table stored in dba_tables. Check LAST_ANALYZED value for table in dba_tables. If this value is recent you can skip this step. Other wise i would suggest to gather table stats to get updated stats.
exec dbms_stats.gather_table_stats(‘&schema_name’,’&table_name’);
\
2. Check Table size:
select table_name,bytes/(1024*1024*1024) from dba_table where table_name=’&table_name’;
3. Check for Fragmentation in table:
SELECT chain_cnt FROM user_tables WHERE table_name = ‘ROW_MIG_CHAIN_DEMO’;
                (or)
set pages 50000 lines 32767
select owner,table_name,round((blocks*8),2)||’kb’ “Fragmented size”, round((num_rows*avg_row_len/1024),2)||’kb’ “Actual size”, round((blocks*8),2)-round((num_rows*avg_row_len/1024),2)||’kb’,
((round((blocks*8),2)-round((num_rows*avg_row_len/1024),2))/round((blocks*8),2))*100 -10 “reclaimable space % ” from dba_tables where table_name =’&table_Name’ AND OWNER LIKE ‘&schema_name’
/Note: This query fetch data from dba_tables, so the accuracy of result depends on dba_table stats.
If you find reclaimable space % value more than 20% then we can expect fragmentation in the table. Suppose, DBA find 50% reclaimable space by above query, So he can proceed for removing fragmentation.
4. DEFRAGMENTATIONS (or) remove fragemenation
1. move table to another tablespace
2. export and import the table(exp/imp)
3. shrink command (fron oracle 10g)
  (shrink command is only applicable for tables which are tablespace with auto segment space management)
4. CTAS method
5.online redefinition
option: 1 move table to another tablespace
alter table

enable row movement;
alter table

move tablespace ;
Now, get back table to old tablespaces using below command
alter table table_name move tablespace old_tablespace_name;
REBUILD ALL INDEXES:
We need to rebuild all the indexes on the table because of move command all the index goes into unusable state.
Here, value in status field may be valid or unusable.
SQL> select status,index_name from dba_indexes where table_name = ‘&table_name’;
STATUS INDEX_NAME
——– ——————————
UNUSABLE INDEX_NAME                             
Here UNUSABLE status going to valid
SQL> alter index rebuild online;  
Index altered.
Here, value in status field must be valid.
SQL> select status,index_name from dba_indexes where table_name = ‘&table_name’;
STATUS INDEX_NAME
——– ——————————
VALID INDEX_NAME                                
Gather table stats:
SQL> exec dbms_stats.gather_table_stats(‘&owner_name’,’&table_name’);
PL/SQL procedure successfully completed.
Check Table size:
table size will find reduced size of the table.
select table_name,bytes/(1024*1024*1024) from dba_table where table_name=’&table_name’;
Check for Fragmentation in table:
set pages 50000 lines 32767
select owner,table_name,round((blocks*8),2)||’kb’ “Fragmented size”, round((num_rows*avg_row_len/1024),2)||’kb’ “Actual size”, round((blocks*8),2)-round((num_rows*avg_row_len/1024),2)||’kb’,
((round((blocks*8),2)-round((num_rows*avg_row_len/1024),2))/round((blocks*8),2))*100 -10 “reclaimable space % ” from dba_tables where table_name =’&table_Name’ AND OWNER LIKE ‘&schema_name’
/
Option: 2Export and Import the table(exp/imp)
SQL> select table_name, round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 85536kb
SQL> select table_name, round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 42535.54kb
SQL> select status from user_indexes where table_name = ‘BENZ’;
STATUS
——–
VALID
SQL> exit
Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Pr
oduction
With the Partitioning, OLAP and Data Mining options
C:\>exp scott/tiger@Orcl file=c:\benz.dmp tables=benz
Export: Release 10.1.0.5.0 – Production on Sat Jul 28 16:30:44 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to: Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Produc
tion
With the Partitioning, OLAP and Data Mining options
Export done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set
About to export specified tables via Conventional Path …
. . exporting table BENZ 468904 rows exported
Export terminated successfully without warnings.
C:\>sqlplus scott/tiger@orcl
SQL*Plus: Release 10.1.0.5.0 – Production on Sat Jul 28 16:31:12 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Production
With the Partitioning, OLAP and Data Mining options
SQL> truncate table benz;
Table truncated.
SQL> exit
Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Pr
oduction
With the Partitioning, OLAP and Data Mining options
C:\>imp scott/tiger@Orcl file=c:\benz.dmp ignore=y
Import: Release 10.1.0.5.0 – Production on Sat Jul 28 16:31:54 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to: Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Produc
tion
With the Partitioning, OLAP and Data Mining options
Export file created by EXPORT:V10.01.00 via conventional path
import done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set
. importing SCOTT’s objects into SCOTT
. . importing table “BENZ” 468904 rows imported
Import terminated successfully without warnings.
C:\>sqlplus scott/tiger@orcl
SQL*Plus: Release 10.1.0.5.0 – Production on Sat Jul 28 16:32:21 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.5.0 – Production
With the Partitioning, OLAP and Data Mining options
SQL> select table_name, round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 85536kb
SQL> select table_name, round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 42535.54kb
SQL> exec dbms_stats.gather_table_stats(‘SCOTT’,’BENZ’);
PL/SQL procedure successfully completed.
SQL> select table_name, round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 51840kb
SQL> select table_name, round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘BENZ’;
TABLE_NAME size
—————————— ——————————————
BENZ 42542.27kb
SQL> select status from user_indexes where table_name = ‘BENZ’;
STATUS
——–
VALID
SQL> exec dbms_redefinition.can_redef_table(‘SCOTT’,’BENZ’,-
> dbms_redefinition.cons_use_pk);
PL/SQL procedure successfully completed.
Option: 3 Shrink command (fron Oracle 10g):-
Shrink command:
Its a new 10g feature to shrink (reorg) the tables (almost) online which can be used with automatic segment space management.
This command is only applicable for tables which are tablespace with auto segment space management.
step to shrink
SQL> alter table

enable row movement;
Table altered.
There are 2 ways of using this command.
1. Rearrange rows and reset the HWM:
     Part 1: Rearrange (All DML’s can happen during this time)
SQL> alter table

shrink space compact;
Table altered.
Part 2: Reset HWM (No DML can happen. but this is fairly quick, infact goes unnoticed.)
SQL> alter table

shrink space;
Table altered.
2. Directly reset the HWM:
SQL> alter table

shrink space; (Both rearrange and restting HWM happens in one statement)
Table altered.
Advantages are:
1. Unlike “alter table move ..”,indexes are not in UNUSABLE state.After shrink command,indexes are updated also.
2. Its an online operation, So you dont need downtime to do this reorg.
3. It doesnot require any extra space for the process to complete.
Option: 4 CTAS method
Examples:-
SQL> create table benz as select * from nijam;
Table created.
SQL> drop table nijam purge;
Table dropped.
SQL> rename benz to nijam;
Table renamed.
SQL> exec dbms_stats.gather_table_stats(‘SCOTT’,’NIJAM’);
PL/SQL procedure successfully completed.
SQL> select table_name,round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 85536kb
SQL> select table_name,round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 68986.97kb
SQL> select status from user_indexes
2 where table_name = ‘NIJAM’;
no rows selected
Note:- we need to create all indexes.
Option:5 online redefinition examples
SQL> create table NIJAM (
2 no number,
3 name varchar2(20) default ‘NONE’,
4 ddate date default SYSDATE);
Table created.
SQL> alter table nijam add constraint pk_no primary key(no);
Table altered.
SQL> begin
2 for x in 1..100000 loop
3 insert into nijam ( no , name, ddate)
4 values ( x , default, default);
5 end loop;
6 end;
7 /
PL/SQL procedure successfully completed.
SQL> create or replace trigger tri_nijam
2 after insert on nijam
3 begin
4 null;
5 end;
6 /
Trigger created.
SQL> select count(*) from nijam;
COUNT(*)
———-
100000
SQL> delete nijam where rownum <= 50000;
50000 rows deleted.
SQL> commit;
Commit complete.
SQL> exec dbms_stats.gather_table_stats(‘SCOTT’,’NIJAM’);
PL/SQL procedure successfully completed.
SQL> select table_name, round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 2960kb
SQL> select table_name, round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 822.69kb
Minimum Privs required “DBA” role or “SELECT” on dbms_redefinition pkg
First check table is condidate for redefinition.
SQL> exec sys.dbms_redefinition.can_redef_table(‘SCOTT’,-
> ‘NIJAM’,-
> sys.dbms_redefinition.cons_use_pk);
PL/SQL procedure successfully completed.
After verifying that the table can be redefined online, you manually crea
te an empty interim table (in the same schema as the table to be redefined)
SQL> create table BENZ as select * from nijam WHERE 1 = 2;
Table created.
SQL> exec sys.dbms_redefinition.start_redef_table ( ‘SCOTT’,-
> ‘NIJAM’,-
> ‘BENZ’);
PL/SQL procedure successfully completed.
This procedure keeps the interim table synchronized with the original tab
SQL> exec sys.dbms_redefinition.sync_interim_table (‘SCOTT’,-
> ‘NIJAM’,-
> ‘BENZ’);
PL/SQL procedure successfully completed.
SQL> –Create PRIMARY KEY on interim table(BENZ)
SQL> alter table BENZ
2 add constraint pk_no1 primary key (no);
Table altered.
SQL> create trigger tri_benz
2 after insert on benz
3 begin
4 null;
5 end;
6 /
Trigger created.
Disable foreign key on original table if exists before finish this proces
SQL> exec sys.dbms_redefinition.finish_redef_table ( ‘SCOTT’,-
> ‘NIJAM’,-
> ‘BENZ’);
PL/SQL procedure successfully completed.
SQL> exec dbms_stats.gather_table_stats(‘SCOTT’,’NIJAM’);
PL/SQL procedure successfully completed.
SQL> select table_name, round((blocks*8),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 1376kb
SQL> select table_name, round((num_rows*avg_row_len/1024),2)||’kb’ “size”
2 from user_tables
3 where table_name = ‘NIJAM’;
TABLE_NAME size
—————————— ——————————————
NIJAM 841.4kb
SQL> select status,constraint_name
2 from user_constraints
3 where table_name = ‘NIJAM’;
STATUS CONSTRAINT_NAME
——– ——————————
ENABLED PK_NO1
SQL> select status ,trigger_name
2 from user_triggers
3 where table_name = ‘NIJAM’;
STATUS TRIGGER_NAME
——– ——————————
ENABLED TRI_BENZ
SQL> drop table BENZ PURGE;
Table dropped.

Rac Error-CRS-0259:,PRCR-1071,PRCR-1006 Failed to add resource ora.rocratc1.db for rocratc1

PRCR-1006 : Failed to add resource ora.rocratc1.db for rocratc1
PRCR-1071 : Failed to register or update resource ora.rocratc1.db
CRS-0259: Owner of the resource does not belong to the group.

solution:-
srvctl add database -d dbname -o /oracle/product/11.2.0/db_1

# /etc/init.d/oracleasm createdisk VOL1 /dev/sdc1
Marking disk “/dev/sdc1” as an ASM disk: [ Failed]

then follow

/usr/sbin/asmtool -C -l /dev/oracleasm -n VOL1 -s /dev/sde1 -a force=yes

/u01/11.2.0/grid/product/11.2.0/grid/bin
ls -l oracle

root#chmod 6751 oracle

Design a site like this with WordPress.com
Get started