Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, April 1, 2026

Using Assertions to Prevent Scheduling Conflicts in Oracle 23ai and beyond

Hospitals manage hundreds of surgeries every day across multiple operating rooms. To ensure patient safety, efficient use of resources, and smooth hospital operations, having a reliable scheduling system is critical.

However, conflicts often occur when multiple staff members or systems try to book the same operating room at overlapping times. Left unchecked, these conflicts can cause delays, coordination issues, and even risks to patients.

A reliable solution is to use assertions in the database. With Oracle Database 23c, hospitals can enforce complex scheduling rules directly at the database level, ensuring no two surgeries are scheduled in the same operating room at the same time. This eliminates human error and protects hospital operations.
The Problem: Double Booking Operating Rooms

Surgery scheduling in hospitals typically follows this workflow:
 
  1. A surgeon requests a procedure.
  2. An operating room is assigned.
  3. Start and end times for the surgery are set.

Even with this workflow, overlapping bookings can happen if the database does not strictly enforce scheduling rules.

Example of a scheduling conflict:

RoomSurgeryStart TimeEnd Time
OR-305Knee Replacement7:009:00
OR-305Hip Replacement8:1510:15

Here, the surgeries overlap by 45 minutes, which can lead to:
  • Delays in procedures
  • Staff coordination problems
  • Risk to patient safety
  • Inefficient use of operating rooms

Relying solely on application logic or manual checks is risky—especially when multiple systems interact with the same database. 

Enforcing Scheduling Rules with Assertions

Assertions are database-level rules that guarantee certain conditions are always true. For hospital scheduling, the main rule is:

An operating room cannot host more than one surgery at the same time.

This ensures that time intervals for surgeries in the same room never overlap.
Example Data Model

Operating Rooms Table:

SQL> CREATE TABLE operating_rooms(
or_id NUMBER PRIMARY KEY,
or_name VARCHAR2(50),
department VARCHAR2(50)
);

Surgeons Table:
 
SQL> CREATE TABLE surgeons(
surgeon_id NUMBER PRIMARY KEY,
surgeon_name VARCHAR2(100),
surgeon_specialty VARCHAR2(50)
);


Surgery Schedule Table:

SQL> CREATE TABLE surgery_schedule(
surgery_id NUMBER PRIMARY KEY,
surgeon_id NUMBER,
or_id NUMBER,
start_time TIMESTAMP,
end_time TIMESTAMP,
CONSTRAINT fk_surgeon FOREIGN KEY (surgeon_id) REFERENCES surgeons(surgeon_id),
CONSTRAINT fk_room FOREIGN KEY (or_id) REFERENCES operating_rooms(or_id)
);

Without assertions, the database could allow conflicting schedules:

RoomSurgeryStart TimeEnd Time
OR-305Knee Replacement7:009:00
OR-305Hip Replacement8:1510:15

How Assertions Detect Conflicts

An assertion prevents overlapping surgeries by checking time intervals:
 
CREATE ASSERTION no_room_schedule_conflict
CHECK (
NOT EXISTS (
SELECT s1.or_id
FROM surgery_schedule s1
JOIN surgery_schedule s2
ON s1.or_id = s2.or_id
AND s1.surgery_id <> s2.surgery_id
WHERE s1.start_time < s2.end_time
AND s2.start_time < s1.end_time
)
);

Logic:

Two surgeries conflict if:
  • Surgery A start < Surgery B end
  • AND Surgery B start < Surgery A end

If a conflict exists, the assertion fails and the database blocks the transaction, preventing overlapping surgeries.

Example:

Valid Schedule:

RoomSurgeryStart TimeEnd Time
OR-402Appendectomy6:307:30
OR-402Gallbladder Removal7:309:00

Conflict Attempt:

RoomSurgeryStart TimeEnd Time
OR-402Appendectomy6:307:30
OR-402Hernia Repair7:008:00

Result: ERROR – assertion NO_ROOM_SCHEDULE_CONFLICT violated.

The conflicting schedule is automatically blocked. 

Why Hospitals Should Use Assertions

Assertions provide several advantages in hospital scheduling systems:
  1. Prevent Critical Operational Errors – Conflicts are blocked immediately.
  2. Protect Patient Safety – Eliminates risks caused by overlapping surgeries or delays.
  3. Ensure Centralized Data Integrity – Works across multiple systems like hospital administration portals, scheduling apps, and emergency systems.
  4. Simplify System Design – Reduces reliance on triggers, manual checks, or complex application validations.
Other Healthcare Applications

Assertions can also help manage:
  • Surgeon availability – Prevents double booking of surgeons.
  • ICU bed allocation – Ensures ICU reservations never exceed capacity.
  • Medical equipment scheduling – Avoids conflicts for MRI, X-ray, or CT scanners.
  • Staff shift compliance – Keeps nursing shifts within legally allowed hours.

Conclusion

Oracle Database 23c’s assertions provide a powerful mechanism for enforcing complex business rules directly in the database. In hospitals, where scheduling mistakes can have serious consequences, assertions ensure no operating room conflicts occur, safeguarding both patients and operations.

Thursday, August 10, 2023

SELECT without FROM Clause in Oracle 23c

Oracle 23c has many new features and “SELECT without FROM” is one of the features. By using this feature, you can run queries without using FROM clause and specifying table name for testing expressions to get the results which can be easy of use for developers.

You will no longer receive error “ORA-00923: FROM keyword not found where expected” when running expressions to get results in Oracle 23c. 

Here are few examples

Example 1: Run mathematical operations with or without using FROM clause and you will get the result

SQL> select 2+3 from dual;
SQL> select 2+3 ;

Example 2: Select current date with and without using FROM clause and you will get the result.

SQL> Select current_date from dual;
SQL> Select current_date;

Example 3: Select NEXTVAL with and without using FROM clause and you will get the result

SQL> Create sequence empno_seq;
 
SQL> select empno_seq.nextval from dual;
SQL> select empno_seq.nextval ;

Example 4: Pl/SQL block with and without using FROM clause and you will get the result
delcare
v1 number;
begin
select empno_seq.nextval into v1 from dual;
dbms_output.put_line ('v1= '||v1);
end;
/

delcare
v1 number;
begin
select empno_seq.nextval into v1;
dbms_output.put_line ('v1= '||v1);
end;
/

Many other databases such as MS SQL Server, MYSQL support without FROM clause, this will help improve SQL Code portability.

Thanks

Tuesday, September 6, 2022

Automatic Indexing in Oracle 19c & 21c

