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

Oracle Dbms Scheduler Exaples And Expalanation With Practical Demo –Windows

Windows provide the link between the scheduler and the resource manager, allowing different resource plans to be activated at different times. Since job classes point to resource consumer groups, and therefore resource plans, this mechanism allows control over the resources allocated to job classes and their jobs during specific time periods.
Only one window can be active (open) at any time, with one resource plan assigned to the window. The affect of resource plan switches is instantly visible to running jobs which are assigned to job classes. The interaction between the resource manager and the scheduler is beyond the scope of this document.
An inline schedule.
BEGIN
 DBMS_SCHEDULER.create_window (
window_name => ‘test_window_1’,
resource_plan   => NULL,
schedule_name   => ‘test_hourly_schedule’,
duration     => INTERVAL ’60’ MINUTE,
window_priority => ‘LOW’,
comments     => ‘Window with a predefined schedule.’);
 — Window with an inline schedule.
 DBMS_SCHEDULER.create_window (
window_name => ‘test_window_2’,
resource_plan   => NULL,
start_date   => SYSTIMESTAMP,
repeat_interval => ‘freq=hourly; byminute=0’,
end_date     => NULL,
duration     => INTERVAL ’60’ MINUTE,
window_priority => ‘LOW’,
comments     => ‘Window with an inline schedule.’);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_name, resource_plan, enabled, active
FROM   dba_scheduler_windows;
WINDOW_NAME                 RESOURCE_PLAN               ENABL ACTIV
—————————— —————————— —– —–
WEEKNIGHT_WINDOW                                           TRUE  FALSE
WEEKEND_WINDOW                                            TRUE  FALSE
TEST_WINDOW_1                                              TRUE  FALSE
TEST_WINDOW_2                                              TRUE  FALSE
4 rows selected.
Windows can be opened and closed manually using the OPEN_WINDOW and CLOSE_WINDOW procedures.
BEGIN
 DBMS_SCHEDULER.open_window (
  window_name => ‘test_window_2’,
  duration => INTERVAL ‘1’ MINUTE,
  force    => TRUE);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_name, resource_plan, enabled, active
FROM   dba_scheduler_windows;
WINDOW_NAME                 RESOURCE_PLAN               ENABL ACTIV
—————————— —————————— —– —–
WEEKNIGHT_WINDOW                                           TRUE  FALSE
WEEKEND_WINDOW                                             TRUE  FALSE
TEST_WINDOW_1                                              TRUE  FALSE
TEST_WINDOW_2                                             TRUE  TRUE
4 rows selected.
Close window.:-
BEGIN
 DBMS_SCHEDULER.close_window (
  window_name => ‘test_window_2’);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_name, resource_plan, enabled, active
FROM   dba_scheduler_windows;
WINDOW_NAME                 RESOURCE_PLAN               ENABL ACTIV
—————————— —————————— —– —–
WEEKNIGHT_WINDOW                                          TRUE  FALSE
WEEKEND_WINDOW                                             TRUE  FALSE
TEST_WINDOW_1                                              TRUE  FALSE
TEST_WINDOW_2                                             TRUE  FALSE
4 rows selected.
Windows can be dropped using the DROP_WINDOW procedure.
BEGIN
 DBMS_SCHEDULER.drop_window (
window_name => ‘test_window_1’,
force    => TRUE);
 DBMS_SCHEDULER.drop_window (
window_name => ‘test_window_2’,
force    => TRUE);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_name, resource_plan, enabled, active
FROM   dba_scheduler_windows;
WINDOW_NAME                 RESOURCE_PLAN               ENABL ACTIV
—————————— —————————— —– —–
WEEKNIGHT_WINDOW                                           TRUE  FALSE
WEEKEND_WINDOW                                            TRUE  FALSE
2 rows selected.
Windows Groups
A window group is a collection of related windows. It can be created with 0, 1 or many windows as group members using the CREATE_WINDOW_GROUP procedure.
BEGIN
 DBMS_SCHEDULER.create_window_group (
group_name  => ‘test_window_group’,
window_list => ‘test_window_1, test_window_2’,
comments => ‘A test window group’);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_group_name, enabled, number_of_windowS
FROM   dba_scheduler_window_groups;
WINDOW_GROUP_NAME           ENABL NUMBER_OF_WINDOWS
—————————— —– —————–
MAINTENANCE_WINDOW_GROUP    TRUE               2
TEST_WINDOW_GROUP           TRUE               2
2 rows selected.
Windows can be added and removed from a group using the ADD_WINDOW_GROUP_MEMBER and REMOVE_WINDOW_GROUP_MEMBER procedures.
Create a new window.
BEGIN
DBMS_SCHEDULER.create_window (
window_name => ‘test_window_3’,
resource_plan   => NULL,
schedule_name   => ‘test_hourly_schedule’,
duration     => INTERVAL ’60’ MINUTE,
window_priority => ‘LOW’,
comments     => ‘Window with a predefined schedule.’);
 DBMS_SCHEDULER.add_window_group_member (
group_name  => ‘test_window_group’,
window_list => ‘test_window_3’);
END;
/
PL/SQL procedure successfully completed.
Display window group members.
SELECT window_group_name, window_name
FROM   dba_scheduler_wingroup_members;
WINDOW_GROUP_NAME           WINDOW_NAME
—————————— ——————————
MAINTENANCE_WINDOW_GROUP    WEEKNIGHT_WINDOW
MAINTENANCE_WINDOW_GROUP    WEEKEND_WINDOW
TEST_WINDOW_GROUP           TEST_WINDOW_1
TEST_WINDOW_GROUP           TEST_WINDOW_2
TEST_WINDOW_GROUP           TEST_WINDOW_3
5 rows selected.
BEGIN
 DBMS_SCHEDULER.remove_window_group_member (
group_name  => ‘test_window_group’,
window_list => ‘test_window_3’);
END;
/
PL/SQL procedure successfully completed.
Display window group members.
SELECT window_group_name, window_name
FROM   dba_scheduler_wingroup_members;
WINDOW_GROUP_NAME           WINDOW_NAME
—————————— ——————————
MAINTENANCE_WINDOW_GROUP    WEEKNIGHT_WINDOW
MAINTENANCE_WINDOW_GROUP    WEEKEND_WINDOW
TEST_WINDOW_GROUP           TEST_WINDOW_1
TEST_WINDOW_GROUP           TEST_WINDOW_2
4 rows selected.
Window groups can be dropped using the DROP_WINDOW_GROUP procedure.
BEGIN
 DBMS_SCHEDULER.drop_window_group (
group_name => ‘test_window_group’,
force   => TRUE);
END;
/
PL/SQL procedure successfully completed.
Display window group details.
SELECT window_group_name, enabled, number_of_windowS
FROM   dba_scheduler_window_groups;
WINDOW_GROUP_NAME           ENABL NUMBER_OF_WINDOWS
—————————— —– —————–
MAINTENANCE_WINDOW_GROUP    TRUE               2
1 row selected.
The force option must be used if the window group currently has members.
Enable, Disable and Attributes
All applicable scheduler objects can be enabled and disabled using the overloaded ENABLE and DISABLE procedures.
Enable programs and jobs.
BEGIN
 DBMS_SCHEDULER.enable (name => ‘test_stored_procedure_prog’);
 DBMS_SCHEDULER.enable (name => ‘test_full_job_definition’);
Disable programs and jobs.
 DBMS_SCHEDULER.disable (name => ‘test_stored_procedure_prog’);
 DBMS_SCHEDULER.disable (name => ‘test_full_job_definition’);
END;
/
The values for individual attributes of all scheduler objects can be altered using one of the SET_ATTRIBUTE overloads.
BEGIN
 DBMS_SCHEDULER.set_attribute (
name   => ‘hourly_schedule’,
attribute => ‘repeat_interval’,
value => ‘freq=hourly; byminute=30’);
END;
/
The values can be set to NULL using the SET_ATTRIBUTE_NULL procedure.
BEGIN
 DBMS_SCHEDULER.set_attribute_null (
name   => ‘hourly_schedule’,
attribute => ‘repeat_interval’);
END;
/
Configuring The Scheduler
The SCHEDULER_ADMIN role gives a user the ability to control every aspect of the scheduler, as well as generating jobs to run as any other user. For this reason you should avoid granting it to anyone other than trusted DBAs.
For the majority of users, the CREATE JOB privilege will be sufficient.
For users requiring some level of scheduler administrative privileges, the MANAGE SCHEDULER privilege allows them to create additional scheduler objects, as well as allowing them to set and retrieve scheduler attributes using the SET_SCHEDULER_ATTRIBUTE and GET_SCHEDULER_ATTRIBUTE procedures.
Extracting DDL
The script used to create scheduler objects can be extracted using the DBMS_METADATA package, as shown in the following example.
CONN test/test
BEGIN
 DBMS_SCHEDULER.CREATE_JOB (
job_name   => ‘MY_TEST_JOB’,
job_type   => ‘PLSQL_BLOCK’,
job_action => ‘BEGIN NULL; END;’,
start_date => TRUNC(SYSDATE),
   repeat_interval => ‘FREQ=monthly;BYDAY=SUN;BYHOUR=22;BYMINUTE=0;BYSECOND=0’);
END;
/
SELECT DBMS_METADATA.get_ddl(‘PROCOBJ’,’MY_TEST_JOB’, ‘TEST’) AS job_def FROM dual;
JOB_DEF
——————————————————————————–
BEGIN
dbms_scheduler.create_job(‘”MY_TEST_JOB”‘,
job_type=>’PLSQL_BLOCK’, job_action=>
‘BEGIN NULL; END;’
, number_of_arguments=>0,
start_date=>TO_TIMESTAMP_TZ(’04-APR-2012 12.00.00.000000000 AM +01:00′,’DD-MON-R
RRR HH.MI.SSXFF AM TZR’,’NLS_DATE_LANGUAGE=english’), repeat_interval=>
‘FREQ=monthly;BYDAY=SUN;BYHOUR=22;BYMINUTE=0;BYSECOND=0’
, end_date=>NULL,
JOB_DEF
——————————————————————————–
job_class=>'”DEFAULT_JOB_CLASS”‘, enabled=>FALSE, auto_drop=>TRUE,comments=>
NULL
);
COMMIT;
END;
Clean up the test job using the floowing.
EXEC DBMS_SCHEDULER.drop_job(‘MY_TEST_JOB’);

Oracle Dbms Scheduler Exaples And Expalanation With Practical Demo

Although the scheduler is capable of very complicated schedules, on many occasions you just want to create a simple job with everything defined inline. If that’s all you want, the following example is for you.
BEGIN
 DBMS_SCHEDULER.create_job (
job_name     => ‘test_full_job_definition’,
job_type     => ‘PLSQL_BLOCK’,
job_action   => ‘BEGIN my_job_procedure; END;’,
start_date   => SYSTIMESTAMP,
repeat_interval => ‘freq=hourly; byminute=0; bysecond=0;’,
enabled      => TRUE);
END;
/
Programs
The scheduler allows you to optionally create programs which hold metadata about a task, but no schedule information. A program may related to a PL/SQL block, a stored procedure or an OS executable file. Programs are created using the CREATE_PROGRAM procedure.
Create the test programs.
BEGIN
 — PL/SQL Block.
 DBMS_SCHEDULER.create_program (
program_name   => ‘test_plsql_block_prog’,
program_type   => ‘PLSQL_BLOCK’,
program_action => ‘BEGIN DBMS_STATS.gather_schema_stats(”SCOTT”); END;’,
enabled     => TRUE,
comments    => ‘Program to gather SCOTT”s statistics using a PL/SQL block.’);
 — Shell Script.
 DBMS_SCHEDULER.create_program (
program_name     => ‘test_executable_prog’,
program_type     => ‘EXECUTABLE’,
program_action   => ‘/u01/app/oracle/dba/gather_scott_stats.sh’,
number_of_arguments => 0,
enabled          => TRUE,
comments         => ‘Program to gather SCOTT”s statistics us a shell script.’);
 — Stored Procedure with Arguments.
 DBMS_SCHEDULER.create_program (
program_name     => ‘test_stored_procedure_prog’,
program_type     => ‘STORED_PROCEDURE’,
program_action   => ‘DBMS_STATS.gather_schema_stats’,
number_of_arguments => 1,
enabled          => FALSE,
comments         => ‘Program to gather SCOTT”s statistics using a stored procedure.’);
 DBMS_SCHEDULER.define_program_argument (
program_name   => ‘test_stored_procedure_prog’,
argument_name => ‘ownname’,
argument_position => 1,
argument_type => ‘VARCHAR2’,
default_value => ‘SCOTT’);
 DBMS_SCHEDULER.enable (name => ‘test_stored_procedure_prog’);