The DBA’s are responsible for Index management, which includes monitor index, add, change and remove based upon workload and ad-hoc manner. It will be difficult to decide type of index, when to create, change or drop and measure the impact, so there will be both positive and negative effects.

In Oracle 19c, the automatic indexing feature introduced and it automatically creates, rebuilds, and drops indexes to improve the performance based upon application workload and changes. This helps to optimize the database and improve performance without any user intervention.

The DBMS_AUTO_INDEX package is used for managing the automatic indexing and user can find out the current automatic index configuration by querying CDB_AUTO_INDEX_CONFIG view.

  • CONFIGURE Procedure - Configures automatic indexing.
  • DROP_AUTO_INDEXES Procedure - Drop the automatically created indexes manually by overriding the retention parameter.
  • DROP_SECONDARY_INDEXES Procedure -Deletes all the indexes, except the ones used for constraints
  • REPORT_ACTIVITY Function - Generate Report of the automatic indexing operations
  • REPORT_LAST_ACTIVITY Function - Generate Report of the last automatic indexing operation
AUTO_INDEX_MODE : The automatic indexing is controlled using the AUTO_INDEX_MODE property, It defines different modes of operation.

  • REPORT ONLY: Turn on automatic indexing and new indexes are invisible and not available for SQL operations
  • IMPLEMENT: Turn on automatic indexing and new indexes are visible available for SQL operations
  • OFF: Turn OFF automatic indexing but does not disable existing auto indexes.
SQL> exec dbms_auto_index.configure('AUTO_INDEX_MODE','REPORT ONLY');
SQL> exec dbms_auto_index.configure('AUTO_INDEX_MODE','IMPLEMENT');
SQL> exec dbms_auto_index.configure('AUTO_INDEX_MODE','OFF');


AUTO_INDEX_SCHEMA Procedure - When automatic indexing enabled all schemas will be used for auto indexes and you can exclude or include any schemas by using AUTO_INDEX_SCHEMA parameter

The below examples adds the SALES schema to AUTO INDEXES exclusion list

begin
dbms_auto_index.configure(
parameter_name => 'AUTO_INDEX_SCHEMA',
parameter_value => 'SALES',
allow => FALSE);
end;


The below examples removes the SALES schema from AUTO INDEXES exclusion list

begin
dbms_auto_index.configure(
parameter_name => 'AUTO_INDEX_SCHEMA',
parameter_value => 'SALES',
allow => NULL);
end;


The below example removes all the schemas from AUTO INDEXES exclusion list.

begin
dbms_auto_index.configure(
parameter_name => 'AUTO_INDEX_SCHEMA',
parameter_value => NULL,
allow => TRUE);
end;


You can also define retention period that you want auto indexes. The below example sets the retention period of auto indexes to 30 days.

begin
dbms_auto_index.configure(
parameter_name => 'AUTO_INDEX_RETENTION_FOR_AUTO',
parameter_value => '30');
end;


By default automatic indexes created in default permanent tablespace and you can change this by using AUTO_INDEX_DEFAULT_TABLESPACE

SQL> exec dbms_auto_index.configure('AUTO_INDEX_DEFAULT_TABLESPACE','AUTO_INDEX_TBS');

You can also allocate percentage of the tablespace can be used for auto indexes. In below example you can use 10%

SQL> exec dbms_auto_index.configure(‘AUTO_INDEX_SPACE_BUDGET’, ‘10’);



DROP_AUTO_INDEXES Procedure: Using this procedure you can Drop the automatically created indexes manually by overriding the retention parameter.

The below example will drop a single index in SALES schema and it allow recreate. If you do not want to recreate set the value to FALSE

begin
dbms_auto_index.drop_auto_indexes(
owner => ‘SALES’,
index_name => '”SYS_AI_45rfg54nxvjcty”',
allow_recreate => TRUE);
end;
/

The below example will drop all auto indexes owned by SALES and will not allow recreate as allow_recreate set to FALSE

begin
dbms_auto_index.drop_auto_indexes(
owner => 'SALES',
index_name => NULL
allow_recreate => FALSE);
end;
/

DROP_SECONDARY_INDEXES Procedure – This procedure deletes all the indexes, except the ones used for constraints

The below example deletes all auto indexes except the ones used for constraints

begin
dbms_auto_index.drop_secondary_indexes;
end;

The below example deletes all auto indexes from the REGION table in the SALES schema except the ones used for constraints

begin
dbms_auto_index.drop_secondary_indexes('SALES', 'REGION');
end;


The below example deletes all auto indexes in the SALES schema except the ones used for constraints

begin
dbms_auto_index.drop_secondary_indexes('SALES');
end;

REPORT_ACTIVITY Function – By using this function you can generate Report of the automatic indexing operations

The below example generates automatic indexing operations report executed in the last 24 hours.

declare
act_report clob := null;
begin
act_report := dbms_auto_index.report_activity();
end;

or

SQL> select dbms_auto_index.report_activity() from dual;


The below example generates HTML automatic indexing operations report executed in the last 6 hours activity.

SQL> select dbms_auto_index.report_activity(activity_start => systimestamp-0.25, activity_end => systimestamp-1, type => 'HTML') from dual;

REPORT_LAST_ACTIVITY Function -The below example generates report of the last automatic indexing executed in a database.

declare
act_report clob := null;
begin
act_report := dbms_auto_index.report_last_activity();
end;

or

SQL>  select dbms_auto_index.report_last_activity() from dual;


The Oracle 21c comes with an enhancement in Automatic indexing, which helps to reduce the over head of the cursor invalidations during automatic index creation and also added new enhancements to improve query performance.

Thanks & Regards
http://oracleracexpert.com, Oracle ACE

Monday, July 19, 2021

Generate Table, Index or tablespace DDLs in oracle

When migrating database from one server to another you need Tablespace creation DDL. Also it is very useful when copying specific table or index or exp/imp from one database to databases.

Here are few ways to generate the tablespace script from source database.

SQL>SET ECHO OFF;
SQL>SET HEADING OFF;
SQL>SET LINESIZE 1000;
SQL> SET LONG 60000;
SQL> SET FEEDBACK OFF;
SQL>SPOOL TBS_DDL.SQL
SQL>SELECT DBMS_METADATA.GET_DDL('TABLESPACE',DBA_TABLESPACES.TABLESPACE_NAME) FROM DBA_TABLESPACES;
SQL>SPOOL OFF

You can see below command if you want the TABLESPACE creation script specific to one Table space.

SQL> SELECT DBMS_METADATA.GET_DDL('TABLESPACE','&TABLESPACE_NAME') FROM dual;