END;
/
PL/SQL procedure successfully completed.
Display the program details.
SELECT owner, program_name, enabled FROM dba_scheduler_programs;
OWNER                       PROGRAM_NAME                ENABL
—————————— —————————— —–
SYS                         PURGE_LOG_PROG              TRUE
SYS                         GATHER_STATS_PROG           TRUE
SYS                         TEST_PLSQL_BLOCK_PROG          TRUE
SYS                         TEST_EXECUTABLE_PROG        TRUE
SYS                         TEST_STORED_PROCEDURE_PROG TRUE
5 rows selected.
Notice how programs that accept arguments must have the arguments defined before they can be enabled.
Programs can be deleted using the DROP_PROGRAM procedure.
BEGIN
 DBMS_SCHEDULER.drop_program (program_name => ‘test_plsql_block_prog’);
 DBMS_SCHEDULER.drop_program (program_name => ‘test_stored_procedure_prog’);
 DBMS_SCHEDULER.drop_program (program_name => ‘test_executable_prog’);
END;
/
PL/SQL procedure successfully completed.
Display the program details.
SELECT owner, program_name, enabled FROM dba_scheduler_programs;
OWNER                       PROGRAM_NAME                ENABL
—————————— —————————— —–
SYS                         PURGE_LOG_PROG              TRUE
SYS                         GATHER_STATS_PROG         TRUE
2 rows selected.
Schedules
Schedules optionally define the start time, end time and interval related to a job. Schedules are created using the CREATE_SCHEDULE procedure.
Create the schedule.
BEGIN
 DBMS_SCHEDULER.create_schedule (
schedule_name   => ‘test_hourly_schedule’,
start_date   => SYSTIMESTAMP,
repeat_interval => ‘freq=hourly; byminute=0’,
end_date     => NULL,
comments     => ‘Repeats hourly, on the hour, for ever.’);
END;
/
PL/SQL procedure successfully completed.
Display the schedule details.
SELECT owner, schedule_name FROM dba_scheduler_schedules;
OWNER                       SCHEDULE_NAME
—————————— ——————————
SYS                         DAILY_PURGE_SCHEDULE
SYS                         TEST_HOURLY_SCHEDULE
2 rows selected.
Notice how the interval is defined using the calendaring syntax. This is explained below.
A schedule can be dropped using the DROP_SCHEDULE procedure.
BEGIN
 DBMS_SCHEDULER.drop_schedule (schedule_name => ‘TEST_HOURLY_SCHEDULE’);
END;
/
PL/SQL procedure successfully completed.
Display the schedule details.
SELECT owner, schedule_name FROM dba_scheduler_schedules;
OWNER                       SCHEDULE_NAME
—————————— ——————————
SYS                         DAILY_PURGE_SCHEDULE
1 row selected.
Schedules don’t have to be created as separate objects. They can be defined using the REPEAT_INTERVAL parameter of the CREATE_JOB procedure.
Jobs
Jobs are what the scheduler is all about. They can either be made up of predefined parts (programs and schedules) or completely self contained depending on which overload of the CREATE_JOB procedure is used to create them.
Create jobs.
BEGIN
 — Job defined entirely by the CREATE JOB procedure.
 DBMS_SCHEDULER.create_job (
job_name     => ‘test_full_job_definition’,
job_type     => ‘PLSQL_BLOCK’,
job_action   => ‘BEGIN DBMS_STATS.gather_schema_stats(”SCOTT”); END;’,
start_date   => SYSTIMESTAMP,
repeat_interval => ‘freq=hourly; byminute=0’,
end_date     => NULL,
enabled      => TRUE,
comments     => ‘Job defined entirely by the CREATE JOB procedure.’);
 — Job defined by an existing program and schedule.
 DBMS_SCHEDULER.create_job (
job_name   => ‘test_prog_sched_job_definition’,
program_name  => ‘test_plsql_block_prog’,
schedule_name => ‘test_hourly_schedule’,
enabled    => TRUE,
comments   => ‘Job defined by an existing program and schedule.’);
 — Job defined by existing program and inline schedule.
 DBMS_SCHEDULER.create_job (
job_name     => ‘test_prog_job_definition’,
program_name => ‘test_plsql_block_prog’,
start_date   => SYSTIMESTAMP,
repeat_interval => ‘freq=hourly; byminute=0’,
end_date     => NULL,
enabled      => TRUE,
comments     => ‘Job defined by existing program and inline schedule.’);
 — Job defined by existing schedule and inline program.
 DBMS_SCHEDULER.create_job (
job_name   => ‘test_sched_job_definition’,
schedule_name => ‘test_hourly_schedule’,
job_type   => ‘PLSQL_BLOCK’,
job_action => ‘BEGIN DBMS_STATS.gather_schema_stats(”SCOTT”); END;’,
enabled    => TRUE,
comments   => ‘Job defined by existing schedule and inline program.’);
END;
/
PL/SQL procedure successfully completed.
— Display job details.
SELECT owner, job_name, enabled FROM dba_scheduler_jobs;
OWNER                       JOB_NAME                    ENABL
—————————— —————————— —–
SYS                         PURGE_LOG                  TRUE
SYS                         GATHER_STATS_JOB            TRUE
SYS                         TEST_FULL_JOB_DEFINITION    TRUE
SYS                         TEST_PROG_SCHED_JOB_DEFINITION TRUE
SYS                         TEST_PROG_JOB_DEFINITION    TRUE
SYS                         TEST_SCHED_JOB_DEFINITION   TRUE
6 rows selected.
Jobs are normally run asynchronously under the control of the job coordinator, but they can be controlled manually using the RUN_JOB and STOP_JOB procedures.
BEGIN
 — Run job synchronously.
 DBMS_SCHEDULER.run_job (job_name         => ‘test_full_job_definition’,
                      use_current_session => TRUE);
  Stop jobs.
 DBMS_SCHEDULER.stop_job (job_name => ‘test_full_job_definition, test_prog_sched_job_definition’);
END;
/
Jobs can be deleted using the DROP_JOB procedure.
BEGIN
 DBMS_SCHEDULER.drop_job (job_name => ‘test_full_job_definition’);
 DBMS_SCHEDULER.drop_job (job_name => ‘test_prog_sched_job_definition’);
 DBMS_SCHEDULER.drop_job (job_name => ‘test_prog_job_definition’);
 DBMS_SCHEDULER.drop_job (job_name => ‘test_sched_job_definition’);
END;
/
PL/SQL procedure successfully completed.
Display job details.
SELECT owner, job_name, enabled FROM dba_scheduler_jobs;
OWNER                       JOB_NAME                    ENABL
—————————— —————————— —–
SYS                         PURGE_LOG                  TRUE
SYS                         GATHER_STATS_JOB            TRUE
2 rows selected.
Job Classes
Job classes allow grouping of jobs with similar characteristics and resource requierments which eases administration. If the JOB_CLASS parameter of the CREATE_JOB procedure is undefined the job is assigned to the DEFAULT_JOB_CLASS. A job class is created using the CREATE_JOB_CLASS procedure.
Display the current resource consumer groups.
SELECT consumer_group FROM dba_rsrc_consumer_groups;
CONSUMER_GROUP
——————————
OTHER_GROUPS
DEFAULT_CONSUMER_GROUP
SYS_GROUP
LOW_GROUP
AUTO_TASK_CONSUMER_GROUP
5 rows selected.
Create a job class.
BEGIN
 DBMS_SCHEDULER.create_job_class (
job_class_name       =>  ‘test_job_class’,
resource_consumer_group =>  ‘low_group’);
END;
/
PL/SQL procedure successfully completed.
Display job class details.
SELECT job_class_name, resource_consumer_group FROM dba_scheduler_job_classes;
JOB_CLASS_NAME              RESOURCE_CONSUMER_GROUP
—————————— ——————————
DEFAULT_JOB_CLASS
AUTO_TASKS_JOB_CLASS        AUTO_TASK_CONSUMER_GROUP
TEST_JOB_CLASS              LOW_GROUP
3 rows selected.
Jobs can be assigned to a job class either during or after creation using the SET_ATTRIBUTE procedure.
BEGIN
 DBMS_SCHEDULER.create_job (
job_name   => ‘test_prog_sched_class_job_def’,
program_name  => ‘test_plsql_block_prog’,
schedule_name => ‘test_hourly_schedule’,
job_class => ‘test_job_class’,
enabled    => TRUE,
comments   => ‘Job defined by an existing program and schedule and assigned toa job class.’);
 DBMS_SCHEDULER.set_attribute (
name   => ‘test_prog_sched_job_definition’,
attribute => ‘job_class’,
value => ‘test_job_class’);
END;
/
PL/SQL procedure successfully completed.
Display job details.
SELECT owner, job_name, job_class, enabled FROM dba_scheduler_jobs;
OWNER                       JOB_NAME                    JOB_CLASS                   ENABL
—————————— —————————— —————————— —–
SYS                         PURGE_LOG                  DEFAULT_JOB_CLASS           TRUE
SYS                         GATHER_STATS_JOB            AUTO_TASKS_JOB_CLASS        TRUE
SYS                         TEST_FULL_JOB_DEFINITION    DEFAULT_JOB_CLASS           TRUE
SYS                        TEST_PROG_SCHED_JOB_DEFINITION TEST_JOB_CLASS              TRUE
SYS                         TEST_PROG_JOB_DEFINITION    DEFAULT_JOB_CLASS           TRUE
SYS                         TEST_SCHED_JOB_DEFINITION   DEFAULT_JOB_CLASS              TRUE
SYS                         TEST_PROG_SCHED_CLASS_JOB_DEF  TEST_JOB_CLASS              TRUE
7 rows selected.
Job classes can be dropped using DROP_JOB_CLASS procedure.
BEGIN
 DBMS_SCHEDULER.drop_job_class (
job_class_name => ‘test_job_class’,
force       => TRUE);
END;
/
PL/SQL procedure successfully completed.
Display job class details.
SELECT job_class_name, resource_consumer_group FROM dba_scheduler_job_classes;
JOB_CLASS_NAME              RESOURCE_CONSUMER_GROUP
—————————— ——————————
DEFAULT_JOB_CLASS
AUTO_TASKS_JOB_CLASS        AUTO_TASK_CONSUMER_GROUP
2 rows selected.
The force option disables any dependent jobs and sets their job class to the default value. If the job class has no dependents the force option is not necessary.

Oracle Dbms Job Exaples And Expalanation With Practical Demo

1)linuxLevel – crontab here is the Oracle server level
2)from 9i to 10g dbms jobs
3)Dbms scheduler from 10g
4)The DBMS_JOB package allows a user to schedule a job to run at a specified time.  A job is submitted to a job queue and runs at the specified time.  The user can also input a parameter that specifies how often the job should run.  A job can consist of any PL/SQL code.
5)Source: {ORACLE_HOME}/rdbms/admin/dbmsjob.sq
6)SNP processes run in the background and implement database snapshots and job queues.  If an SNP process fails, Oracle restarts it without affecting the rest of the database
7)The INIT.ORA initialization file contains three parameters that control the behavior of the SNP processes
JOB_QUEUE_PROCESSES:-           
How many processes to start.  If set to zero, no jobs are executed. Default is 0.  Range is 0..1000.
JOB_QUEUE_INTERVAL (obsolete in 9i):-
How long an interval the process will sleep before checking for a new job. Default is 60 sec.  Range is 1..3600 sec
JOB_QUEUE_KEEP_CONNECTIONS:-
Controls whether an SNP process closes any remote database connections. Default is False.  Range is True/False.
The person who submits a job to the job queue is considered the job’s owner.
8)Views
dba_jobs      
all_jobs      
user_jobs
dba_jobs_running      
all_jobs_running      
user_jobs_running
9)job timing(intervals)
Execute daily      –> ‘SYSDATE + 1’
Execute once per week –> ‘SYSDATE + 7’
Execute hourly     –>’SYSDATE + 1/24′
Execute every 10 min. –> ‘SYSDATE + 10/1440’
Execute every 30 sec. –> ‘SYSDATE + 30/86400’
Do not re-execute –> NULL
10)Syntax:
DBMS_JOB.CHANGE (
job    IN  BINARY_INTEGER,
what   IN  VARCHAR2,
next_date IN  DATE,
interval  IN  VARCHAR2,
instance  IN  BINARY_INTEGER DEFAULT NULL,
force IN  BOOLEAN DEFAULT FALSE);
explanation
job– Number of the job being run.
What – PL/SQL procedure to run.
next_date – Date of the next refresh.
interval – Date function evaluated immediately before the job starts running.
instance – When a job is submitted, specifies which instance can run the job.
This defaults to NULL, which indicates that instance affinity is not changed.
force – If this is FALSE, then the specified instance must be running.
Otherwise, the routine raises an exception.
If this is TRUE, then any positive integer is acceptable as the job instance.
practicals
Change the WHAT
The definition of a job can be altered by calling the DBMS_JOB.WHAT procedure.
Syntax:
DBMS_JOB.CHANGE (
job IN  BINARY_INTEGER,
what   IN  VARCHAR2);
Code:
execute DBMS_JOB.WHAT(3,Begin SEND_MESSAGE(); End;’);
Changing the Next Date
The DBMS_JOB.NEXT_DATE procedure alters the next execution time for a specified job.
Syntax:
DBMS_JOB.NEXT_DATE (JOB IN BINARY_INTEGER,
NEXT_DATE  IN DATE);
Code:
execute DBMS_JOB.NEXT_DATE(4,SYSDATE+3);
Changing the Interval
The DBMS_JOB.INTERVAL procedure alters the interval between executions for a specified job.
Syntax:
DBMS_JOB.INTERVAL (job      IN  BINARY_INTEGER,
interval  IN  VARCHAR2);
Assign job to RAC instance
Assign a specific RAC instance to execute a job:
Syntax:
dbms_job.instance(
job   IN BINARY_INTEGER,
instance IN BINARY_INTEGER,
force IN BOOLEAN DEFAULT FALSE);
SELECT instance_number FROM gv$instance;
Code:
EXECUTE  DBMS_JOB.INSTANCE(job=>123, instance=>1);
SELECT JOB,SUBSTR(WHAT,1,35),NEXT_DATE, NEXT_SEC,INTERVAL
FROM DBA_JOBS;
ISUBMIT
Submit a job with a user specified job number
Syntax:
dbms_job.isubmit (
job    IN BINARY_INTEGER,
what IN VARCHAR2,
next_date IN DATE,
interval  IN VARCHAR2 DEFAULT ‘NULL’,
no_parse  IN BOOLEAN DEFAULT FALSE);
N.B: no_parse indicates whether to parse job PL/SQL at time of submission (FALSE) or execution (TRUE)
exec dbms_job.isubmit(4242, ‘MYPROC’, SYSDATE);
IS_JOBQ
dbms_job.is_jobq RETURN BOOLEAN;
Code:
set serveroutput on
DECLARE
b BOOLEAN;
BEGIN
IF dbms_job.is_jobq THEN
dbms_output.put_line(‘TRUE’);
ELSE
dbms_output.put_line(‘FALSE’);
END IF;
END;
/
BROKEN Jobs
How a job becomes ‘broken’
Oracle has failed to successfully execute the job after 16 attempts.
                                      or