You can use below command to generate specific TABLE, INDEX Script from a user

Syntax:-
select dbms_metadata.get_ddl('TABLE','<TABEL NAME>','<SCHEMA>') from dual;
select dbms_metadata.get_ddl('INDEX','<INDEX NAME>','<SCHEMA>') from dual;


Ex:-
select dbms_metadata.get_ddl('TABLE','EMP_SAL','EMP') from dual;
select dbms_metadata.get_ddl('INDEX','EMPNO_IDX','EMP') from dual;


You can use below command to all TABLE, INDEX Script from a user. First, connect to user

SQL>SET ECHO OFF;
SQL>SET HEADING OFF;
SQL>SET LINESIZE 1000;
SQL> SET LONG 60000;
SQL> SET FEEDBACK OFF;
SQL> SELECT DBMS_METADATA.GET_DDL('TABLE',U.TABLE_NAME)
FROM USER_TABLES U;
SQL> SELECT DBMS_METADATA.GET_DDL('INDEX',U.INDEX_NAME)
FROM USER_INDEXES U;  

In case if you need a View DDL, you can run below command;
SQL>select DBMS_METADATA.GET_DDL('VIEW',<View_Name>’) from dual;
or
SQL>select DBMS_METADATA.GET_DDL('VIEW','<view_name>','<schema_name>') from DUAL;

You can run below command to generate the DDL statements of a SCHEMA
set pages 30000
set linesize 1000
set lines 500
SQL> SELECT DBMS_METADATA.GET_DDL('USER','<schema_name>') FROM dual;

You can run below command to generate DDL statements for more than one schema

SQL> SELECT DBMS_METADATA.GET_DDL('USER',U.USERNAME) FROM DBA_USERS U WHERE USERNAME IN ('USER1','USER2');

You can run below command to generate DDL statement of the System Grant/ role granted/object granted to a schema owner

SQL> SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','<schema_name>') from dual;
SQL> SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','<schema_name>') from dual;
SQL> SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT',<Schema_Name>’) from dual;

You can run below command to generate DDL statement of the role
SQL> SELECT DBMS_METADATA.GET_DDL('ROLE','RESOURCE') from dual;

You can also use SQL Developer to get the DDL script for a specific object.

You can refer oracle documentation for more details on DBMS_METADATA

Thanks & Regards
http://oracleracexpert.com






Wednesday, May 26, 2021

ORA-01555: snapshot too old: rollback segment number x with name "_xxxxx" too small

When we come across “snapshot too old” error we need to look into all possibilities

1. Determine if UNDO_MANAGEMENT is MANUAL or AUTO – Make sure you are using Auto, this will take care of auto management and will help to tune

2. In the ora-01555, if you see segment number with name that means it is caused by UNDO segment, if not LOG segment due to read consistency

3. Find out which client sessions or programs causing the issue and QUERY DURATION.

The possible solution will be set UNDO_MANAGEMENT to AUTO then make sure we have set correct value for UNDO_RETENTION.

Run below SQL query to identify weather undo tablespace was too small to maintain UNDO_RETENTION