You have marked the job as broken, using the procedure DBMS_JOB.BROKEN
N.B:  Once a job has been marked as broken, Oracle will not attempt to execute the job until it is either marked not broken, or forced to be execute by calling the DBMS_JOB.RUN.
Syntax:
dbms_job.broken (
job    IN BINARY_INTEGER,
broken IN BOOLEAN,
next_date IN DATE DEFAULT SYSDATE);
Run a job now
To force immediate job execution:
EXEC dbms_job.run(job_no);
Mark a job as not broken
If a job fails to successfully execute it will go into a broken state after 16 attempts. To reset the job use following command
EXEC dbms_job.broken(jobno, FALSE);
Monitor User jobs
See created jobs:
Code:
SELECT  job, next_date,
next_sec,
failures,
broken,
SUBSTR(what,1,40) DESCRIPTION
FROM user_jobs;
Jobs that are currently running:
Code:
select
job                            j,
to_char ( last_date, ‘hh24:mi:ss’ ) last,
to_char ( this_date, ‘hh24:mi:ss’ ) this,
to_char ( next_date, ‘hh24:mi:ss’ ) next,
broken                         b,
failures                       f,
interval,
what
from user_jobs;
Remove a submitted job
Syntax:
dbms_job.remove(job IN BINARY_INTEGER);
EXECUTE DBMS_JOB.REMOVE(jobno);

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 ;
     }

Database Link In Oracle (Server To Server)

A  database link is schema object.
 A database link is a  connection between  two physical database servers that allows a client to  access them as  one logical database.

WHY USE DATABASE LINK:-
·   The most advantage  of database link is that they allow users to access another users objects  in a remote   database so that  they  are bounded by the privileges  set of the object owner.
They are three basic types of database link.
TYPES:-
1.private
2.public
GRANT PRIVILEGES:-
Sql>grant create database link to username;
Sql>grant create public database link to username;
TYPES:-
1.private database link:-
·         Create link in specific schema of the local database.
·         May be used only by the link owner.
Syntax:-
Sql>create private database link   connect to identified by using ‘tnsname’;
Example:-
Sql>create  private database link xla1 connect to u1 identified by u1 using ‘tnsxla12’;
2.public database link:-
·      A   public database link that can be used by any user.
·      You can access remote objects using insert,update and  delete statement.
Syntax:-
Sql>Create public database link connect to identified by using ‘tnsname’;
Example:-
Sql>create public database link xla1 connect to u1 identified by u1 using ‘tnsla1’;
DATABASE LINK RESTRICTIONS:-
Grant privileges on remote  objects.                    
 Do support describe operations –tables,views,functions,procedures,mviews,packages.
CLOSE DATABASE LINK:-
Syntax:-
Sql>alter session close database link ;
Example:-
Sql>alter session close database link xla1  ;
DROPPING A DATABASE LINK:-
Sql>drop database link ;
Sql>drop public database link ;
VIEWS:-
All_db_links
Dba_db_links
User_db_links
The local  database user can view the object.
Sql>select *  from tab@;
Sql>select * from tab@xla1;
practical:-
Test11> select name, password
2  from sys.user$
3  where name=’NIJAM’;
NAME                           PASSWORD
—————————— ——————————
NIJAM                         66EE6D5F9AB42E0F
1 row selected.
Changed current NIJAM password to temporary “tmp_pwd” and granted “create database link” privilege to NIJAM.
Test1> alter user nijam identified by tmp_pwd;
User altered.
Test1> grant create database link to nijam;
Grant succeeded.
Connect as NIJAM user using temporary password and creat database link.
Test1> connect nijam/tmp_pwd@test11
Connected.
nijam@TEST11> CREATE DATABASE LINK U1_LINK
2   CONNECT TO U1
3   IDENTIFIED BY u1
4   USING ‘(DESCRIPTION =
5         (ADDRESS_LIST =
6           (ADDRESS = (PROTOCOL = TCP)(HOST = linux01)(PORT = 1521))
7         )
8         (CONNECT_DATA =
9           (SID = TEST10)
10         )
11       )’;
Database link created.
Simple test:
nijam@TEST11> select count(*) from u1.u1_log@u1_link;
COUNT(*)
———-
355412
1 row selected.
LINK Link is functioning perfectly and now I can revoke “create database link privilege” and return password as it was before.
nijam@TEST11> conn Test11
Enter password:
Connected.
Test1> revoke create database link from nijam;
Revoke succeeded.
Test1> alter user nijam identified by values ’66EE6D5F9AB42E0F’;
User altered.
The key thing is to have prepared scripts to do this actions as quick as possible because when you change current schema password to temporary other users or u1s will not be able to log in.

Fully Concept Of Flashback Oracle ,Practical With Demo Error And Solution Also

Oracle Flashback Technology is a group of Oracle Database features that let you view past states of database objects or to return database objects to a previous state without using point-in-time media recovery.
Flashback feature was introduced in Oracle9i; it was limited to Flashback Query only
Great improvements have been made in the Flashback functions in Oracle Database 10g.
Flashback functionalities provide fast and flexible data recovery
TYPES OF FLASHBACK :-
1.     flashback query         —we can show  only the  past state of the table
2.     flashback version query   —show the the table transaction time and scn
3.     flashback transaction query —it show what operation is  done and which user is performed
4.     flashback table   — to flash back a table to an earlier scn or timestamp
5.     flashback drop flashback table to before drop using recylebin
6.     flashback database — to flash back a table to an earlier scn,timestamp or restore point
Flashback Works On Two Parameter
1.     scn
2.     timestamp
FLASHBACK STATUS:-
Flashback status of a database can be checked from the below query and system parameters.
           SQL> select NAME, FLASHBACK_ON from v$database;
        SQL> archive log list
        SQL> show parameter undo_retention
        SQL> show parameter  db_recovery_file_dest
        SQL> show parameter  db_recovery_file
FLASHBACK ENABLE:-
The Database must be started through SPFILE
SQL > show parameter spfile
NAME                       TYPE     VALUE
Step to Flashback Practical
1)undo_retention seconds, set to one hour
SQL> SELECT tablespace_name,retention FROM dba_tablespaces;
TABLESPACE_NAME             RETENTION
—————————— ———–
SYSTEM                         NOT APPLY
SYSAUX                         NOT APPLY
UNDOTBS1                    NOGUARANTEE
TEMP                           NOT APPLY
USERS                          NOT APPLY
TESTTBS                        NOT APPLY
6 ROWS selected.
SQL> ALTER TABLESPACE UNDOTBS1 retention guarantee;
TABLESPACE altered.
SQL> SELECT tablespace_name,retention FROM dba_tablespaces;
TABLESPACE_NAME             RETENTION
—————————— ———–
SYSTEM                         NOT APPLY
SYSAUX                         NOT APPLY
UNDOTBS1                    GUARANTEE
TEMP                           NOT APPLY
USERS                          NOT APPLY
TESTTBS                        NOT APPLY
6 ROWS selected.
SQL> ALTER SYSTEM SET undo_retention=3600;
SYSTEM altered.
2)create test1 table and insert some data’s
SQL> CREATE TABLE test1(id NUMBER, descr VARCHAR2(30));
TABLE created.
SQL> INSERT INTO test1 VALUES(1,’One’);
1 ROW created.
SQL> INSERT INTO test1 VALUES(2,’Two’);
1 ROW created.
SQL> INSERT INTO test1 VALUES(3,’Three’);
1 ROW created.
SQL> COMMIT;
COMMIT complete.
3)step to set flashback_on in database
SQL> shutdown IMMEDIATE
DATABASE closed.
DATABASE dismounted.
ORACLE instance shut down.
SQL> startup mount;
ORACLE instance started.
Total SYSTEM Global Area 1068937216 bytes
Fixed SIZE                  2233336 bytes
Variable SIZE             796920840 bytes
DATABASE Buffers          260046848 bytes
Redo Buffers                9736192 bytes
DATABASE mounted.
SQL> ALTER DATABASE flashback ON;
DATABASE altered.
SQL> ALTER DATABASE OPEN;
DATABASE altered.
SQL> SELECT flashback_on FROM v$database;
FLASHBACK_ON
——————
YES
You define the flashback database retention with:
SQL> show parameter db_flashback_retention_target
NAME                              TYPE     VALUE
———————————— ———– ——————————
db_flashback_retention_target     INTEGER 1440
4) You are now able to rewind your database at maximum db_flashback_retention_target minutes in the past, if you look into your Fast Recovery Area you see creation of below files:
[oracle@server1 fast_recovery_area]$ pwd
/oracle/fast_recovery_area
[oracle@server1 fast_recovery_area]$ ll
total 20
drwx—— 2 root   root 16384 May 11 17:05 lost+found
drwxr-x— 7 oracle dba   4096 Aug 15 14:23 TEST
[oracle@server1 fast_recovery_area]$ ll TEST
total 20
drwxr-x— 30 oracle dba 4096 Aug 15 00:11 archivelog
drwxr-x—  2 oracle dba 4096 Jul 13 11:22 autobackup
drwxr—–  5 oracle dba 4096 Jul 25 17:07 backupset
drwxr-x—  2 oracle dba 4096 Aug 15 14:23 flashback
drwxr-x—  2 oracle dba 4096 Jul 20 12:07 onlinelog
[oracle@server1 fast_recovery_area]$ ll TEST/flashback
total 16040
-rw-r—– 1 oracle dba 8200192 Aug 15 14:31 o1_mf_74l3ynbt_.flb
-rw-r—– 1 oracle dba 8200192 Aug 15 14:23 o1_mf_74l3yoth_.flb
5)add some values in the tables and just show the scn
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN         SCN_TO_TIMESTAMP(CURRENT_SCN)
———–                           ——————————-
  29034095                15-AUG-11 02.35.27.000000000 PM
SQL> SELECT * FROM test1;
   ID DESCR
———- ————–
        1 One
        2 Two
        3 Three
SQL> ALTER TABLE test1 ADD (column1 VARCHAR2(20));
TABLE altered.
SQL> UPDATE test1 SET column1=’Temporary’;
3 ROWS updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1;
    ID DESCR                       COLUMN1
———- —————-            ————-
        1 One                            TEMPORARY
        2 Two                            TEMPORARY
        3 Three                          TEMPORARY
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN       SCN_TO_TIMESTAMP(CURRENT_SCN)
———–      ———————————
  29034142       15-AUG-11 02.36.11.000000000 PM
6) flashback query — we can only show  the  past state of the table
SQL> flashback DATABASE as of scn 29034095;
Flashback complete.
SQL> SELECT * FROM nijam.test1;
    ID DESCR
———- ————–
     1 One
     2 Two
     3 Three