select inst_id, to_char(begin_time,'MM/DD/YYYY HH24:MI') begin_time,
UNXPSTEALCNT "# Unexpired|Stolen", EXPSTEALCNT "# Expired|Reused",
SSOLDERRCNT "ORA-1555|Error", NOSPACEERRCNT "Out-Of-space|Error",
MAXQUERYLEN "Max Query|Length" from gv$undostat
where begin_time between
to_date(‘Start time of the query','MM/DD/YYYY HH24:MI:SS')
and
to_date('End time of the query','MM/DD/YYYY HH24:MI:SS')
order by inst_id, begin_time;


Find out the current retention period by querying the tuned_undoretention column of v$undostat. The database tunes the undo retention period to be longer than the long running query. The v$undostat view contains one row for each 10-minute stats collection interval over the last 4 days. The Data beyond 4 days can query the dba_hist_undostat view.

The below query will display the tuned_undoretention value in seconds:

select to_char(begin_time, 'DD-MON-RR HH24:MI') begin_time,
to_char(end_time, 'DD-MON-RR HH24:MI') end_time,
tuned_undoretention from v$undostat
order by end_time;


Refer Oracle notes
Note 563470.1 Lob retention not changing when undo_retention is changed
Note 800386.1 ORA-1555 - UNDO_RETENTION is silently ignored if the LOB
Note 422826.1 How To Identify LOB Segment Use PCTVERSION Or RETENTION
Bug:3200789 Abstract: VISIBILITY OF LOB SEGMENT USAGE FOR UNDO


Thanks & Regards,
http://oracleracexpert.com, Oracle ACE

Thursday, January 16, 2020

ORA-00942: table or view does not exist

When calling a table directly or through procedure/function...etc user may receive error “ORA-00942: table or view does not exist”.

For ex:-
CREATE OR REPLACE FUNCTION PROC1
(Num IN NUMBER)
RETURN NUMBER
IS
BEGIN
INSERT INTO Table1 SELECT * FROM SCOTT.Table2 WHERE ID = Num;
END;

PL/SQL: ORA-00942: table or view does not exist

SQL> select * from table1;
select * from table1
              *
ERROR at line 1:
ORA-00942: table or view does not exist

Possible reasons:
1. The table name or view name spelled wrongly
2. The table or view doesn’t exist
3. The user doesn’t have required permissions

In some cases users have select access and able to query data but when running from a procedure they still receive “ORA-00942: table or view does not exist”

The reason for this error is the access granted trough a ROLE not directly. In order to access another user table from a procedure you need to have SELECT privilege granted directly.

Regards,
Satishbabu Gunukula, Oracle ACE
http://www.oracleracexpert.com

Tuesday, April 10, 2018

Oracle Flashback Technology and features

Oracle Flashback Technology is a group of Database features that that will help you to view past states of database objects or to return database objects to a previous state without using point-in-time media recovery.

With flashback features, you can do the following:
· Queries that return past data
· Recover rows or tables to a previous point in time
· Track and archive transactional data changes
· Roll back a transaction and its dependent transactions while the db online

Oracle flashback uses automatic undo management (AUM) for all flashback transactions.

Here are few Oracle flashback features.
· Flashback Database
· Flashback Table
· Flashback drop
· Flashback query
· Flashback Version/Transaction Query
· Flashback Data Archive (From Oracle 11g)
· Flashback Recovery Area:-

Flashback Database:- The FLASHBACK DATABASE is a fast alternative to performing an incomplete recovery. The database must be running in ARCHIVELOG mode, because archived logs are used in the Flashback Database operation. You must have a flash recovery area enabled, because flashback logs can only be stored in the flash recovery area.

To enable logging for Flashback Database, set the DB_FLASHBACK_RETENTION_TARGET initialization parameter and issue the ALTER DATABASE FLASHBACK ON statement.

DB_FLASHBACK_RETENTION_TARGET- length of the desired flashback window in minutes (1440 min)

SQL> ALTER SYSTEM SET DB_FLASHBACK_RETENTION_TARGET=4320; # 3 days

For ex-
FLASHBACK DATABASE TO TIMESTAMP my_date;
FLASHBACK DATABASE TO SCN my_scn;

Limitations:
· It cannot be used to repair media failures, or to recover from accidental deletion of data files.
· You cannot use Flashback Database to undo a shrink data file operation.
· If the database control file is restored from backup or re-created, all accumulated flashback log information is discarded
· Flashback database cannot be used against block corruptions.

Flashback Table The FLASHBACK TABLE used to restore an earlier state of a table in the event of human or application error. The time in the past to which the table can be flashed back is dependent on the amount of undo data in the system and cannot restore a table to an earlier state across any DDL operation.

SQL> FLASHBACK TABLE test TO TIMESTAMP (SYSTIMESTAMP - INTERVAL '1' minute);

Flashback Drop:

The Oracle 10g provides the ability to reinstating an accidentally dropped table from recyclebin.
SQL> FLASHBACK TABLE test TO BEFORE DROP;

Flashback Query The feature allows the DBA to see the value of a column as of a specific time, as long as the before-image copy of the block is available in the undo segment.

For ex:-
SQL> SELECT comments FROM employee AS OF TIMESTAMP TO_TIMESTAMP ('2004-03-29 13:34:12', 'YYYY-MM-DD HH24:MI:SS');

SQL> SELECT comments FROM employee AS OF SCN 722452;

Flashback Version/Transaction Query Flashback Query only provides a fixed snapshot of the data as of a time. Use Flashback Version Query feature to see the changed data between two time points.

Ex: - The following query shows the changes made to the table:

SQL> select versions_starttime, versions_endtime, versions_xid, versions_operation, rate from rates versions between timestamp minvalue and maxvalue order by VERSIONS_STARTTIME

Flashback transaction query can be used to get extra information about the transactions listed by flashback version queries using FLASHBACK_TRANSACTION_QUERY view. The UNDO_SQL column in the table shows the actual SQL Statement.

For Ex:-
SQL> SELECT xid, operation, start_scn, commit_scn, logon_user, undo_sql FROM flashback_transaction_query

Oracle 11g has more enhancements in Flashback Transaction and LogMiner. The LogMiner Viewer has been incorporated into Enterprise Manager and integrated with the new Flashback Transaction feature, making it simple to recover transactions. Flashback Transaction allows the changes made by a transaction to be undone.

Flashback Data Archive (From Oracle 11g) : Flashback data archive allows long-term retention (for ex years) of changed data to a table or set of tables for a user-defined period of time. Flashback Data Archive (which can logically span one or more table spaces) specifies a space quota and retention period for the archive, and then creates the required tables in the archive.

User needs the FLASHBACK ARCHIVE ADMINISTER, FLASHBACK ARCHIVE privileges

SQL> CREATE FLASHBACK ARCHIVE flash_back_archive

TABLESPACE flash_back_archive QUOTA 10G RETENTION 5 YEARS;

Flashback Recovery Area:-
Flash recovery area is a disk location in which the database can store and manage files related to Backup and Recovery. To setup a flash recovery area, you must choose a directory location or Automatic Storage Management disk group to hold the files.

Flash recovery area simplifies the administration of your database by automatically naming recovery-related files, retaining the files as long as they are needed for restore and recovery activities, and deleting the files when they are no longer needed to restore your database and space is needed for some other backup and recovery-related purpose.

To Setup Flash Recovery Area (FRA), you just need to specify below two parameters.
1. DB_RECOVERY_FILE_DEST_SIZE (Specifies max space to use for FRA)

2. DB_RECOVERY_FILE_DEST (Location of FRA)


Performance Guidelines for Oracle Flashback Technology
· For Oracle Flashback Version Query, use index structures.

· Not to scan entire tables and use indexes to query small set of past data. If you need to scan a full table then use parallel hint to the query

· Keep the statistics current as cost-based optimized relies on statistics and use the DBMS_STATS package to generate statistics for tables involved in a Oracle Flashback Query.

· In a Oracle Flashback Transaction Query, the xid column is of the type RAW(8). Use the HEXTORAW conversion function: HEXTORAW(xid)to take advantage of inbuilt function

· The I/O performance cost is mainly paging in the data and undo blocks I the buffer cache. The CPU performance cost is to apply undo.

· A Oracle Flashback Query against a materialized view does not take advantage of query rewrite optimization.

Regards
Satishbabu Gunukula, Oracle ACE

Monday, May 22, 2017

Webinar: What’s new in Oracle 12c Recovery Manager (RMAN)?

Oracle Database 12c offers new enhancements and additions in Recovery Manager (RMAN). Take the advantage of new features for efficient backup & recovery.

Date and time: May, 31 2017 8:00am-9:00am
Pacific Daylight Time (San Francisco, GMT-07:00)

Join the Webinar to learn New Features in Oracle RMAN 12c
  • SQL Interface Improvements 
  • SYSBACKUP Privilege 
  • Support for multitenant container and pluggable databases 
  • DUPLICATE enhancements 
  • Multisection Backup Improvements 
  • Restoring and Recovering Files Over Network 
  • Storage Snapshot Optimization 
  • Active Database Duplication Improvements 
  • Cross-Platform Backup and Restore Improvements 
  • Recovering Tables and Table Partitions using RMAN Backups 
  • Unified auditing and RMAN 
To register for this Webinar, please send an email to SatishbabuGunukula@gmail.com.

Note that registrations are limited and first come and first serve basis.
You will receive an email confirmation with meeting session link.

For Presentation link "Click here"

Regards,
Satishbabu Gunukula, Oracle ACE
http://www.oracleracexpert.com

Wednesday, February 17, 2016

How to enable and disable HANA Client Trace

Use hdbodbc_cons for tracing applications based on ODBC and hdbsqldbc_cons for tracing applications based on SQLDBC.

Use blow syntax

hdbodbc_cons.exe trace <level> <on/off>

Where levels are:
             api: tracing of ODBC api calls
             debug: detailed tracing of whole call stack
             sql: tracing of sql commands as well as output and parameter handling

Before you trun on trace, first configure the trace file name.
C:\Program Files\sap\hdbclient>hdbodbc_cons.exe config trace filename C:\temp\hdbodbc_trace.log

To turn on/off trace use below examples

Tracing of sql commands as well as output and parameter handling
          C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace sql on
          C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace sql off

Detailed tracing of whole call stack
          C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace debug on
          C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace debug off

Tracing of ODBC api calls
           C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace api on
           C:\Program Files\sap\hdbclient>hdbodbc_cons.exe trace api off

Reference:-
SAP Note: 1993254 - Collecting ODBC Trace
SAP Note: 1993251 - Collecting SQLDBC Trace

Regards,
Satishbabu Gunukula, Oracle ACE

Tuesday, October 7, 2014

Recovery Manager New Features in Oracle Database 12c - Part1

Hi Everyone,

My articles published in Oracle Experts website media "Allthingsoracle.com" by RedGate

Please view the article using below link.

Oracle Database 12c – RMAN New Features: Part1

In this article I will cover:
  • SQL Interface Improvements
  • SYSBACKUP Privilege
  • Support for multitenant container and pluggable databases
  • DUPLICATE enhancements
This article will help all Oracle Community to understand new enhancements and additions in Recovery Manager (RMAN) and take advantage of new features for efficient backup & recovery.

I hope you will like the article and it will be helpful to you.

Please leave your valuable comments.

Regards,
Satishbabu Gunukula, Oracle ACE
http://www.oracleracexpert.com

Thursday, January 23, 2014

Optimal redo logfile size in Oracle

If you have a small redo log file then you will see frequent log switches, in case of large redo logfile you might be at risk of losing data during instance crash. The optimal redo logfile size should not have more than 5 switches per hour.

You can use below query to find the number of log switches per hour

col day format a15;
col hour format a4;
col total format 999;
select to_char(first_time,'yyyy-mm-dd') day, to_char(first_time,'hh24') hour, count(*) total
from v$log_history
group by to_char(first_time,'yyyy-mm-dd'),to_char(first_time,'hh24')
order by to_char(first_time,'yyyy-mm-dd'),to_char(first_time,'hh24') asc;


To resize the redo logfile size follow the steps in below link

In Oracle 10g, the Redo Logfile Size Advisor introduced and using this you can determine the optimal redo log size based upon FAST_START_MTTR_TARGET parameter. You must set a non-zero value to enable redo log file size advisor.

FAST_START_MTTR_TARGET – this parameter enables you to specific number of seconds the database takes to perform crash recovery. Based up on this value Oracle determines the checkpoint writes to meet the target.

If you DONT set FAST_START_MTTR_TARGET then OPTIMAL_LOGFILE_SIZE in V$INSTANCE_RECOVERY will not populated with recommend redo log file size.

SQL> show parameter FAST_START_MTTR_TARGET
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
fast_start_mttr_target integer 0

SQL> select optimal_logfile_size from v$instance_recovery;
OPTIMAL_LOGFILE_SIZE
--------------------------------

User must set FAST_START_MTTR_TARGET to a non-zero value then OPTIMAL_LOGFILE_SIZE in V$INSTANCE_RECOVERY will be populated with recommend redo log file size.

Here I am setting FAST_START_MTTR_TARGET=60 (sec), you will see that OPTIMAL_LOGFILE_SIZE will be populated with recommended value.

SQL> alter system set FAST_START_MTTR_TARGET=60 scope=both;
System altered.

SQL> select OPTIMAL_LOGFILE_SIZE from v$instance_recovery;
OPTIMAL_LOGFILE_SIZE
--------------------
151

Now the checkpoints are driven by FAST_START_MTTR_TARGET parameter.

In some cases user will see many log switches during batch job window and there is no log switches out of batch job window. In this case you need to optimal value for redo log size and may need to set archive_lag_target to force redo log switches to increase the frequency during non-batch job window.

For more information on archive_lag_target refer below Oracle document.
http://docs.oracle.com/cd/B19306_01/server.102/b14237/initparams009.htm

Regards
Satishbabu Gunukula, Oracle ACE
http://www.oracleracexpert.com

Monday, July 22, 2013

Thread 1 cannot allocate new log & Checkpoint not complete

Users will see these messages when Oracle wants to reuse the redolog file, but checkpoint position is still in the log, Oracle must wait until the checkpoint completes.

Cause: In this situation either DBWR writes slowly or log switch happens before the log is completely full or log file is small.

Mon Apr 15 07:20:42 2013
Thread 1 advanced to log sequence 5021
Current log# 1 seq# 5021 mem# 0: /oracle/ORCL/redoA/redo01.log
Mon Apr 15 07:21:15 2013
Thread 1 cannot allocate new log, sequence 5022
Checkpoint not complete


If you have many updates in the system, you might need more redo groups. If you have fewer redo groups then adding more redo groups will help.

Use below syntax to add more redo groups

ALTER DATABASE ADD LOGFILE GROUP <Group No> ('<Redo log member 1 path’ ,'<redo log member 2 path>') size 500M;

If you have smaller redo log and if you see many log switches then increasing the redo size might help.

Step1: Switch logfile to make group 1 ‘INACTIVE’

SQL> Alter system switch logfile;
SQL> select group#, status from v$log;

GROUP# STATUS
---------- ----------------
1 INACTIVE
2 ACTIVE
3 CURRENT

Step2:- Drop the log group1 which is ‘INACTIVE’ and recreate with bigger size.

SQL> alter database drop logfile group 1;

SQL> alter database add logfile group 1 ('/db01/ORCL/redoA/log1_m1.dbf',' /db01/ORCL/redoB/log1_m2.dbf') size 100M reuse;

Repeat step 1 and 2 until you drop and recreate all redo logs with bigger size.

It is a recommended to have 4-5 log switches per hour. You can use below Script to find the log switches on hourly basis.

set lines 120;
set pages 999;
SELECT to_char(first_time,'YYYY-MON-DD') day,
to_char(sum(decode(to_char(first_time,'HH24'),'00',1,0)),'99') "00",
to_char(sum(decode(to_char(first_time,'HH24'),'01',1,0)),'99') "01",
to_char(sum(decode(to_char(first_time,'HH24'),'02',1,0)),'99') "02",
to_char(sum(decode(to_char(first_time,'HH24'),'03',1,0)),'99') "03",
to_char(sum(decode(to_char(first_time,'HH24'),'04',1,0)),'99') "04",
to_char(sum(decode(to_char(first_time,'HH24'),'05',1,0)),'99') "05",
to_char(sum(decode(to_char(first_time,'HH24'),'06',1,0)),'99') "06",
to_char(sum(decode(to_char(first_time,'HH24'),'07',1,0)),'99') "07",
to_char(sum(decode(to_char(first_time,'HH24'),'08',1,0)),'99') "0",
to_char(sum(decode(to_char(first_time,'HH24'),'09',1,0)),'99') "09",
to_char(sum(decode(to_char(first_time,'HH24'),'10',1,0)),'99') "10",
to_char(sum(decode(to_char(first_time,'HH24'),'11',1,0)),'99') "11",
to_char(sum(decode(to_char(first_time,'HH24'),'12',1,0)),'99') "12",
to_char(sum(decode(to_char(first_time,'HH24'),'13',1,0)),'99') "13",
to_char(sum(decode(to_char(first_time,'HH24'),'14',1,0)),'99') "14",
to_char(sum(decode(to_char(first_time,'HH24'),'15',1,0)),'99') "15",
to_char(sum(decode(to_char(first_time,'HH24'),'16',1,0)),'99') "16",
to_char(sum(decode(to_char(first_time,'HH24'),'17',1,0)),'99') "17",
to_char(sum(decode(to_char(first_time,'HH24'),'18',1,0)),'99') "18",
to_char(sum(decode(to_char(first_time,'HH24'),'19',1,0)),'99') "19",
to_char(sum(decode(to_char(first_time,'HH24'),'20',1,0)),'99') "20",
to_char(sum(decode(to_char(first_time,'HH24'),'21',1,0)),'99') "21",
to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'99') "22",
to_char(sum(decode(to_char(first_time,'HH24'),'23',1,0)),'99') "23"
from
v$log_history
GROUP by to_char(first_time,'YYYY-MON-DD');

Click here to learn about "Private Strand Flush Not Complete"  message in alert.log

Regards,
Satishbabu Gunukula, Oracle ACE
http://www.oracleracexpert.com

Friday, September 21, 2012

Manage Access Control List in Oracle 11g and ORA-24247

Oracle 11g offers fine-grained access to network services (ACL) and the packages used to access external network resources are restricted.

The 11g allows access to external packages UTL_TCP, UTL_HTTP, UTL_SMTP, UTL_MAIL, UTL_INADDR, DBMS_LDAP, but the access must be granted explicitly. Please note that ACLs are stored in XML DB and user must install XML DB for the use of ACL, if not installed.

The DBMS_NETWORK_ACL_ADMIN package provides the interface to administer the network Access Control List (ACL).

     • ACL - Name of access control list in xml file and relative path will be “/sys/acls”
     • Description - Description of the ACL.
     • Principal - To whom the privilege is granted or revoked
     • Is_grant - Indicates weather the privilege is granted (TRUE) or denied (FALSE).
     • Privilege – Network privilege, Use ‘connect’ for access and ‘resolve’ for UTL_INADDR name/IP resolution.
     • Position – Position of ACL
     • Start_date – Start date of the ACL , the default value is NULL.
     • End_date – End date of an ACL.

Uses might see below error when they upgrade their databases from Oracle 10g to 11g. This is expected behavior in Oracle 11g

ORA-24247: network access denied by access control list (ACL)

This is expected behavior in 11g, if any of the UTL_% packages referred or used in any user defined programs. To resolve this issue user must explicitly grant the access using DBMS_NETWORK_ACL_ADMIN package.

For ex: - A used defined new send_mail PL/SQL program or existing program (After upgrading to 11g) failed with ORA-24247

DECLARE

mailhost VARCHAR2(64) := ‘localsmtp.oracleracexpert.com;
sender VARCHAR2(64) := 'fromuser@oracleracexpert.com';
recipient VARCHAR2(64) := 'touser@ oracleracexpert.com';
smtp_mail_conn utl_smtp.connection;
BEGIN
mail_conn := utl_smtp.open_connection (mailhost, 25);
utl_smtp.helo (smtp_mail_conn, mailhost);
utl_smtp.mail (smtp_mail_conn, sender);
utl_smtp.rcpt (smtp_mail_conn, recipient);
utl_smtp.data (smtp_mail_conn, 'This is a test mail using UTL_SMTP '
chr(10));
utl_smtp.quit (smtp_mail_conn);
END;
/

DECLARE

*
ERROR at line 1:
ORA-24247: network access denied by access control list (ACL)
ORA-06512: at "SYS.UTL_TCP", line 17
ORA-06512: at "SYS.UTL_TCP", line 246
ORA-06512: at "SYS.UTL_SMTP", line 127
ORA-06512: at "SYS.UTL_SMTP", line 150
ORA-06512: at line 7

To resolve the issue user need to create ACL and grant required access, follow the below steps.

Step1:- Create New Access Control List

begin
dbms_network_acl_admin.create_acl (
acl => 'utl_smtp.xml',
description => 'Allow UTL_SMTP to send mails',
principal => 'TEST_USER',
is_grant => TRUE,
privilege => 'connect',
Start_Date => Null,
End_Date => Null);
end;

Step2:- Add privilege to Access control list

You can add the privilege like ‘resolve’ to the ACL.

begin
dbms_network_acl_admin.add_privilege (
acl => 'utl_smtp.xml',
principal => ‘TEST_USER’,
is_grant => TRUE,
privilege => 'resolve');
end;
/

Step3:- Assign Access control List

begin
dbms_network_acl_admin.assign_acl(
acl => 'utl_smtp.xml',
host => 'localsmtp.oracleracexpert.com',
lower_port => 25,
upper_port => NULL);
end;
/

Step4:- Check the permission

Check the required permission is granted to the user “TEST_USER” using below query

SQL> SELECT DECODE(
2 DBMS_NETWORK_ACL_ADMIN.check_privilege('utl_smtp.xml', 'TEST_USER', 'connect'),
3 1, 'GRANTED', 0, 'DENIED', NULL) as "Connect",
4 DECODE(
5 DBMS_NETWORK_ACL_ADMIN.check_privilege('utl_smtp.xml', 'TEST_USER', 'resolve'),
6 1, 'GRANTED', 0, 'DENIED', NULL) as "Resolve"
7 FROM dual;

Connect     Resolve
----------- -------
DENIED DENIED

The access is not granted and user still receives error “ORA-24247: network access denied by access control list (ACL)”.

You must “COMMIT” the changes in order to work the Network ACL’s.

Now user should be able to see the changes using below queries

SQL> SELECT DECODE(
2 DBMS_NETWORK_ACL_ADMIN.check_privilege('utl_smtp.xml', 'TEST_USER', 'connect'),
3 1, 'GRANTED', 0, 'DENIED', NULL) as "Connect",
4 DECODE(
5 DBMS_NETWORK_ACL_ADMIN.check_privilege('utl_smtp.xml', 'TEST_USER', 'resolve'),
6 1, 'GRANTED', 0, 'DENIED', NULL) as "Resolve"
7 FROM dual;

Connect      Resolve
------------ -------
GRANTED GRANTED

SQL> select * from dba_network_acls where acl like '%utl_smtp%%';

HOST LOWER_PORT UPPER_PORT ACL ACLID
------------------------ ---------- ---------- ------------------------------ ---------------------------------------------
localsmtp.oracleracexpert.com /sys/acls/utl_smtp.xml C6B2CCC62AC30707E04025AC80DA7FA3

Now user defined send_mail program is working fine.

DECLARE
mailhost VARCHAR2(64) := ‘localsmtp.oracleracexpert.com;
sender VARCHAR2(64) := 'fromuser@oracleracexpert.com';
recipient VARCHAR2(64) := 'touser@ oracleracexpert.com';
smtp_mail_conn utl_smtp.connection;
BEGIN
mail_conn := utl_smtp.open_connection (mailhost, 25);
utl_smtp.helo (smtp_mail_conn, mailhost);
utl_smtp.mail (smtp_mail_conn, sender);
utl_smtp.rcpt (smtp_mail_conn, recipient);
utl_smtp.data (smtp_mail_conn, 'This is a test mail using UTL_SMTP '
chr(10));
utl_smtp.quit (smtp_mail_conn);
END;
/
PL/SQL procedure successfully completed.

Manage the Network ACLs as below

Add a user or role to newly created Access control list (ACL) – Using ADD_PRIVILEGE procedure adding privilege to the user “SCOTT”

begin
dbms_network_acl_admin.add_privilege (
acl => 'utl_smtp.xml',
principal => ‘SCOTT’,
is_grant => TRUE,
privilege => 'connect');
end;
/

Remove a user or role to newly created Access control list (ACL) – Using DELETE_PRIVILEGE procedure deleting a privilege in an access control list from user “SCOTT”

begin
dbms_network_acl_admin.delete_privilege (
acl => 'utl_smtp.xml',
principal => ‘SCOTT’,
is_grant => FALSE,
privilege => 'connect');
end;
COMMIT;
/

Drop Access control list (ACL) – Using DROP_ACL procedure dropping an access control list (ACL).

begin
dbms_network_acl_admin.drop_acl (
acl => 'utl_smtp.xml');
COMMIT;
end;
/

Unassign Access control list (ACL) – Using UNASSIGN_ACL procedure un-assigning the access control list (ACL) from a host.

begin
dbms_network_acl_admin.unassign_acl (
acl => 'utl_smtp.xml',
host => 'hostname’);
COMMIT;
end;
/

You can query below views for ACL and privilege information

DBA_NETWORK_ACL_PRIVILEGES describes the network privileges defined in all access control lists that are currently assigned to network hosts.

DBA_NETWORK_ACLS describes the access control list assignments to network hosts.

Regards,
Satishbabu Gunukula
http://www.oracleracexpert.com

Tuesday, May 22, 2012

ORA-01427: single-row subquery returns more than one row

Everyday developers, testers and newbie’s face ORA-01427 error and I have seen many users looking for a solution for this error.

First let’s understand why users receive this error.

SQL> select count(*) from employee where employee_id = (select employee_id from salary where gross_sal < 5000 );
ERROR at line 1:
ORA-01427: single-row subquery returns more than one row

This error is raised when a sub-query returns more than one row.

Make sure you use multiple row sub query operator instead of single row sub-query operator to resolve the issue.

SQL> select count(*) from employee where employee_id in (select employee_id from salary where gross_sal < 5000 );

Now this query works fine.

Single row sub query operators are = (equal) , < (less than) , <=( less than or equal) , >(greater than) , >= (greater than or equal), <>(not equal ) ,!=(not equal)

Multiple row sub query operators are IN (equal to any member in the list), ANY (compare value to each value returned by the subquery), ALL (compare value to every value returned by the subquery)

Few guide lines for using Sub queries:
1. Use single-row operators with sing row sub queries
2. Use multiple-row operators with multiple row sub queries
3. Make sure you enclose sub queries in parentheses
4. Always keep sub queries on the right side of the comparison operator
5. You can use inline view to avoid ORA-01427 error, please refer http://docs.oracle.com/cd/E11882_01/server.112/e25554/qradv.htm#DWHSG08032

Regards
Satishbabu Gunukula
http://www.oracleracexpert.com/

Thursday, February 16, 2012

How to Deploy and Un-deploy Oracle Agile Application

Whenever you are applying the patches to Oracle Agile environment, you need to Un-deploy and deploy the application.

Before you apply the patch you must Un-deploy the Agile application. After successful installation of the patch you must deploy the agile application in order to take effect of the applied patch.

Un-Deploy Agile application:-Go to Agile home directory and run below command
$ cd $/agileDomain/bin
$./ UndeployAgilePLM.sh

Where password is the oc4jadmin user password

12/02/09 14:04:10 Notification ==>Application UnDeployer for Agile STARTS.
12/02/09 14:04:11 Notification ==>Removing all web binding(s) for application Agile from all web site(s)
12/02/09 14:04:19 Notification ==>Application UnDeployer for Agile COMPLETES.

Follow the steps to apply a Patch in Oracle Agile environment
1. Check PMN processes are running on the Agile Server.

2. Stop the OPMN processes
$ opmnctl stopall

3. Unzip the patch to a temporary directory
For Unix
$/tmp//Install_Patch.sh
For Windows
C:\temp\\Install_Patch.bat

You will get a message “Is the Agile Application already undeployed? (y/n) “. You must enter Y inorder to proceed further.

Ignore the message "Enter Passphrase for keystore:" and let the installation continue

When the installation is completed, the “INSTALLATION SUCCESSFUL” message will appear and press the return key to complete the installation.

4. Start OPMN processes
$ opmnctl startall

Deploy Agile application:-After successful installation of the patch deploy the Agile application

$ cd $/agileDomain/bin
$./DeployAgilePLM.sh

Where password is the oc4jadmin user password
12/02/09 14:06:50 Notification ==>Application Deployer for Agile STARTS.
………………………
……………………….
12/02/09 14:07:35 Notification ==>Binding web application(s) to site default-web-site ends...

12/02/09 14:07:35 Notification ==>Application Deployer for Agile COMPLETES. Operation time: 45434 msecs

Check the status of the agile application
$ opmnctl status

Make sure to check applied patch from application. If Deploy and Un-deploys fails with some reason then you will not see the applied patch in Application.

. Launch the application and login
. Click on help --> About Agile
. You should see the patch number under “updated versions”

Regards,
Satishbabu Gunukula
http://www.oracleracexpert.com

Tuesday, January 26, 2010

Oracle RAC load balancing and failover

LOAD BALANCING: The Oracle RAC system can distribute the load over many nodes this feature called as load balancing.

There are two methods of load balancing
1.Client load balancing
2.Server load balancing

Client Load Balancing distributes new connections among Oracle RAC nodes so that no one server is overloaded with connection requests and it is configured at net service name level by providing multiple descriptions in a description list or multiple addresses in an address list. For example, if connection fails over to another node in case of failure, the client load balancing ensures that the redirected connections are distributed among the other nodes in the RAC.

Configure Client-side connect-time load balancing by setting LOAD_BALANCE=ON in the corresponding client side TNS entry.

TESTRAC =
(DESCRIPTION =
(ADDRESS_LIST=
(LOAD_BALANCE = ON)
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC1-VIP)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC2-VIP)(PORT = 1521))
)
(CONNECT_DATA = (SERVICE_NAME = testdb.oracleracexpert.com))
)