7) flashback table   — to flash back a table to an earlier scn or timestamp
Enabling row movement for your test table is mandatory for flashback table:
SQL> ALTER TABLE test1 enable ROW movement;
TABLE altered.
Database must be in mount state to flashback it:
SQL> shutdown IMMEDIATE;
DATABASE closed.
DATABASE dismounted.
ORACLE instance shut down.
SQL> startup mount;
ORACLE instance started.
Total SYSTEM Global Area 1068937216 bytes
Fixed SIZE               2233336 bytes
Variable SIZE          796920840 bytes
DATABASE Buffers       260046848 bytes
Redo Buffers                9736192 bytes
DATABASE mounted.
SQL> flashback DATABASE TO scn 29034095;
Flashback complete.
SQL> ALTER DATABASE OPEN resetlogs;
DATABASE altered.
SQL> SELECT * FROM nijam.test1;
          ID DESCR
———- ————–
    1 One
     2 Two
     3 Three
8) Inserting few test rows and performing a “wrong” update:
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN   SCN_TO_TIMESTAMP(CURRENT_SCN)
———–   ———————————–
  28947307 15-AUG-11 09.35.57.000000000 AM
SQL> SELECT * FROM test1;
ID DESCR
———- ——————
     1 One
     2 Two
     3 Three
SQL> INSERT INTO test1 VALUES(4,’Five’);
1 ROW created.
SQL> SELECT * FROM test1;
    ID DESCR
———- —————–
     1 One
     2 Two
     3 Three
     4 Five
SQL> UPDATE test1 SET descr=’Four’;
4 ROWS updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1;
    ID DESCR
  —– ————–
     1 Four
     2 Four
     3 Four
     4 Four
9) Flashing back table to original good state (SCN or timestamp taken in previous step, Oracle suggests to record current SCN before issuing such command):
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– ————————————-
  28947426 15-AUG-11 09.38.03.000000000 AM
SQL> flashback TABLE test1 TO scn 28947307;
Flashback complete.
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
You can also work with restore point (refer to official documentation for retention policies):
SQL> SELECT * FROM test1;
     ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> CREATE restore point before_upgrade;
Restore point created.
SQL> UPDATE test1 SET descr=’Temporary’;
3 ROWS updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 TEMPORARY
     2 TEMPORARY
     3 TEMPORARY
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– —————————————-
  28949800 15-AUG-11 10.03.02.000000000 AM
SQL> flashback TABLE test1 TO restore point before_upgrade;
Flashback complete.
SQL> SELECT * FROM test1;
   ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> DROP restore point before_upgrade;
Restore point dropped.
10) Using flasback technology will create SYS_TEMP_FBT in your schema:
SQL> SELECT table_name FROM user_tables;
TABLE_NAME
——————————
SYS_TEMP_FBT
TEST1
11) flashback drop  — flashback table to before drop using recylebin
SQL> SELECT table_name FROM user_tables;
TABLE_NAME
——————————
SYS_TEMP_FBT
TEST1
SQL> DROP TABLE test1;
TABLE dropped.
SQL> SELECT table_name FROM user_tables;
TABLE_NAME
——————————
SYS_TEMP_FBT
SQL> show recyclebin;
ORIGINAL NAME RECYCLEBIN NAME             OBJECT TYPE  DROP TIME
—————- —————————— ———— ——————-
TEST1         BIN$qogQry1iu6TgQEsKbCUKuA==$0 TABLE     2011-08-15:10:29:44
SQL> SELECT * FROM recyclebin;
OBJECT_NAME                 ORIGINAL_NAME                 OPERATION TYPE                   TS_NAME                     CREATETIME       DROPTIME            DROPSCN
—————————— ——————————– ——— ————————- —————————— ——————- ——————- ———-
PARTITION_NAME                CAN CAN RELATED BASE_OBJECT PURGE_OBJECT   SPACE
——————————– — — ———- ———– ———— ———-
BIN$qogQry1iu6TgQEsKbCUKuA==$0 TEST1                         DROP   TABLE                  USERS                       2011-08-15:09:35:12 2011-08-15:10:29:44   28951308
                             YES YES   71097    71097     71097       8
12) Once the object is dropped you cannot access it but you can still query its recyclebin counterpart and/or restore it:
SQL> SELECT * FROM test1;
SELECT * FROM test1
          *
ERROR AT line 1:
ORA-00942: TABLE OR VIEW does NOT exist
SQL> SELECT * FROM “BIN$qogQry1iu6TgQEsKbCUKuA==$0”;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> flashback TABLE test1 TO before DROP;
Flashback complete.
SQL> show recyclebin;
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
You can also purge it with:
SQL> purge recyclebin;
Recyclebin purged.
13) flashback query         —we can show  only the  past state of the table
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT table_name FROM user_tables;
TABLE_NAME
——————————
SYS_TEMP_FBT
TEST1
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn),TO_CHAR(SYSDATE,’dd-mon-yyyy hh24:mi:ss’) AS current_time FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)                                           CURRENT_TIME
———– ————————————————————————— —————————–
  28954179 15-AUG-11 11.03.48.000000000 AM                                          15-aug-2011 11:03:48
SQL> UPDATE test1 SET descr=’Temporary’;
3 ROWS updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1;
   ID DESCR
———- ——————————
     1 TEMPORARY
     2 TEMPORARY
     3 TEMPORARY
The flashback query feature works with AS OF SCN and AS OF TIMESTAMP in SELECT statement:
SQL> SELECT * FROM test1
AS OF scn 28954179;
     ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT * FROM test1
AS OF TIMESTAMP TO_TIMESTAMP(’15-AUG-11 11.03.48.000000000 AM’);
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT * FROM test1
AS OF TIMESTAMP SYSTIMESTAMP – INTERVAL ’10’  MINUTE
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
You can also use DBMS_FLASHBACK package for flashback query. This can as well been done with SCN using ENABLE_AT_SYSTEM_CHANGE_NUMBER procedure or timestamp using ENABLE_AT_TIME procedure:
SQL> EXEC dbms_flashback.enable_at_system_change_number(28954179);
PL/SQL PROCEDURE successfully completed.
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> EXEC dbms_flashback.disable;
PL/SQL PROCEDURE successfully completed.
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 TEMPORARY
     2 TEMPORARY
     3 TEMPORARY
Finally you can flashback your table using flashback table technology (or insert using AS SELECT in a subquery):
SQL> flashback TABLE test1 TO scn 28954179;
Flashback complete.
SQL> SELECT * FROM test1
ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
Remark:
This flashback query technology can also be used in export utility (exp and expdp) using FLASHBACK_SCN and FLASHBACK_TIME parameters.
14) flashback version query   —show the the table transaction time and scn
SQL> SELECT * FROM test1;
   ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– —————————————————————————
  29006118 15-AUG-11 12.51.21.000000000 PM
SQL> UPDATE test1 SET descr=’The one’ WHERE id=1;
1 ROW updated.
SQL> COMMIT;
COMMIT complete.
SQL> UPDATE test1 SET descr=’The only one’ WHERE id=1;
1 ROW updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– —————————————————————————
  29006142 15-AUG-11 12.52.03.000000000 PM
note:
Please note the commit after each update to generate multiple transactions.
You can now see past figures:
SQL> SELECT versions_startscn, versions_starttime, versions_endscn, versions_endtime, versions_xid, versions_operation, id, descr
FROM test1
VERSIONS BETWEEN SCN 29006118 AND 29006142
WHERE id = 1;
VERSIONS_STARTSCN VERSIONS_STARTTIME    VERSIONS_ENDSCN VERSIONS_ENDTIME      VERSIONS_XID V      ID DESCR
—————– ———————— ————— ———————— —————- – ———- ——————————
     29006133 15-AUG-11 12.51.45 PM                                          0A001500B99F0000 U       1 The only one
     29006128 15-AUG-11 12.51.36 PM        29006133 15-AUG-11 12.51.45 PM 060017000A100000 U       1 The one
                                              29006128 15-AUG-11 12.51.36 PM                             1 One
SQL> SELECT * FROM test1 AS OF scn 29006128;
     ID DESCR
———- ——————————
     1 The one
     2 Two
     3 Three
SQL> SELECT * FROM test1 AS OF scn 29006118;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT * FROM test1;
     ID DESCR
———- ——————————
     1 The only one
     2 Two
     3 Three
Note:
Same as DBMS_FLASHBACK package you may work with timestamp or SCN
15) flashback transaction query —it show what operation is  done and which user is performed
SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
DATABASE altered.
If we use flashback query example:
SQL> SELECT xid, operation, start_scn, commit_scn, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW(‘0A001500B99F0000’);
no ROWS selected
SQL> SELECT xid, operation, start_scn, commit_scn, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW(‘060017000A100000’);
XID           OPERATION                      START_SCN COMMIT_SCN LOGON_USER
—————- ——————————– ———- ———- ——————————
UNDO_SQL
——————————————————————————————————————————————————————————————————–
060017000A100000 UPDATE                          29006126   29006128 YJAQUIER
UPDATE “YJAQUIER”.”TEST1″ SET “DESCR” = ‘One’ WHERE ROWID = ‘AAARW7AAEAABn6GAAA’;
060017000A100000 BEGIN                           29006126   29006128 YJAQUIER
First strange thing is missing information for one of the DML statement… After a while if you again select the existing one:
SQL> SELECT xid, operation, start_scn, commit_scn, logon_user, undo_sql
FROM flashback_transaction_query
WHERE xid = HEXTORAW(‘060017000A100000’);
no ROWS selected
Behavior is really erratic and this is explained by bugs, apparently corrected in 11.2.0.2.2, so not really mature so far:
Bug 10358019 – Queries against FLASHBACK_TRANSACTION_QUERY return wrong results [ID 10358019.8]
Note:
Oracle 11gR2 extend this functionality with flashback transaction backout by flashing back a specific transactions and all its dependent transactions.
16) Flashback Data Archive
Flashback Data Archive (FDA) technology is an extension of flashback versions query technology and extend Undo functionality (bypassing UNDO_RETENTION parameter) by keeping figures for fixed pre-defined period (if enough available space obviously). On the paper it’s perfect: transparent, efficient, old figures stored in compressed format, answers to SOX requirements. Small drawback is the cost as you must purchase Oracle Total Recall option to use it…
First start by creating a dedicated tablespace (you may instead use an existing one):
SQL> CREATE TABLESPACE fda datafile ‘/oracle/data01/test/fda01.dbf’ SIZE 100m
extent management local SEGMENT SPACE management auto;
TABLESPACE created.
Then create a default flashback data archive (then no need to specify one when activating FDA on your tables), no quota to use whole tablespace and retention set to one month:
SQL> CREATE flashback archive DEFAULT fla1
TABLESPACE fda
retention 1 MONTH;
Flashback archive created.
Then modify your table:
SQL> ALTER TABLE test1 flashback archive;
TABLE altered.
Note:
To see what’s activated and your FDA you may use the following queries (USER and ALL counterparts may also be used)
SELECT * FROM dba_flashback_archive;
SELECT * FROM dba_flashback_archive_ts;
SELECT * FROM dba_flashback_archive_tables;
Let’s modify the table and see past figures, same as versions query and you may use SCN or timestamp. From pure SQL standpoint you don’t see difference with versions query, except in retention policy…
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– —————————————————————————
  29045024 15-AUG-11 04.22.20.000000000 PM
SQL> UPDATE test1 SET descr=’The one’ WHERE id=1;
1 ROW updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1;
    ID DESCR
———- ——————————
     1 The one
     2 Two
     3 Three
SQL> SELECT * FROM test1 AS OF scn 29045024;
     ID DESCR
———- ——————————
     1 One
     2 Two
     3 Three
SQL> SELECT current_scn, SCN_TO_TIMESTAMP(current_scn) FROM v$database;
CURRENT_SCN SCN_TO_TIMESTAMP(CURRENT_SCN)
———– —————————————————————————
  29045079 15-AUG-11 04.23.29.000000000 PM
SQL> UPDATE test1 SET descr=’The only one’ WHERE id=1;
1 ROW updated.
SQL> COMMIT;
COMMIT complete.
SQL> SELECT * FROM test1 AS OF scn 29045079;
   ID DESCR
———- ——————————
     1 The one
     2 Two
    3 Three
In this example past version of the table will be kept for one month and then automatically deleted.
With only few exceptions DDLs are supported and for unsupported ones you may use DBMS_FLASHBACK_ARCHIVE PL/SQL package:
SQL> ALTER TABLE test1 ADD (column1 VARCHAR2(20));
TABLE altered.
SQL> SELECT * FROM test1;
     ID DESCR                       COLUMN1
———- —————————— ——————–
     1 The only one
     2 Two
     3 Three
SQL> SELECT * FROM test1 AS OF scn 29045024;
    ID DESCR
———- ——————————
     1 One
     3 Three
        2 Two

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