Server Load Balancing distributes processing workload among Oracle RAC nodes. It divides the connection load evenly between all available listeners and distributes new user session connection requests to the least loaded listener(s) based on the total number of sessions which are already connected. Each listener communicates with the other listener(s) via each database instance’s PMON process.

Configure Server-side connect-time load balancing feature by setting REMOTE_LISTENERS initialization parameter of each instance to a TNS name that describes list of all available listeners.

TESTRAC_LISTENERS =
(DESCRIPTION =
(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC1)(PORT = 1521)))
(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC2)(PORT = 1521))))
)

Set *.remote_listener= TESTRAC_LISTENERS’ initialization parameter in the database’s shared SPFILE and add TESTRAC_LISTENERS’ entry to the TNSNAMES.ORA file in the Oracle Home of each node in the cluster.

Once you configure Server-side connect-time load balancing, each database’s PMON process will automatically register the database with the database’s local listener as well as cross-register the database with the listeners on all other nodes in the cluster. Now the nodes themselves decide which node is least busy, and then will connect the client to that node.

FAILOVER:

The Oracle RAC system can protect against failures caused by O/S or server crashes or hardware failures. When a node failure occurs in RAC system, the connection attempts can fail over to other surviving nodes in the cluster this feature called as Failover.

There are two methods of failover
1. Connection Failover
2. Transparent Application Failover (TAF)

Connection Failover - If a connection failure occurs at connect time, the application failover the connection to another active node in the cluster. This feature enables client to connect to another listener if the initial connection to the first listener fails.

Enable client-side connect-time Failover by setting FAILOVER=ON in the corresponding client side TNS entry.

TESTRAC =
(DESCRIPTION =
(ADDRESS_LIST=
(LOAD_BALANCE = ON)
(FAILOVER = ON)
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC1-VIP)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC2-VIP)(PORT = 1521))
)
(CONNECT_DATA = (SERVICE_NAME = testdb.oracleracexpert.com))
)

If LOAD_BALANCE is set to on then clients randomly attempt connections to any nodes. If client made connection attempt to a down node, the client needs to wait until it receives the information that the node is not accessible before trying alternate address in ADDRESS_LIST.

Transparent application Failover (TAF) – If connection failure occurs after a connection is established, the connection fails over to other surviving nodes. Any uncommitted transactions are rolled back and server side program variables and session properties will be lost. In some case the select statements automatically re-executed on the new connection with the cursor positioned on the row on which it was positioned prior to the failover.

TESTRAC =
(DESCRIPTION =
(LOAD_BALANCE = ON)
(FAILOVER = ON)
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC1-VIP)(PORT = 1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = TESTRAC1-VIP)(PORT = 1521))
(CONNECT_DATA =
(SERVICE_NAME = testdb.oracleracexpert.com)
(FAILOVER_MODE = (TYPE = SELECT)(METHOD = BASIC)(RETRIES = 180)(DELAY = 5))
)
)

Regards,
Satishbabu Gunukula
http://www.oracleracexpert.com

Delete duplicate rows from Oracle Table:

There are several techniques to delete duplicate rows from a table, but the most effective way is to join the table against itself. Always make sure to select the duplicate data before you delete using below queries.


1. Delete duplicate rows based on one column value using ROWID

SQL> delete from dup_table t1 where rowid > ( select min(rowid) from dup_table t2 where t1.ename = t2.ename);

-- or --
SQL> delete from dup_table t1 where rowid < ( select max(rowid) from dup_table t2 where t1.ename = t2.ename);


2. Use the below query to delete the rows suing Oracle analytic functions

SQL> Delete from dup_table

where rowid in ( select rowid from

( select rowid , row_number() over (partition by col1 order by upper col1 ) row_num from dup_table ) where rno > 1 );


3. You must specify all columns that make the row duplicate in the query, use the below query to delete duplicate records based on two columns or composite unique key

SQL> delete from dup_table t1

where rowid > (select min(rowid) from dup_table t2

where upper(t2.col1) = upper(t1.col1)

and upper(t2.col2) = upper(t1.col2)

);

-- or --

SQL> delete from dup_table t1

where rowid < (select max(rowid) FROM dup_table t2

where t1.col1=t2.col1 AND t1.col2=t2.col2 );

-- or --

SQL> delete from dup_table t1

where rowid <> ( select max(rowid) from dup_table t2

where t2.col1 = t1.col1

and t2.col2 = t1.col2 )


4. If the fields match on the NULL value then duplicate fails to remove the duplicate rows. In this situation add a null check

SQL> delete from dup_table t1
where t1.rowid > ANY (select t2.rowid FROM dup_table t2
where (t1.col1 = t2.col1 OR (t1.col1 is null AND t2.col1 is null))
and
(t1.col2 = t2.col2 OR (t1.col2 is null AND t2.col2 is null))
);

If the table contains duplicate data in upper case and lower case, use below query to delete to delete the data

SQL> delete from dup_table

where rowid in ( select rid from ( select rowid rid, row_number() over (partition by upper(col1) order by upper(col2)) rno from dup_table )

where rno > 1

);


Regards,
Satishbabu Gunukula
http://www.oracleracexpert.com