Thursday, December 3, 2026

Does Oracle GoldenGate Replication Work Without TRANDATA Being Enabled at the Table Level?

Introduction

Have you ever wondered whether Oracle GoldenGate replication can work without enabling TRANDATA on individual source tables?

The answer is Yes, but it depends on the level of supplemental logging enabled at the database level and the type of DML operation being performed.

Oracle GoldenGate relies on supplemental logging to capture sufficient information from redo logs to identify and replicate changes accurately.

When database-level supplemental logging is enabled for Primary Keys, Unique Keys, Foreign Keys, or ALL columns, table-level supplemental logging may not be required for the corresponding logging information.

However, enabling extensive supplemental logging at the database level can generate additional redo and introduce performance overhead.

Oracle generally recommends enabling minimal supplemental logging at the database level and enabling the required key-column logging at the table level through GoldenGate ADD TRANDATA.

In this article, we will perform a practical demonstration to understand how GoldenGate behaves when table-level TRANDATA is removed while only minimal supplemental logging is enabled at the database level.

We will test three different DML operations:

  1. INSERT

  2. DELETE

  3. UPDATE

Let's see what happens!

1. Understanding Database-Level Supplemental Logging

Before starting the demonstration, let's understand how to check the supplemental logging configuration.

For a Non-CDB Database

Execute the following query:

SELECT supplemental_log_data_min MIN,
       supplemental_log_data_pk  PK,
       supplemental_log_data_ui  UI,
       supplemental_log_data_fk  FK,
       supplemental_log_data_all "ALL"
FROM v$database;

For a Multitenant Database (CDB/PDB)

To check the database-level supplemental logging configuration across containers, execute:

SELECT *
FROM cdb_supplemental_logging;

Alternatively, when connected directly to a PDB:

SELECT *
FROM dba_supplemental_logging;

When database-wide supplemental logging is enabled for Primary Keys, Unique Keys, Foreign Keys, or ALL columns, the corresponding logging information can be available without separately enabling table-level supplemental logging.

However, minimal supplemental logging alone does not guarantee that all the key-column information required by GoldenGate will be captured.

This distinction is important and will become clear during our UPDATE test.

2. Environment Configuration

For this demonstration, we will use the following Oracle GoldenGate configuration.

ComponentSourceTarget
Hostnameora-prod01ora-standby01
CDBPRODCDBSTBYCDB
PDBSALESPDBDRSALESPDB
SchemaSALESAPPDRSALES
TablePRODUCT_MASTERPRODUCT_MASTER

Source GoldenGate Process Status

Let's first verify the existing Extract and Pump processes.

GGSCI> INFO ALL

Program     Status      Group
MANAGER     RUNNING
EXTRACT     RUNNING     EXT_SALES
EXTRACT     RUNNING     PMP_SALES

Target GoldenGate Process Status

Similarly, verify the Replicat process on the target.

GGSCI> INFO ALL

Program     Status      Group
MANAGER     RUNNING
REPLICAT    RUNNING     REP_SALES

Verify Database Supplemental Logging

In our environment, only minimal supplemental logging is enabled at both the CDB and PDB levels.

Connect to the source database:

sqlplus / as sysdba

Check the database name:

SELECT name FROM v$database;

Example:

NAME
---------
PRODCDB

Check the available PDBs:

SHOW PDBS;

Now check supplemental logging:

SELECT *
FROM CDB_SUPPLEMENTAL_LOGGING;

Example output:

MIN PRI UNI FOR ALL PRO CON_ID
--- --- --- --- --- --- ----------
YES NO  NO  NO  NO  NO       1
YES NO  NO  NO  NO  NO       3

As we can see, only MIN supplemental logging is enabled at the CDB and PDB levels.

Primary Key, Unique Key, Foreign Key, and ALL supplemental logging are disabled.

3. Disable Table-Level TRANDATA

Now let's check the existing supplemental logging configuration for our source table.

Connect to the source GoldenGate environment:

GGSCI> INFO TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Example output:

Oracle Goldengate support native capture
on table SALESAPP.PRODUCT_MASTER.

Oracle Goldengate marked following column
as key columns:
PRODUCT_ID.

Logging of supplemental redo log data is enabled
for table SALESPDB.SALESAPP.PRODUCT_MASTER.

Columns supplementally logged:
"PRODUCT_ID".

Now remove the table-level supplemental logging:

GGSCI> DELETE TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Verify the configuration again:

GGSCI> INFO TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Expected output:

Oracle Goldengate support native capture
on table SALESAPP.PRODUCT_MASTER.

Oracle Goldengate marked following column
as key columns:
PRODUCT_ID.

Logging of supplemental redo log data is disabled
for table SALESPDB.SALESAPP.PRODUCT_MASTER.

Now table-level TRANDATA is disabled.

Our database still has minimal supplemental logging enabled.

Let's test how GoldenGate behaves with different DML operations.

4. Testing DML Operations Without TRANDATA

Test 1: INSERT Operation

Connect to the source PDB:

sqlplus salesapp@SALESPDB

Check the existing table records:

SELECT *
FROM product_master;

Example output:

PRODUCT_ID PRODUCT_NAME       LOCATION
---------- ------------------ ----------
101        LAPTOP             DELHI
102        DESKTOP            MUMBAI
103        SERVER             BANGALORE

Now execute an INSERT statement:

INSERT INTO product_master
VALUES (104, 'WORKSTATION', 'NOIDA');

COMMIT;

Verify the source table:

SELECT *
FROM product_master;

The new record should now be visible.

Check Replicat Statistics

Connect to the target GoldenGate environment:

GGSCI> STATS REP_SALES HOURLY

Example output:

Replicating from SALESPDB.SALESAPP.PRODUCT_MASTER
to DRSALESPDB.DRSALES.PRODUCT_MASTER:

Total inserts       1.00
Total updates       0.00
Total deletes       0.00
Total discards      0.00
Total operations    1.00

The INSERT operation has been successfully replicated.

Verify the Target Table

Connect to the target PDB:

sqlplus drsales@DRSALESPDB

Execute:

SELECT *
FROM product_master;

Example output:

PRODUCT_ID PRODUCT_NAME       LOCATION
---------- ------------------ ----------
101        LAPTOP             DELHI
102        DESKTOP            MUMBAI
103        SERVER             BANGALORE
104        WORKSTATION        NOIDA

Result: INSERT replication works successfully without table-level TRANDATA in this test environment.

Test 2: DELETE Operation

Now let's test a DELETE operation.

Connect to the source PDB and execute:

DELETE FROM product_master
WHERE product_id = 104;

COMMIT;

Check Replicat statistics:

GGSCI> STATS REP_SALES HOURLY

Example output:

Replicating from SALESPDB.SALESAPP.PRODUCT_MASTER
to DRSALESPDB.DRSALES.PRODUCT_MASTER:

Total inserts       1.00
Total updates       0.00
Total deletes       1.00
Total discards      0.00
Total operations    2.00

The DELETE operation has also been successfully captured and replicated.

Verify the target table:

SELECT *
FROM product_master;

Example output:

PRODUCT_ID PRODUCT_NAME       LOCATION
---------- ------------------ ----------
101        LAPTOP             DELHI
102        DESKTOP            MUMBAI
103        SERVER             BANGALORE

Result: DELETE replication also works successfully without table-level TRANDATA in this test environment.

Test 3: UPDATE Operation

Now comes the interesting part!

Let's execute an UPDATE statement on the source table.

UPDATE product_master
SET product_name = 'ENTERPRISE_SERVER'
WHERE product_id = 103;

COMMIT;

The source database successfully executes the UPDATE.

However, when we check the target Replicat process, we notice something unexpected.

Check the Replicat statistics:

GGSCI> STATS REP_SALES HOURLY

Example output:

ERROR OGG-15148
REPLICAT REP_SALES not currently running.

Now check the process status:

GGSCI> INFO ALL

Output:

Program     Status      Group
MANAGER     RUNNING
REPLICAT    ABENDED     REP_SALES

Our Replicat process has ABENDED!

Check the Replicat Report File

Let's investigate the Replicat report file.

Example error messages:

WARNING OGG-01431
Aborted grouped transaction on
DRSALESPDB.DRSALES.PRODUCT_MASTER,
Mapping error.

WARNING OGG-01003
Repositioning to rba in trail file.

WARNING OGG-01151
Error mapping from
SALESPDB.SALESAPP.PRODUCT_MASTER
to
DRSALESPDB.DRSALES.PRODUCT_MASTER.

The UPDATE operation could not be successfully applied to the target.

Why Did INSERT and DELETE Work but UPDATE Failed?

This is where supplemental logging becomes important.

An INSERT operation introduces a new row, while a DELETE operation removes an existing row. In our test, GoldenGate successfully handled both operations.

An UPDATE operation is different.

When an UPDATE statement modifies only one column, Oracle's redo information does not necessarily contain the complete identifying key information required by GoldenGate to locate the corresponding target row.

In our example:

UPDATE product_master
SET product_name = 'ENTERPRISE_SERVER'
WHERE product_id = 103;

Only PRODUCT_NAME is modified.

Without the required supplemental logging, the primary key PRODUCT_ID may not be available in the redo information in the form needed by GoldenGate.

As a result, Replicat cannot reliably identify the target row and encounters a mapping error.

This is why enabling table-level supplemental logging through ADD TRANDATA is important.

5. Resolution: Re-enable Table-Level TRANDATA

Now let's resolve the issue.

Step 1: Enable TRANDATA Again

Connect to the source GoldenGate environment.

First verify the current status:

GGSCI> INFO TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Enable table-level supplemental logging:

GGSCI> ADD TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Example output:

INFO OGG-15132
Logging of supplemental redo data enabled.

INFO OGG-15133
TRANDATA for scheduling columns has been added.

INFO OGG-15135
TRANDATA for instantiation CSN has been added.

Verify the configuration:

GGSCI> INFO TRANDATA SALESPDB.SALESAPP.PRODUCT_MASTER

Now supplemental logging should be enabled for the table, including its primary key column.

Step 2: Stop the Source Extract

For this demonstration, we will stop the source Extract before performing the next UPDATE operation.

GGSCI> STOP EXT_SALES

Verify:

GGSCI> INFO ALL

Step 3: Execute Another UPDATE

Connect to the source PDB:

UPDATE product_master
SET product_name = 'DATABASE_SERVER'
WHERE product_id = 103;

COMMIT;

The transaction is now generated after table-level supplemental logging has been enabled.

Step 4: Perform Trail Rollover

For this demonstration, we will perform a trail rollover and reposition the downstream readers to the appropriate new trail sequence.

First, verify the existing trail files:

GGSCI> SH LS -LRT ./dirdat/et*

Perform trail rollover:

GGSCI> ALTER EXT_SALES ETROLLOVER

Restart the Extract:

GGSCI> START EXT_SALES

Verify:

GGSCI> INFO ALL

A new trail file should now be created.

Check the Extract statistics:

GGSCI> STATS EXT_SALES HOURLY

Confirm that the latest UPDATE transaction has been captured.

Step 5: Reposition the Data Pump

Now stop the existing Pump process:

GGSCI> STOP PMP_SALES

Reposition it to the appropriate new Extract trail sequence.

For example, if the new trail sequence is 3:

GGSCI> ALTER PMP_SALES EXTSEQNO 3 EXTRBA 0

Start the Pump:

GGSCI> START PMP_SALES

Verify:

GGSCI> INFO ALL

Note: The sequence number above is illustrative. Always identify the actual trail sequence and reader position before repositioning. Do not skip transactions that must be delivered to the target.

Step 6: Reposition and Restart Replicat

Now move to the target GoldenGate environment.

Check the target trail files:

GGSCI> INFO ALL

Inspect the available remote trail sequences:

GGSCI> SH LS -LRT ./dirdat/rt*

If the appropriate new remote trail sequence is 2, the example repositioning command is:

GGSCI> ALTER REP_SALES EXTSEQNO 2 EXTRBA 0

Start Replicat:

GGSCI> START REP_SALES

Verify:

GGSCI> INFO ALL

Expected output:

Program     Status      Group
MANAGER     RUNNING
REPLICAT    RUNNING     REP_SALES

Monitor the Replicat report and statistics to confirm successful application of the UPDATE.

Step 7: Verify the Final Result

Connect to the target PDB:

sqlplus drsales@DRSALESPDB

Execute:

SELECT *
FROM product_master;

Expected output:

PRODUCT_ID PRODUCT_NAME       LOCATION
---------- ------------------ ----------
101        LAPTOP             DELHI
102        DESKTOP            MUMBAI
103        DATABASE_SERVER    BANGALORE

The UPDATE operation has now been successfully replicated after enabling table-level TRANDATA.

6. Summary: INSERT vs DELETE vs UPDATE Without TRANDATA

Based on our demonstration, here is the final comparison.

DML OperationWithout Table TRANDATAReplicat Status
INSERTSuccessfulRUNNING
DELETESuccessful in this testRUNNING
UPDATEFailed (OGG-01151)ABENDED

The important observation is that minimal supplemental logging at the database level does not provide all the information required for reliable UPDATE replication in this scenario.

7. Key Takeaways

  1. GoldenGate replication behavior depends on the supplemental logging configuration at both database and table levels.

  2. Minimal supplemental logging alone does not guarantee that primary key columns are supplementally logged for every table.

  3. INSERT operations worked successfully in our demonstration without table-level TRANDATA.

  4. DELETE operations also worked successfully in our demonstration.

  5. UPDATE operations failed because GoldenGate did not have the required key-column information to identify the target row.

  6. Enabling ADD TRANDATA ensures that the required key-column information is available for GoldenGate replication.

  7. Always verify the actual redo logging and GoldenGate report before making assumptions about replication behavior.

Conclusion

Can Oracle GoldenGate replication work without enabling table-level TRANDATA?

Yes, in certain scenarios. But should we rely on it in a production environment? Definitely not without understanding the supplemental logging requirements.

Our demonstration clearly shows that INSERT and DELETE operations were successfully replicated with only minimal supplemental logging, whereas the UPDATE operation caused Replicat to ABEND.

The safest and recommended approach is to enable minimal supplemental logging at the database level and use GoldenGate ADD TRANDATA to enable the required supplemental logging at the individual table level.

This ensures that GoldenGate has the necessary key-column information to identify and replicate row changes reliably.

Remember: Successful INSERT and DELETE replication does not necessarily mean your GoldenGate supplemental logging configuration is complete. Always test UPDATE operations as well!

How to Add an Existing Table with Data to an Running Oracle GoldenGate Extract and Replicat Without HANDLECOLLISIONS

 

Introduction

In an Oracle GoldenGate replication environment, we sometimes need to add a new table to an existing Extract, Data Pump, and Replicat configuration.

The challenge becomes more interesting when the table already contains millions of records and is actively receiving INSERT, UPDATE, and DELETE operations.

A common approach is to use HANDLECOLLISIONS while performing the initial load and starting replication. However, when both source and target databases are Oracle, we can leverage Oracle SCNs (System Change Numbers) to achieve a consistent initial load and synchronize subsequent transactions without relying on HANDLECOLLISIONS.

In this article, I will demonstrate how to add an existing table containing one million records to an already running Oracle GoldenGate replication environment.

The entire procedure will be performed without taking the source database offline. However, we will temporarily stop the target Replicat process during the initial load.

We will use Oracle Data Pump with FLASHBACK_SCN to maintain data consistency between the source and target.

1. Environment Details

For this demonstration, we will use the following configuration.

ComponentSourceTarget
Hostnameora-src01ora-dr01
CDBFINCDBDRFINCDB
PDBFINPDBDRPDB
SchemaFINAPPDRAPP
TableCUSTOMER_TXNCUSTOMER_TXN
ExtractEXT_FIN-
PumpPMP_FIN-
Replicat-REP_FIN

Objective: Add the existing FINAPP.CUSTOMER_TXN table to the current GoldenGate replication configuration and replicate it to DRAPP.CUSTOMER_TXN.

2. Create the Table and Populate Initial Data on Source

First, connect to the source PDB and create a table.

sqlplus finapp@FINPDB

Create the table:

CREATE TABLE finapp.customer_txn
(
    txn_id      NUMBER(10),
    customer_name VARCHAR2(50),
    txn_date    DATE,
    amount      NUMBER(12,2),
    CONSTRAINT pk_customer_txn
        PRIMARY KEY (txn_id)
);

Create a sequence:

CREATE SEQUENCE finapp.seq_customer_txn
MINVALUE 1
MAXVALUE 999999999999999
START WITH 1
INCREMENT BY 1
CACHE 100;

Now populate the table with one million records.

DECLARE
    i NUMBER;
BEGIN
    FOR i IN 1..1000000 LOOP

        INSERT INTO finapp.customer_txn
        VALUES
        (
            finapp.seq_customer_txn.NEXTVAL,
            'CUSTOMER_' || MOD(i,1000),
            SYSDATE,
            ROUND(DBMS_RANDOM.VALUE(100,50000),2)
        );

        COMMIT;
    END LOOP;
END;
/

Verify the record count:

SELECT COUNT(*)
FROM finapp.customer_txn;

Expected output:

  COUNT(*)
----------
   1000000

At this point, we have an existing table with one million records.

For this demonstration, assume the application continues performing transactions on this table while we configure GoldenGate.

3. Enable Supplemental Logging for the New Table

Before adding the table to the Extract configuration, enable supplemental logging.

Connect to the source database using GGSCI.

[oracle@ora-src01 ~]$ . ./setgg_src
[oracle@ora-src01 ~]$ ./ggsci

Connect to the source CDB:

GGSCI> DBLOGIN USERIDALIAS GG_SRC_CDB

Add TRANDATA:

GGSCI> ADD TRANDATA FINPDB.FINAPP.CUSTOMER_TXN

Verify the configuration:

GGSCI> INFO TRANDATA FINPDB.FINAPP.CUSTOMER_TXN

Confirm that supplemental logging is enabled and that the primary key TXN_ID is identified as the key column.

Important: Ensure that supplemental logging is enabled before establishing the initial-load SCN.

4. Update Extract and Pump Parameter Files

Now we need to include the new table in the existing Extract and Pump parameter files.

Check the current GoldenGate processes:

GGSCI> INFO ALL

Example:

Program     Status      Group
MANAGER     RUNNING
EXTRACT     RUNNING     EXT_FIN
EXTRACT     RUNNING     PMP_FIN

Update Extract Parameter File

Edit the existing Extract parameter file:

GGSCI> EDIT PARAM EXT_FIN

Add the new table:

EXTRACT EXT_FIN
USERIDALIAS GG_SRC_CDB

TRANLOGOPTIONS INTEGRATEDPARAMS (MAX_SGA_SIZE 128)

EXTTRAIL ./dirdat/et

TABLE FINPDB.FINAPP.DEPARTMENTS;
TABLE FINPDB.FINAPP.EMPLOYEES;
TABLE FINPDB.FINAPP.CUSTOMER_TXN;

Update Pump Parameter File

Edit the existing Pump parameter file:

GGSCI> EDIT PARAM PMP_FIN

Add the same table:

EXTRACT PMP_FIN

RMTHOST ora-dr01, MGRPORT 7811

RMTTRAIL ./dirdat/rt

TABLE FINPDB.FINAPP.DEPARTMENTS;
TABLE FINPDB.FINAPP.EMPLOYEES;
TABLE FINPDB.FINAPP.CUSTOMER_TXN;

Note: The connection configuration shown here assumes the integrated Extract connects using the appropriate source CDB-level credentials and the Pump forwards the captured trail records.

Restart Extract and Pump

Restart the Extract process so that the updated table list is loaded:

GGSCI> STOP EXT_FIN
GGSCI> START EXT_FIN

Similarly, restart the Pump:

GGSCI> STOP PMP_FIN
GGSCI> START PMP_FIN

Verify:

GGSCI> INFO ALL

Ensure both Extract and Pump are running.

5. Stop the Target Replicat Process

Before performing the initial load, stop the existing Replicat process.

Important: Do not start Replicat until the initial table import has completed and the CSN filter has been configured.

Connect to the target GoldenGate environment:

[oracle@ora-dr01 ~]$ ./ggsci

Check the process:

GGSCI> INFO ALL

Stop Replicat:

GGSCI> STOP REP_FIN

Verify:

GGSCI> INFO ALL

Expected status:

Program     Status      Group
MANAGER     RUNNING
REPLICAT    STOPPED     REP_FIN

The source database and its application transactions continue running. The target Replicat is temporarily stopped.

6. Capture the Current SCN on Source

This is the most important step in the entire procedure.

We need to capture the current SCN before exporting the table.

Connect to the source PDB:

sqlplus system@FINPDB

Verify the current container:

SHOW CON_NAME;

Capture the SCN:

SELECT CURRENT_SCN
FROM V$DATABASE;

Example output:

CURRENT_SCN
-----------
  8456210

For this demonstration, we will use:

FLASHBACK_SCN = 8456210

Save this SCN carefully. We will use exactly the same SCN during the Data Pump export and in the Replicat filtering condition.

7. Create an Oracle Directory for Data Pump

Create a directory on the source database:

CREATE OR REPLACE DIRECTORY PUMP_DIR
AS '/backup/fin_export';

Grant the required directory privileges to the Data Pump user if necessary.

GRANT READ, WRITE ON DIRECTORY PUMP_DIR TO SYSTEM;

Ensure the Oracle database software owner has the required operating-system permissions on the directory.

8. Export the Table Using FLASHBACK_SCN

Now export the table using Oracle Data Pump.

expdp system@FINPDB \
directory=PUMP_DIR \
dumpfile=customer_txn.dmp \
logfile=customer_txn_exp.log \
tables=FINAPP.CUSTOMER_TXN \
flashback_scn=8456210

The FLASHBACK_SCN parameter ensures that the export represents the table's data as of the specified SCN, even if the application continues modifying the table during the export.

Example output:

Starting "SYSTEM"."SYS_EXPORT_TABLE_01":

Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Processing object type TABLE_EXPORT/TABLE/INDEX/INDEX
Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/CONSTRAINT

. . exported "FINAPP"."CUSTOMER_TXN"
    35.50 MB 1000000 rows

Job "SYSTEM"."SYS_EXPORT_TABLE_01"
successfully completed.

Once the export completes, copy the dump file to the target server.

scp customer_txn.dmp oracle@ora-dr01:/backup/fin_import/

9. Import the Table into the Target PDB

Connect to the target database and create the Data Pump directory.

sqlplus system@DRPDB
CREATE OR REPLACE DIRECTORY PUMP_DIR
AS '/backup/fin_import';

Grant the required privileges if necessary.

GRANT READ, WRITE ON DIRECTORY PUMP_DIR TO SYSTEM;

Now import the table using schema remapping.

impdp system@DRPDB \
directory=PUMP_DIR \
dumpfile=customer_txn.dmp \
logfile=customer_txn_imp.log \
remap_schema=FINAPP:DRAPP \
transform=SEGMENT_ATTRIBUTES:N

The REMAP_SCHEMA parameter imports the source table into the target schema.

Example output:

Starting "SYSTEM"."SYS_IMPORT_TABLE_01":

Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA

. . imported "DRAPP"."CUSTOMER_TXN"
    35.50 MB 1000000 rows

Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/CONSTRAINT

Job "SYSTEM"."SYS_IMPORT_TABLE_01"
successfully completed.

Verify the target table:

SELECT COUNT(*)
FROM drapp.customer_txn;

Expected output:

  COUNT(*)
----------
   1000000

At this point, the target has a consistent copy of the source table as of SCN 8456210.

10. Update the Replicat Parameter File with a CSN Filter

Now comes the most important part of the synchronization process.

The target table already contains all the records committed up to the export SCN.

However, the Extract and Pump have also been capturing ongoing transactions.

If we start Replicat without any filtering, it may attempt to apply transactions that are already present in the initial imported data.

This can result in duplicate key errors.

To avoid this, we will configure a CSN filter in the Replicat parameter file.

Edit the existing Replicat parameter file:

GGSCI> EDIT PARAM REP_FIN

Example configuration:

REPLICAT REP_FIN

USERIDALIAS GG_TGT_PDB

DBOPTIONS INTEGRATEDPARAMS (parallelism 3)

ASSUMETARGETDEFS

MAP FINPDB.FINAPP.DEPARTMENTS,
    TARGET DRPDB.DRAPP.DEPARTMENTS;

MAP FINPDB.FINAPP.EMPLOYEES,
    TARGET DRPDB.DRAPP.EMPLOYEES;

MAP FINPDB.FINAPP.CUSTOMER_TXN,
    TARGET DRPDB.DRAPP.CUSTOMER_TXN,
    FILTER (@GETENV('TRANSACTION', 'CSN') > 8456210);

Let's understand the filter:

FILTER (@GETENV('TRANSACTION', 'CSN') > 8456210)

It instructs Replicat to apply only transactions with a CSN greater than 8456210 for this table.

Transactions represented in the initial Data Pump export are therefore excluded from subsequent replication.

Transactions committed after the captured SCN are applied through GoldenGate.

Important: The SCN used in this filter must be exactly the same SCN used in the Data Pump export.

Also, ensure that the CSN filter is scoped only to the newly added table and that the deployed GoldenGate version supports the parameter syntax being used.

11. Start Replicat

Once the import has completed successfully and the Replicat parameter file has been updated, start Replicat.

GGSCI> START REP_FIN

Check the status:

GGSCI> INFO ALL

Expected output:

Program     Status      Group
MANAGER     RUNNING
REPLICAT    RUNNING     REP_FIN

Monitor the Replicat report and discard/error logs to ensure that transactions are being applied successfully.

12. Verify Replication by Performing DML Operations

Now let's validate the complete configuration.

Connect to the source database:

sqlplus finapp@FINPDB

Check the existing record count:

SELECT COUNT(*)
FROM finapp.customer_txn;

Expected:

COUNT(*)
----------
1000000

Insert two new records:

INSERT INTO finapp.customer_txn
VALUES
(
    finapp.seq_customer_txn.NEXTVAL,
    'NEW_CUSTOMER_1',
    SYSDATE,
    15000
);

INSERT INTO finapp.customer_txn
VALUES
(
    finapp.seq_customer_txn.NEXTVAL,
    'NEW_CUSTOMER_2',
    SYSDATE,
    25000
);

COMMIT;

Verify the source:

SELECT COUNT(*)
FROM finapp.customer_txn;

Expected:

COUNT(*)
----------
1000002

Now connect to the target database:

sqlplus drapp@DRPDB

Check the target record count:

SELECT COUNT(*)
FROM drapp.customer_txn;

Expected:

COUNT(*)
----------
1000002

Verify the newly inserted records:

SELECT *
FROM drapp.customer_txn
WHERE customer_name LIKE 'NEW_CUSTOMER%';

You should see both newly inserted records on the target.

You can also test UPDATE and DELETE operations on the source table and verify that those changes are reflected on the target.

13. Final Result

We have successfully added an existing table containing one million records to an already running Oracle GoldenGate replication environment.

The process was completed without taking the source database offline and without using HANDLECOLLISIONS.

The key to achieving this was using the same SCN for both the initial Data Pump export and the Replicat CSN filter.

Conclusion

Adding an existing table to an active Oracle GoldenGate replication environment requires careful coordination between the initial data load and ongoing transaction replication.

Instead of depending on HANDLECOLLISIONS, we can use Oracle's native SCN-based consistency mechanism.

The overall approach is:

  1. Enable supplemental logging for the new table.

  2. Add the table to the existing Extract and Pump configurations.

  3. Restart the relevant capture and Pump processes.

  4. Stop the target Replicat.

  5. Capture the current source SCN.

  6. Export the table using FLASHBACK_SCN.

  7. Import the table into the target PDB.

  8. Configure the Replicat CSN filter using the same SCN.

  9. Start Replicat and validate data synchronization.

This approach provides a controlled way to introduce an existing table into an active GoldenGate replication environment without requiring source database downtime.

The key takeaway: Use FLASHBACK_SCN for the initial load and the corresponding CSN filter for subsequent replication. This allows us to synchronize existing data and ongoing transactions without relying on HANDLECOLLISIONS.

Wednesday, December 2, 2026

Does Dropping a PDB on the Primary Automatically Drop It on the Physical Standby?

Introduction

Managing Pluggable Databases (PDBs) in an Oracle Multitenant environment is relatively straightforward. However, when Oracle Data Guard is configured, even a simple operation such as dropping a PDB requires additional consideration.

One common question Oracle DBAs encounter is:

If we drop a Pluggable Database (PDB) from the Primary database, will Oracle automatically drop the same PDB from the Physical Standby database?

The answer depends on the Oracle Database version and, in certain releases, the open mode of the PDB on the standby database.

In Oracle Database 19c, redo apply can automatically handle PDB drop operations, including closing an open standby PDB when necessary. However, older 12c releases have additional considerations.

In this article, we'll perform a practical demonstration using Oracle Database 19c and Data Guard to understand what happens when a PDB is dropped from the primary database under two different standby configurations.

We'll cover:

  • How PDB drop operations propagate through redo.

  • What happens when the standby PDB is in MOUNTED mode.

  • What happens when the standby PDB is open in READ ONLY mode.

  • How MRP handles PDB drop markers.

  • How to troubleshoot ORA-65112.

  • Differences between Oracle 12c and 19c.

  • Manual recovery considerations for older releases.

1. Understanding the Lab Environment

For this demonstration, I'm using Oracle Database 19c with a Primary and Physical Standby configuration.

To make the example easy to follow, I've used separate CDB names, DB unique names, hostnames, and PDB names.

Data Guard Configuration

ParameterPrimaryPhysical Standby
Hostnameora19c-pri01ora19c-stby01
CDB NamePRODDBPRODDB
DB Unique NamePRODDBPRODDB_STBY
Database RolePRIMARYPHYSICAL STANDBY
Open ModeREAD WRITEMOUNTED
Database Version19c19c

PDB Configuration

Our primary database contains two application PDBs:

  • SALES_PDB

  • HR_PDB

We'll use SALES_PDB for our first test case and HR_PDB for the second test case.

The objective is to drop these PDBs from the primary database and observe how the standby database handles the corresponding redo operations.

2. Verify Primary and Standby Database Configuration

Let's first connect to the primary database.

SQL> SELECT
         name,
         db_unique_name,
         open_mode,
         database_role
     FROM v$database;

NAME    DB_UNIQUE_NAME  OPEN_MODE   DATABASE_ROLE
------- --------------- ----------- ----------------
PRODDB  PRODDB          READ WRITE  PRIMARY

Check the PDB configuration.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE  RESTRICTED
---------- ---------- ---------- ----------
         2 PDB$SEED   READ ONLY   NO
         3 SALES_PDB  READ WRITE  NO
         4 HR_PDB     READ WRITE  NO

Now connect to the physical standby database.

SQL> SELECT
         name,
         db_unique_name,
         open_mode,
         database_role
     FROM v$database;

NAME    DB_UNIQUE_NAME  OPEN_MODE  DATABASE_ROLE
------- --------------- ---------- ----------------
PRODDB  PRODDB_STBY     MOUNTED    PHYSICAL STANDBY

Check the standby PDB status.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   MOUNTED
         3 SALES_PDB  MOUNTED
         4 HR_PDB     MOUNTED

Our initial configuration is ready.

3. Verify Data Guard Redo Transport and Apply Status

Before performing any DDL operation on the primary database, we should verify that redo transport and apply are functioning correctly.

In Oracle 19c, we can use V$DATAGUARD_PROCESS to monitor Data Guard processes.

SQL> SELECT
         name,
         role,
         action,
         thread#,
         sequence#
     FROM v$dataguard_process;

We should also verify the transport and apply lag.

SQL> SELECT
         name,
         value,
         time_computed
     FROM v$dataguard_stats
     WHERE name IN (
         'transport lag',
         'apply lag',
         'apply finish time'
     );

Ideally, both transport lag and apply lag should be zero or within the expected operational limits.

For this demonstration, let's assume redo transport and apply are synchronized.

4. Test Case 1: Dropping a PDB When the Standby PDB Is in MOUNTED Mode

In our first scenario, SALES_PDB is in MOUNTED mode on the physical standby database.

This is a straightforward scenario in which redo apply can process the PDB drop operation.

Step 1: Verify the Primary PDB Status

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   READ ONLY
         3 SALES_PDB  READ WRITE
         4 HR_PDB     READ WRITE

Before dropping the PDB, close it on the primary database.

SQL> ALTER PLUGGABLE DATABASE SALES_PDB CLOSE IMMEDIATE;

Pluggable database altered.

Now drop the PDB, including its associated datafiles.

SQL> DROP PLUGGABLE DATABASE SALES_PDB INCLUDING DATAFILES;

Pluggable database dropped.

Verify the remaining PDBs.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   READ ONLY
         4 HR_PDB     READ WRITE

SALES_PDB has now been successfully dropped from the primary database.

Step 2: Check the Standby Alert Log

Now switch to the physical standby database and monitor its alert log.

You should observe recovery-related messages indicating that Oracle is removing the PDB's associated datafiles and tablespaces.

Representative alert log messages:

SALES_PDB(3): Recovery deleting file from controlfile.
SALES_PDB(3): Deleted Oracle managed file ...
SALES_PDB(3): Recovery dropped tablespace 'USERS'
SALES_PDB(3): Recovery dropped tablespace 'SYSTEM'
SALES_PDB(3): Recovery dropped tablespace 'SYSAUX'
SALES_PDB(3): Recovery dropped pluggable database 'SALES_PDB'

These messages indicate that the standby redo apply process has processed the PDB drop operation.

Step 3: Verify the Standby PDB Configuration

Connect to the physical standby database.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   MOUNTED
         4 HR_PDB     MOUNTED

SALES_PDB has automatically disappeared from the standby database.

Let's verify Data Guard apply status again.

SQL> SELECT
         name,
         value,
         time_computed
     FROM v$dataguard_stats
     WHERE name IN (
         'transport lag',
         'apply lag'
     );

The standby database remains synchronized.

Observation: When the standby PDB is in MOUNTED mode, Oracle Database 19c automatically processes the PDB drop operation through redo apply. No manual PDB closure is required on the standby.

5. Test Case 2: Dropping a PDB When the Standby PDB Is Open in READ ONLY Mode

Now let's move to a more interesting scenario.

What happens if the PDB is open in READ ONLY mode on the physical standby database when the primary database drops it?

This scenario is particularly relevant for environments using Active Data Guard, where application reporting or read-only workloads run against the standby database.

We will use HR_PDB for this demonstration.

Step 1: Prepare the Physical Standby Database

For this demonstration, we need to open the physical standby database in READ ONLY mode.

Stop managed recovery first.

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

Database altered.

Open the standby database.

SQL> ALTER DATABASE OPEN;

Database altered.

Verify the database mode.

SQL> SELECT
         name,
         db_unique_name,
         open_mode,
         database_role
     FROM v$database;

NAME    DB_UNIQUE_NAME  OPEN_MODE  DATABASE_ROLE
------- --------------- ---------- ----------------
PRODDB  PRODDB_STBY     READ ONLY  PHYSICAL STANDBY

Now open HR_PDB in READ ONLY mode.

SQL> ALTER PLUGGABLE DATABASE HR_PDB OPEN;

Pluggable database altered.

Verify the PDB status.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   READ ONLY
         4 HR_PDB     READ ONLY

Restart managed recovery.

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE
     DISCONNECT FROM SESSION;

Database altered.

Note: This is an Active Data Guard scenario when the appropriate licensing and configuration are in place. Opening a physical standby read-only while managed recovery is stopped is not, by itself, the same as running Active Data Guard with real-time apply.

Step 2: Drop HR_PDB from the Primary Database

Switch to the primary database.

First, verify that HR_PDB is open.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   READ ONLY
         4 HR_PDB     READ WRITE

Close the PDB.

SQL> ALTER PLUGGABLE DATABASE HR_PDB CLOSE IMMEDIATE;

Pluggable database altered.

Drop it.

SQL> DROP PLUGGABLE DATABASE HR_PDB INCLUDING DATAFILES;

Pluggable database dropped.

The PDB has now been removed from the primary database.

Step 3: Monitor the Standby Alert Log

Now switch to the standby database and examine the alert log.

In Oracle Database 19c, the recovery process can encounter the PDB drop marker while the standby PDB is still open.

Representative alert log messages may look like this:

PR00: MRP0: PDB unplug/drop/rename marker encountered.
PR00: Retry recovery...

ORA-65112: pluggable database HR_PDB
not closed on all instances of the standby database

This error indicates that the PDB must be closed before recovery can process the operation.

However, an important difference in Oracle 19c is that redo apply can automatically initiate the PDB closure.

You may subsequently observe messages similar to:

alter pluggable database "HR_PDB" close immediate

HR_PDB: Buffer Cache flush started
HR_PDB: Buffer Cache flush finished

Pluggable database HR_PDB closed

Completed: alter pluggable database "HR_PDB" close immediate

After the PDB has been closed, recovery continues processing the drop operation.

Representative messages:

Managed Standby Recovery starting Real Time Apply

HR_PDB: Recovery dropped temporary tablespace 'TEMP'
HR_PDB: Recovery dropped tablespace 'SYSTEM'
HR_PDB: Recovery dropped tablespace 'SYSAUX'

HR_PDB: Recovery dropped pluggable database 'HR_PDB'

The important observation here is that Oracle 19c can automatically close the affected standby PDB and continue redo apply.

You should always inspect the complete alert log to confirm that recovery resumed successfully rather than assuming that the initial ORA-65112 message represents a permanent failure.

Step 4: Verify the Standby Database

Let's check the standby PDB configuration.

SQL> SHOW PDBS;

    CON_ID CON_NAME   OPEN MODE
---------- ---------- ----------
         2 PDB$SEED   READ ONLY

HR_PDB is no longer present.

Check the Data Guard process status.

SQL> SELECT
         name,
         role,
         action,
         thread#,
         sequence#
     FROM v$dataguard_process;

Also verify transport and apply lag.

SQL> SELECT
         name,
         value,
         time_computed
     FROM v$dataguard_stats
     WHERE name IN (
         'transport lag',
         'apply lag'
     );

The expected result is that managed recovery continues and the standby catches up with the primary.

Observation: In Oracle Database 19c, an open standby PDB does not necessarily require manual intervention for a PDB drop. Oracle can automatically close the PDB and continue redo apply.

6. What About Oracle Database 12c?

This is where database version becomes important.

In Oracle Database 12c, PDB drop and unplug operations could cause redo apply to stop when the corresponding PDB was open on the physical standby.

The behaviour depended on the release and patch level.

For Oracle Database 12.2.0.1, Oracle provided patch 25616359, which introduced improved handling of PDB drop and unplug operations during redo apply.

Without the relevant fix, DBAs may need to manually close the PDB on the standby before restarting managed recovery.

For example:

SQL> ALTER PLUGGABLE DATABASE HR_PDB CLOSE IMMEDIATE;

If the environment is Oracle RAC, ensure the PDB is closed across all instances.

SQL> ALTER PLUGGABLE DATABASE HR_PDB
     CLOSE IMMEDIATE INSTANCES=ALL;

Then cancel the managed recovery process if it is still running or has entered an error state.

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

If Data Guard Broker is managing the configuration, recovery can be controlled through DGMGRL.

DGMGRL> EDIT DATABASE 'PRODDB_STBY'
         SET STATE='APPLY-OFF';

DGMGRL> EDIT DATABASE 'PRODDB_STBY'
         SET STATE='APPLY-ON';

Verify the managed recovery process and apply lag after restarting recovery.

Important: The exact recovery procedure should be selected according to the Oracle release, installed patches, standby open mode, RAC configuration, and Data Guard Broker configuration. Do not blindly execute these commands on a production standby.

7. Important Oracle DBA Considerations

Before dropping a PDB in a production Data Guard environment, keep the following points in mind.

1. Always verify the database role

Make sure you are connected to the correct primary database before executing a destructive operation.

SELECT name, db_unique_name, database_role
FROM v$database;

2. Verify standby synchronization

Check transport lag and apply lag before performing the operation.

SELECT name, value
FROM v$dataguard_stats
WHERE name IN ('transport lag', 'apply lag');

3. Check the standby PDB open mode

SELECT
    name,
    open_mode
FROM v$pdbs;

4. Monitor the standby alert log

Do not rely exclusively on the SQL command response from the primary database. Verify that the standby has successfully processed the PDB drop marker.

5. Verify managed recovery

In Oracle 19c, prefer V$DATAGUARD_PROCESS for monitoring Data Guard processes.

6. Consider RAC environments

A PDB may be open on multiple standby instances. Ensure the PDB is closed on all relevant instances when manual intervention is required.

7. Understand the impact of INCLUDING DATAFILES

The command:

DROP PLUGGABLE DATABASE HR_PDB INCLUDING DATAFILES;

removes the PDB and its associated datafiles. This is a destructive operation. Verify backups and recovery requirements before executing it.

8. Conclusion

So, does dropping a PDB from the primary database automatically drop it from the physical standby?

The answer is yes, provided redo transport and apply are functioning and the operation is supported by the relevant Oracle release and patch level.

Our Oracle 19c demonstration covered two scenarios:

ScenarioStandby PDB StateOracle 19c Behaviour
Test Case 1MOUNTEDPDB automatically dropped through redo apply
Test Case 2READ ONLYOracle can automatically close the PDB and continue redo apply

For older Oracle 12c environments, the behaviour can be different, particularly when the standby PDB is open during the drop operation. The applicable release-specific fixes and recovery procedures must be considered.

Final takeaway: Before performing PDB lifecycle operations in a Data Guard environment, always consider the database version, patch level, standby PDB open mode, and managed recovery status. A successful DROP operation on the primary does not eliminate the need to verify redo apply on the standby.

Happy Learning & Happy DBAing!

Oracle Bind Variable Peeking: Understanding Histograms, Data Skew, and Execution Plan Selection

 Introduction

Have you ever wondered why the same SQL statement performs exceptionally well for one bind variable value but becomes extremely slow when executed with another?

This is a common Oracle Database performance challenge, particularly in environments where applications heavily use bind variables.

Oracle uses bind variables to improve SQL sharing, reduce hard parsing, and minimize CPU overhead. Instead of generating a separate SQL statement for every input value, applications can execute the same SQL statement with different bind variable values.

However, there is an interesting challenge: different bind variable values can have dramatically different data selectivity.

For example, consider a table where one column contains a particular value in 499,981 rows, while other values appear only once. An index range scan might be ideal for a value that returns one row, but a full table scan could be significantly more efficient for a value that returns almost the entire table.

How does Oracle's Cost-Based Optimizer (CBO) handle this situation?

This is where Bind Variable Peeking comes into the picture.

In this article, we'll walk through a practical demonstration of:

  • Understanding data skew and column histograms.

  • How Oracle gathers and uses histogram statistics.

  • How different predicate values influence execution plans.

  • What happens when bind variable peeking is disabled.

  • How bind peeking helps Oracle estimate cardinality.

  • Why bind peeking does not always guarantee optimal execution plans.

Let's get started!

1. Understanding Data Skew: Creating the Test Environment

First, let's create a sample table named BIND_TEST and populate it with 500,000 records.

Our objective is to create a highly skewed data distribution:

  • Values 1 to 19 will appear exactly once.

  • Value 20 will appear 499,981 times.

CREATE TABLE bind_test (
    pk   INT,
    data CHAR(100)
);

INSERT INTO bind_test
SELECT
    CASE
        WHEN ROWNUM < 20 THEN ROWNUM
        ELSE 20
    END,
    ROWNUM
FROM dual
CONNECT BY LEVEL <= 500000;

CREATE INDEX pk_idx1 ON bind_test(pk);

EXEC DBMS_STATS.GATHER_TABLE_STATS(
    ownname => USER,
    tabname => 'BIND_TEST'
);

We now have a table containing 500,000 records with a significant data distribution imbalance.

This is an ideal scenario to understand how Oracle handles data skew.

2. Understanding Histogram Generation in Oracle

A histogram helps Oracle understand the actual data distribution within a column.

Without a histogram, the optimizer may rely on average selectivity estimates. This can result in inaccurate cardinality estimates when the column contains highly skewed data.

Let's first try gathering statistics using SIZE AUTO.

EXEC DBMS_STATS.GATHER_TABLE_STATS(
    ownname    => USER,
    tabname    => 'BIND_TEST',
    method_opt => 'FOR COLUMNS PK SIZE AUTO'
);

SELECT histogram
FROM user_tab_col_statistics
WHERE table_name = 'BIND_TEST'
AND column_name = 'PK';

Output:

HISTOGRAM
---------------
NONE

Why didn't Oracle create a histogram?

In modern Oracle versions, SIZE AUTO considers column usage information maintained through the column usage tracking mechanism, including SYS.COL_USAGE$.

Oracle uses this information to identify columns that are relevant to query predicates and other optimizer operations.

If the column hasn't been used in relevant SQL statements, Oracle may decide that a histogram is not required.

Let's explicitly request a histogram with 200 buckets.

EXEC DBMS_STATS.GATHER_TABLE_STATS(
    ownname    => USER,
    tabname    => 'BIND_TEST',
    method_opt => 'FOR COLUMNS PK SIZE 200'
);

SELECT histogram
FROM user_tab_col_statistics
WHERE table_name = 'BIND_TEST'
AND column_name = 'PK';

Output:

HISTOGRAM
---------------
FREQUENCY

Great! Oracle has now created a frequency histogram.

Let's examine how Oracle has captured the data distribution.

SELECT
    endpoint_value,
    endpoint_number -
        NVL(
            LAG(endpoint_number) OVER (
                ORDER BY endpoint_value
            ), 0
        ) AS frequency
FROM user_histograms
WHERE table_name = 'BIND_TEST'
AND column_name = 'PK'
ORDER BY endpoint_value;

Output:

ENDPOINT_VALUEFREQUENCY
11
21
31
41
51
61
71
81
91
101
111
121
131
141
151
161
171
181
191
20499,981

Notice how accurately Oracle has captured the data distribution.

It knows that values 1 to 19 occur only once, whereas value 20 occurs 499,981 times.

This information becomes extremely important when the optimizer estimates the number of rows returned by a query.

3. Testing Literal SQL Statements: How Oracle Selects Execution Plans

Before moving to bind variables, let's understand how Oracle behaves when we execute SQL statements using literal values.

Scenario 1: Querying a value that returns only one row

SELECT MAX(data) max_data
FROM bind_test
WHERE pk = 10;

Output:

MAX_DATA
--------------------------------
10

Let's inspect the execution plan.

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        format => 'TYPICAL +PEEKED_BINDS'
    )
);

Execution plan:

--------------------------------------------------------------------------------
| Id | Operation                            | Name      | Rows | Cost (%CPU) |
--------------------------------------------------------------------------------
|  0 | SELECT STATEMENT                     |           |      | 4 (100)     |
|  1 | SORT AGGREGATE                       |           | 1    |             |
|  2 | TABLE ACCESS BY INDEX ROWID BATCHED  | BIND_TEST | 1    | 4 (0)       |
|* 3 | INDEX RANGE SCAN                     | PK_IDX1   | 1    | 3 (0)       |
--------------------------------------------------------------------------------

Oracle estimates that the query will return just one row.

Since only one row needs to be retrieved, using the index is the most efficient access path.

The optimizer chooses:

INDEX RANGE SCAN

Scenario 2: Querying a value that returns almost the entire table

Now let's execute the same query using value 20.

SELECT MAX(data) max_data
FROM bind_test
WHERE pk = 20;

Output:

MAX_DATA
--------------------------------
99999

Check the execution plan again.

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        format => 'TYPICAL +PEEKED_BINDS'
    )
);

Execution plan:

--------------------------------------------------------------------------------
| Id | Operation         | Name      | Rows  | Cost (%CPU) |
--------------------------------------------------------------------------------
|  0 | SELECT STATEMENT  |           |       | 2087 (100)  |
|  1 | SORT AGGREGATE    |           | 1     |             |
|* 2 | TABLE ACCESS FULL | BIND_TEST | 499K  | 2087 (1)    |
--------------------------------------------------------------------------------

This time Oracle estimates approximately 499,981 rows.

Using an index to retrieve almost the entire table would introduce unnecessary index and table block accesses.

Therefore, Oracle chooses:

TABLE ACCESS FULL

This is exactly what we expect from an optimizer that understands the underlying data distribution.

So far, everything looks perfect.

But what happens when we replace the literal value with a bind variable?

4. Disabling Bind Variable Peeking: Understanding the Problem

Let's simulate the behavior where Oracle does not peek at user bind variable values during optimization.

For demonstration purposes, we'll disable bind peeking using the hidden parameter _optim_peek_user_binds.

Note: This is an undocumented internal parameter. Use it only in a controlled test environment, not as a production tuning recommendation.

ALTER SESSION SET "_optim_peek_user_binds" = FALSE;

ALTER SYSTEM FLUSH SHARED_POOL;

Now declare a bind variable and assign the value 10.

VARIABLE v01 NUMBER;

EXEC :v01 := 10;

SELECT MAX(data) max_data
FROM bind_test
WHERE pk = :v01;

Let's inspect the execution plan.

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        format => 'TYPICAL +PEEKED_BINDS'
    )
);

Execution plan:

--------------------------------------------------------------------------------
| Id | Operation                            | Name      | Rows  | Cost (%CPU) |
--------------------------------------------------------------------------------
|  0 | SELECT STATEMENT                     |           |       | 430 (100)   |
|  1 | SORT AGGREGATE                       |           | 1     |             |
|  2 | TABLE ACCESS BY INDEX ROWID BATCHED  | BIND_TEST | 25000 | 430 (0)     |
|* 3 | INDEX RANGE SCAN                     | PK_IDX1   | 25000 | 51 (0)      |
--------------------------------------------------------------------------------

Look at the estimated cardinality.

Oracle estimates 25,000 rows instead of the actual one row.

Why?

Because Oracle doesn't know the actual bind variable value during optimization in this demonstration.

It therefore uses a generic selectivity estimate rather than the value-specific histogram information.

In this example:

  • Total rows = 500,000

  • Distinct values = 20

  • Average rows per distinct value = 500,000 / 20

  • Estimated cardinality = 25,000

The estimate is therefore 25,000 rows.

This is significantly different from the actual one row returned by the query.

What happens when we change the bind variable value?

Now let's change the bind variable to 20.

EXEC :v01 := 20;

SELECT MAX(data) max_data
FROM bind_test
WHERE pk = :v01;

The query returns the expected result, but let's check the execution plan again.

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        format => 'TYPICAL +PEEKED_BINDS'
    )
);

Execution plan:

--------------------------------------------------------------------------------
| Id | Operation                            | Name      | Rows  | Cost (%CPU) |
--------------------------------------------------------------------------------
|  0 | SELECT STATEMENT                     |           |       | 430 (100)   |
|  1 | SORT AGGREGATE                       |           | 1     |             |
|  2 | TABLE ACCESS BY INDEX ROWID BATCHED  | BIND_TEST | 25000 | 430 (0)     |
|* 3 | INDEX RANGE SCAN                     | PK_IDX1   | 25000 | 51 (0)      |
--------------------------------------------------------------------------------

Notice something important.

Even though the bind variable value has changed from 10 to 20, Oracle continues using the same execution plan.

Why?

Because Oracle has reused the previously cached execution plan for the same SQL statement.

The optimizer has no value-specific information to distinguish between these two executions.

Consequently, it continues using the INDEX RANGE SCAN even though the query now returns 499,981 rows.

For this particular data distribution, a FULL TABLE SCAN would be a much more appropriate access path.

This demonstrates one of the potential performance problems associated with inaccurate bind-variable cardinality estimates.

5. Enabling Bind Variable Peeking: How Oracle Makes Better Decisions

Now let's enable bind variable peeking again.

Bind variable peeking was introduced in Oracle Database 9i.

It allows the optimizer to inspect the bind variable value during hard parsing and use that value when estimating predicate selectivity and generating an execution plan.

Let's enable it for our test session.

ALTER SESSION SET "_optim_peek_user_binds" = TRUE;

ALTER SYSTEM FLUSH SHARED_POOL;

Now assign value 10 to the bind variable and execute the query.

VARIABLE v01 NUMBER;

EXEC :v01 := 10;

SELECT MAX(data) max_data
FROM bind_test
WHERE pk = :v01;

Let's inspect the execution plan.

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        format => 'TYPICAL +PEEKED_BINDS'
    )
);

Execution plan:

--------------------------------------------------------------------------------
| Id | Operation                            | Name      | Rows | Cost (%CPU) |
--------------------------------------------------------------------------------
|  0 | SELECT STATEMENT                     |           |      | 4 (100)     |
|  1 | SORT AGGREGATE                       |           | 1    |             |
|  2 | TABLE ACCESS BY INDEX ROWID BATCHED  | BIND_TEST | 1    | 4 (0)       |
|* 3 | INDEX RANGE SCAN                     | PK_IDX1   | 1    | 3 (0)       |
--------------------------------------------------------------------------------

Peeked Binds (identified by position):
--------------------------------------
1 - :V01 (NUMBER): 10

Excellent!

Look at the difference.

Oracle has now identified the actual bind variable value during optimization.

Because the histogram indicates that value 10 occurs only once, the optimizer estimates one row and chooses an INDEX RANGE SCAN.

The Peeked Binds section confirms that Oracle peeked at the bind variable value:

1 - :V01 (NUMBER): 10

This is the basic working principle of Bind Variable Peeking.

6. Important Architectural Consideration: Bind Peeking Is Not a Complete Solution

There is one important point every Oracle DBA should understand.

Bind Variable Peeking does not mean Oracle will generate a new execution plan every time the bind variable value changes.

Bind peeking generally happens during hard parsing.

Once Oracle generates an execution plan, subsequent executions can reuse that plan.

Consider our example:

ExecutionBind ValueActual RowsIdeal Access Path
First101Index Range Scan
Second20499,981Full Table Scan

If Oracle initially peeks at value 10, it may generate an index-based execution plan.

When the same SQL statement is subsequently executed with value 20, Oracle may reuse that plan.

This can result in a suboptimal execution plan for the second execution.

This behavior is commonly associated with Bind Variable Peeking and the Bind-Sensitive SQL problem.

What is Adaptive Cursor Sharing?

To address this type of problem, Oracle introduced Adaptive Cursor Sharing (ACS) in Oracle Database 11g.

ACS allows Oracle to identify SQL statements whose execution plans may need to vary depending on bind variable selectivity.

Oracle can mark a cursor as bind-sensitive and, when appropriate, bind-aware.

It can then create multiple child cursors with different execution plans for different selectivity ranges.

For example:

  • Bind value 10: INDEX RANGE SCAN.

  • Bind value 20: TABLE ACCESS FULL.

This allows Oracle to accommodate different data distributions without requiring applications to use completely different SQL statements.

However, ACS is not guaranteed to create multiple plans for every SQL statement. Its behavior depends on optimizer decisions, execution feedback, selectivity ranges, and other conditions.

7. Conclusion

Bind Variable Peeking is an important Oracle optimizer feature that helps improve cardinality estimation when SQL statements use bind variables.

Our demonstration showed how the same SQL statement can produce different optimal execution plans depending on the bind variable value.

The key takeaways are:

  1. Histograms help Oracle understand data skew and value distribution.

  2. SIZE AUTO uses column usage information to determine whether histograms are appropriate.

  3. Without bind peeking, Oracle may use generic selectivity estimates for bind predicates.

  4. Bind peeking allows Oracle to inspect bind values during hard parsing.

  5. The execution plan generated during the initial hard parse may be reused for subsequent bind values.

  6. Adaptive Cursor Sharing helps Oracle manage SQL statements where different bind values require different execution plans.

As Oracle DBAs, understanding these mechanisms is essential when troubleshooting SQL performance issues involving bind variables, skewed data, and inconsistent execution plans.

Remember: Bind variables improve SQL sharing, but different bind values do not always have the same selectivity. Understanding how Oracle handles this difference is the key to effective SQL performance tuning.

Friday, October 30, 2026

Oracle Database SQL Performance Investigation and Query Optimization

 

1. Introduction

SQL query performance is an important factor in maintaining database application responsiveness. A query taking longer than expected can affect application performance, user experience, and overall system availability.

This document covers the Oracle DBA-side investigation and optimization checks performed when troubleshooting a reported 30-second SQL-FIX portal query timeout.

The objective is to identify whether the delay is related to:

  • SQL query execution performance.

  • Missing or inefficient indexes.

  • Outdated or stale table statistics.

  • Inefficient execution plans.

  • Oracle resource profile limitations.

  • Database locking or blocking sessions.

  • High CPU utilization or I/O waits.

  • Application-side timeout configuration.

All SQL queries included in this document are intended for diagnostic purposes and are read-only.

Note: Replace YOUR_ORACLE_USERNAME, YOUR_SCHEMA, YOUR_PROFILE, and other placeholders with actual database values before execution.


2. Oracle User Account Status Validation

Verified the Oracle account status, assigned profile, account creation date, last login, and expiry information.

SELECT username,
       account_status,
       profile,
       created,
       last_login
FROM dba_users
WHERE username = UPPER('TESTUSER');

Additional check for account expiry and lock details:

SELECT username,
       account_status,
       profile,
       expiry_date,
       lock_date
FROM dba_users
WHERE username = UPPER('TESTUSER
');

Purpose:

  • Verify whether the account is OPEN, EXPIRED, or LOCKED.

  • Identify the assigned resource profile.

  • Check whether account expiry or locking could affect application connectivity.

Note: An EXPIRED(GRACE) account does not automatically indicate a SQL execution performance issue.


3. Oracle User Profile Resource Limit Validation

Reviewed the resource limits configured under the assigned Oracle profile.

SELECT profile,
       resource_name,
       limit
FROM dba_profiles
WHERE profile = 'DEFAULT'
AND resource_name IN (
    'CONNECT_TIME',
    'CPU_PER_SESSION',
    'IDLE_TIME',
    'SESSIONS_PER_USER'
)
ORDER BY resource_name;

Optional comparison with the DEFAULT profile:

SELECT p.profile,
       p.resource_name,
       p.limit,
       d.limit AS default_limit
FROM dba_profiles p
LEFT JOIN dba_profiles d
  ON d.profile = 'DEFAULT'
 AND d.resource_name = p.resource_name
 AND d.resource_type = p.resource_type
WHERE p.profile = 'DEFAULT'
AND p.resource_type = 'KERNEL'
AND p.resource_name IN (
    'CONNECT_TIME',
    'IDLE_TIME',
    'CPU_PER_SESSION',
    'SESSIONS_PER_USER'
)
ORDER BY p.resource_name;

Purpose:

  • Identify resource restrictions imposed on the application user.

  • Review CPU and session-related limits.

  • Determine whether profile restrictions could contribute to session termination or resource exhaustion.

Note: IDLE_TIME does not limit an actively executing SQL statement. CONNECT_TIME limits session duration rather than individual query execution time. Check RESOURCE_LIMIT and the effective profile configuration when evaluating enforcement.


4. Table Statistics Validation

Reviewed table statistics for the selected application tables to identify missing or stale statistics.

SELECT owner,
       table_name,
       num_rows,
       blocks,
       TO_CHAR(last_analyzed,
               'DD-MON-YYYY HH24:MI:SS') AS last_analyzed,
       stale_stats
FROM dba_tab_statistics
WHERE owner = 'YOUR_SCHEMA'
AND table_name IN (
    'F9201',
    'F9202')
ORDER BY table_name;

Purpose:

  • Validate whether table statistics are available.

  • Review estimated row counts.

  • Identify stale statistics.

  • Check when statistics were last collected.

Optimization recommendation:

If statistics are missing or stale, evaluate gathering statistics after assessing the production impact and maintenance window.

Do not gather statistics blindly during an active performance investigation.


5. Index Status Validation

Reviewed the indexes associated with the application schema.

SELECT table_name,
       index_name,
       status,
       uniqueness,
       last_analyzed
FROM dba_indexes
WHERE owner = 'TESTUSER'
ORDER BY table_name, index_name;

To identify indexed columns:

SELECT i.table_name,
       i.index_name,
       i.status,
       c.column_name,
       c.column_position,
       c.descend
FROM dba_indexes i
JOIN dba_ind_columns c
  ON i.owner = c.index_owner
 AND i.index_name = c.index_name
WHERE i.table_owner = 'TESTUSER'
ORDER BY i.table_name, i.index_name, c.column_position;

Purpose:

  • Verify whether indexes are VALID.

  • Identify existing indexes on frequently queried columns.

  • Review index column order.

  • Identify potential indexing gaps based on SQL predicates and joins.

Optimization recommendation:

Evaluate indexes on columns frequently used in:

  • WHERE conditions.

  • JOIN conditions.

  • ORDER BY clauses.

  • GROUP BY clauses.

Avoid creating indexes without reviewing the actual execution plan and existing index structures.


6. SQL Execution Plan Analysis

Execution plan analysis is one of the most important steps in Oracle SQL performance troubleshooting.

First, identify the SQL ID of the affected query.

SELECT sql_id,
       child_number,
       parsing_schema_name,
       executions,
       elapsed_time / 1000000 AS elapsed_seconds,
       cpu_time / 1000000 AS cpu_seconds,
       buffer_gets,
       disk_reads,
       rows_processed,
       SUBSTR(sql_text, 1, 1000) AS sql_text
FROM v$sql
WHERE parsing_schema_name = 'TESTUSER'
ORDER BY last_active_time DESC;

Review the execution plan using the SQL ID:

SELECT *
FROM TABLE(
    DBMS_XPLAN.DISPLAY_CURSOR(
        'YOUR_SQL_ID',
        NULL,
        'ALLSTATS LAST +PEEKED_BINDS'
    )
);

Important execution plan indicators:

Operation / IndicatorWhat to investigate
TABLE ACCESS FULLWhether full table scan is appropriate
INDEX RANGE SCANIndex access efficiency
INDEX UNIQUE SCANUnique index access
NESTED LOOPSJoin cardinality and repeated access
HASH JOINMemory usage and join volume
SORT ORDER BYSorting overhead
High buffer getsExcessive logical I/O
High disk readsPhysical I/O overhead
E-Rows vs A-RowsCardinality estimation accuracy

Optimization recommendation:

Compare estimated rows (E-Rows) against actual rows (A-Rows). Significant differences may indicate inaccurate optimizer statistics, data skew, or bind-variable-related issues.

Note: ALLSTATS LAST requires runtime plan statistics to have been collected. If they are unavailable, inspect the available plan and consider collecting execution statistics during a controlled reproduction. PEEKED_BINDS shows available peeked bind values, not necessarily every runtime bind value.


7. SQL Performance Metrics Analysis

Review SQL execution metrics to identify expensive SQL statements.

SELECT sql_id,
       executions,
       ROUND(elapsed_time / 1000000, 2) AS elapsed_seconds,
       ROUND(cpu_time / 1000000, 2) AS cpu_seconds,
       buffer_gets,
       disk_reads,
       rows_processed,
       ROUND(
           (elapsed_time / NULLIF(executions, 0)) / 1000000,
           4
       ) AS avg_elapsed_seconds
FROM v$sql
WHERE parsing_schema_name = 'TESTUSER'
AND executions > 0 ORDER BY elapsed_time DESC FETCH FIRST 20 ROWS ONLY;

Purpose:

  • Identify SQL statements consuming maximum elapsed time.

  • Compare CPU time against total elapsed time.

  • Identify excessive logical and physical reads.

  • Review average execution time.

Note: These are cumulative cursor-cache metrics, not necessarily the duration of a single execution. Cursor statistics can be aged out or reset, and elapsed time may include time spent waiting.


8. Active Session and Wait Event Monitoring

Attempted to identify the affected application user's live session.

SELECT sid,
       serial#,
       username,
       machine,
       program,
       module,
       status,
       sql_id,
       sql_child_number,
       event,
       wait_class,
       last_call_et,
       blocking_session
FROM v$session
WHERE username = UPPER('TESTUSER')
ORDER BY logon_time DESC;

If no matching session is found, check all active user sessions.

SELECT sid,
       serial#,
       username,
       status,
       sql_id,
       machine,
       program,
       module,
       logon_time
FROM v$session
WHERE type = 'USER'
AND status = 'ACTIVE'
ORDER BY logon_time DESC;

Purpose:

  • Identify the affected SQL ID.

  • Review current wait events.

  • Identify blocking sessions.

  • Capture application machine and module information.

  • Determine whether the query is actively executing or waiting.

Note: A session may disappear or become inactive before the DBA captures it. Coordinate with the application team to reproduce the issue while monitoring.


9. Blocking Session and Lock Investigation

Check whether database locks are contributing to the query delay.

SELECT sid,
       serial#,
       username,
       blocking_session,
       event,
       wait_class,
       seconds_in_wait,
       sql_id
FROM v$session
WHERE blocking_session IS NOT NULL
ORDER BY seconds_in_wait DESC;

Additional lock information:

SELECT s.sid,
       s.serial#,
       s.username,
       s.sql_id,
       l.type,
       l.id1,
       l.id2,
       l.lmode,
       l.request,
       l.block
FROM v$lock l
JOIN v$session s
  ON l.sid = s.sid
WHERE l.block = 1
   OR l.request > 0
ORDER BY s.sid;

Purpose:

  • Identify blocking sessions.

  • Check lock requests.

  • Determine whether transaction-level contention is affecting application queries.


10. SQL-FIX Portal Timeout Investigation

The application team reported a query timeout of approximately 30 seconds.

The following points should be verified jointly by the DBA and application teams:

  1. Confirm the exact SQL statement submitted by the portal.

  2. Capture the SQL ID and child cursor number.

  3. Record query start and end timestamps.

  4. Check whether the SQL statement is still executing after 30 seconds.

  5. Identify whether the session is waiting on CPU, I/O, locks, or other database resources.

  6. Compare database execution time with the total application response time.

  7. Review JDBC or application connection timeout settings.

  8. Check whether the application cancels the SQL statement after 30 seconds.

  9. Verify whether connection-pool settings or network latency contribute to the delay.

Important: A 30-second portal timeout does not necessarily mean Oracle is terminating the SQL statement after 30 seconds. The timeout could be configured at the application, JDBC, middleware, or database-call level.


11. Oracle SQL Query Optimization Recommendations

Based on the investigation, consider the following optimization approaches:

AreaRecommended action
Execution planIdentify inefficient operations and join methods
IndexingReview missing or inefficient indexes
StatisticsValidate table, index, and column statistics
SQL predicatesAvoid unnecessary functions on indexed columns
JoinsValidate join conditions and cardinality
Bind variablesCheck bind usage and possible bind sensitivity
Full table scansDetermine whether scans are justified
SortingMinimize unnecessary ORDER BY operations
PartitioningEvaluate partition pruning where applicable
Resource waitsInvestigate CPU, I/O, locks, and memory pressure

Example: Avoid functions on indexed columns

Potentially inefficient:

SELECT *
FROM YOUR_TABLE
WHERE TRUNC(CREATED_DATE) = DATE '2026-10-30';

Alternative:

SELECT *
FROM YOUR_TABLE
WHERE CREATED_DATE >= DATE '2026-10-30'
AND CREATED_DATE < DATE '2026-10-31';

The second approach can allow a normal index on CREATED_DATE to be used, depending on the execution plan and other predicates.

Example: Avoid SELECT *

Instead of:

SELECT *
FROM YOUR_TABLE
WHERE STATUS = 'ACTIVE';

Prefer:

SELECT ID,
       NAME,
       STATUS
FROM YOUR_TABLE
WHERE STATUS = 'ACTIVE';

Selecting only required columns can reduce unnecessary data retrieval and network transfer.


12. DBA Findings and Investigation Summary

Based on the diagnostic checks captured during the investigation:

  • Selected application table statistics showed STALE_STATS = NO.

  • Displayed indexes showed STATUS = VALID.

  • The reviewed profile was DEFAULT.

  • The application user's account status was EXPIRED(GRACE).

  • No matching live session was captured during the V$SESSION check.

  • The actual SQL execution plan and runtime wait behavior were not yet verified.

  • The reported 30-second timeout requires correlation with application-side timeout configuration.

Conclusion

The initial Oracle-side checks did not identify an obvious issue with table statistics or index status. However, these checks alone are insufficient to conclude that database performance is normal.

The next step should be to capture the exact SQL statement and SQL ID during an actual timeout reproduction, followed by execution plan analysis, runtime statistics review, and wait-event investigation.

The DBA and application teams should correlate Oracle execution time with the SQL-FIX portal response time to identify whether the bottleneck is within Oracle Database or the application layer.

Precaution: All queries in this document are intended for read-only diagnostics. Do not modify indexes, statistics, profiles, SQL statements, or session settings without validating the root cause and assessing the production impact.


13. Required Oracle Privileges

The queries use Oracle dictionary and dynamic performance views, including:

  • DBA_USERS

  • DBA_PROFILES

  • DBA_TAB_STATISTICS

  • DBA_INDEXES

  • DBA_IND_COLUMNS

  • V$SESSION

  • V$SQL

  • V$LOCK

  • DBMS_XPLAN.DISPLAY_CURSOR

Appropriate dictionary-view and dynamic performance view privileges are required. Access to DBMS_XPLAN and the relevant cursor information must also be available.

Thursday, October 29, 2026

PostgreSQL Tutorial: Create a Database, Create a Table, and Insert Records

 If you are starting with PostgreSQL, one of the first things to learn is how to create a database, define a table, and insert records into it.

In this tutorial, we will walk through the complete process using simple SQL commands and practical examples.

Step 1: Connect to PostgreSQL

You can connect to PostgreSQL using psql, the PostgreSQL command-line client.

psql -U postgres -h localhost -p 5432

Parameters:

  • -U postgres — PostgreSQL username

  • -h localhost — Database server hostname

  • -p 5432 — PostgreSQL port

Enter your password when prompted.

Step 2: Create a Database

Execute the following SQL command to create a new database named company_db.

CREATE DATABASE company_db;

To list the available databases:

\l

Connect to the newly created database:

\c company_db

Note: The \l and \c commands are psql meta-commands, not standard SQL statements.

Step 3: Create a Table

Let's create an employees table to store employee information.

CREATE TABLE employees (
    employee_id SERIAL PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    department VARCHAR(50),
    salary NUMERIC(10,2),
    joining_date DATE DEFAULT CURRENT_DATE
);

Column explanation:

  • employee_id SERIAL PRIMARY KEY — Automatically generates an integer ID and uniquely identifies each employee.

  • employee_name VARCHAR(100) NOT NULL — Stores the employee's name and does not allow NULL values.

  • department VARCHAR(50) — Stores the department name.

  • salary NUMERIC(10,2) — Stores salary values with two decimal places.

  • joining_date DATE DEFAULT CURRENT_DATE — Uses the current date when no joining date is provided.

Step 4: Verify the Table Structure

To view the table definition in psql, run:

\d employees

To list tables in the current database:

\dt

Step 5: Insert Records into the Table

Insert sample employee records using an INSERT statement.

INSERT INTO employees
    (employee_name, department, salary, joining_date)
VALUES
    ('Rahul Sharma', 'IT', 75000.00, '2025-01-15'),
    ('Priya Verma', 'HR', 60000.00, '2025-03-10'),
    ('Amit Kumar', 'Finance', 68000.00, '2025-06-20');

Since employee_id is generated automatically, there is no need to specify it in the INSERT statement.

Step 6: Retrieve the Inserted Records

To display all records:

SELECT * FROM employees;

To retrieve only employee names and salaries:

SELECT employee_name, salary
FROM employees;

To retrieve employees working in the IT department:

SELECT *
FROM employees
WHERE department = 'IT';

Step 7: Verify the Number of Records

Count the total number of employees:

SELECT COUNT(*) AS total_employees
FROM employees;

Expected output:

 total_employees
-----------------
               3

Complete Workflow at a Glance

  1. Connect to PostgreSQL using psql.

  2. Create a database using CREATE DATABASE.

  3. Connect to the database using \c.

  4. Create a table using CREATE TABLE.

  5. Verify the table using \d and \dt.

  6. Insert records using INSERT INTO.

  7. Retrieve and validate data using SELECT.

Conclusion

You have now learned the basic PostgreSQL workflow for creating a database, creating a table, inserting multiple records, and verifying the results.

These fundamental commands are essential for PostgreSQL database administration, application development, and day-to-day database operations.

Next step: Learn how to update records using UPDATE, delete records using DELETE, and manage transactions using COMMIT and ROLLBACK.

#PostgreSQL #SQL #DatabaseAdministration #DBA #LearnPostgreSQL #DatabaseTutorial

Tuesday, October 13, 2026

ORA-02380: Profile ORA_STIG_PROFILE Does Not Exist During Oracle AI Database 26ai Upgrade

 

ORA-02380: Profile ORA_STIG_PROFILE Does Not Exist During Oracle AI Database 26ai Upgrade

Published: October 13, 2026
Category: Oracle Database, Database Upgrade, Troubleshooting
Tags: Oracle 26ai, AutoUpgrade, ORA-02380, ORA_STIG_PROFILE, Oracle DBA

Introduction

During an upgrade to Oracle AI Database 26ai, you may encounter the error ORA-02380: profile ORA_STIG_PROFILE does not exist. This issue can cause the Oracle Server component to become INVALID in the Post-Upgrade Status Report, even when other database components have been upgraded successfully.

The good news is that this issue does not necessarily require restoring the database or starting the upgrade from scratch. In the scenario described here, the missing profile can be created manually, and the upgrade can then be rerun using Oracle AutoUpgrade.

In this blog post, we will look at the error, its root cause, the resolution, and the precautions DBAs should take before upgrading to Oracle AI Database 26ai.

1. Understanding the Error

During the upgrade process, Oracle executes SQL statements to configure the ORA_STIG_PROFILE profile. If this profile does not exist in the database, the following error may occur:

ORA-02380: profile ORA_STIG_PROFILE does not exist
ORA-06512: at line 2

The failing statement may look similar to this:

BEGIN
  EXECUTE IMMEDIATE
    'ALTER PROFILE ora_stig_profile LIMIT
       idle_time 15
       failed_login_attempts 3
       password_life_time 35
       password_reuse_time 175
       password_reuse_max 5
       password_lock_time UNLIMITED
       password_grace_time 0
       password_verify_function ora12c_stig_verify_function';
END;
/

Oracle is attempting to modify the profile, but the operation fails because the profile is missing.

2. Impact on the Upgrade

The upgrade may continue through several database components before reporting an error for the Oracle Server component.

For example, the Post-Upgrade Status Report may show:

Component                         Status
------------------------------------------
Oracle Server                     INVALID
JServer JAVA Virtual Machine      UPGRADED
Oracle XDK                        UPGRADED
Oracle Database Java Packages     UPGRADED
Oracle Real Application Clusters  UPGRADED
Oracle XML Database               UPGRADED

The Oracle Server component may remain INVALID because of the failed upgrade step.

Important: Do not assume that the entire upgrade has failed irrecoverably, and do not immediately restore the database. First, investigate the reported error and follow the appropriate Oracle-supported recovery procedure.

3. Root Cause

The immediate cause is that the ORA_STIG_PROFILE profile does not exist when the upgrade script attempts to alter it.

Oracle's upgrade process expects the profile to be available for the relevant security configuration changes. If it is absent, the ALTER PROFILE statement fails with ORA-02380.

This scenario has been documented for upgrades to Oracle AI Database 26ai. Oracle Support has also documented the issue and its workaround in the following Knowledge Base article:

KB885836 – Oracle Database Upgrade from 19.xx to 26ai fails with “ORA-02380: profile ORA_STIG_PROFILE does not exist”.

4. Resolution: Create the Missing Profile

Before applying the workaround, verify that the profile is missing and confirm that the password verification function referenced by the profile is available.

Check whether the profile exists:

SELECT profile
FROM dba_profiles
WHERE profile = 'ORA_STIG_PROFILE';

Check whether the password verification function exists:

SELECT owner, object_name, object_type, status
FROM dba_objects
WHERE object_name = 'ORA12C_STIG_VERIFY_FUNCTION';

If the profile is missing and the required verification function is available, create the profile using the following SQL statement:

CREATE PROFILE ORA_STIG_PROFILE
  LIMIT
    PASSWORD_LIFE_TIME 35
    PASSWORD_GRACE_TIME 0
    PASSWORD_REUSE_TIME 175
    PASSWORD_REUSE_MAX 5
    FAILED_LOGIN_ATTEMPTS 3
    PASSWORD_LOCK_TIME UNLIMITED
    INACTIVE_ACCOUNT_TIME 35
    IDLE_TIME 15
    PASSWORD_VERIFY_FUNCTION
      ora12c_stig_verify_function;

Execute the command in the appropriate database container with the required administrative privileges.

Verify the profile

After creating the profile, verify its configuration:

SELECT resource_name, limit
FROM dba_profiles
WHERE profile = 'ORA_STIG_PROFILE'
ORDER BY resource_name;

Confirm that the expected limits are present and that the password verification function is correctly configured.

If the verification function is missing, do not blindly proceed with the profile creation command. Investigate the function's availability and follow the relevant Oracle Support instructions for your database version.

5. Rerun the Upgrade Using AutoUpgrade

Once the missing profile has been created and its configuration verified, rerun the upgrade using the same AutoUpgrade configuration file:

java -jar autoupgrade.jar \
  -config yourconfig.cfg \
  -mode deploy

Replace yourconfig.cfg with the path to your actual AutoUpgrade configuration file.

Monitor the upgrade logs and review the Post-Upgrade Status Report to confirm that the Oracle Server component completes successfully.

Do not consider the upgrade complete until the database components and required post-upgrade activities have been validated.

6. What About Oracle AutoUpgrade?

According to the source report published on October 12, 2026, Oracle had developed a precheck intended to detect and automatically fix this condition.

The enhancement was tracked under:

Bug 39133336 – PRECHECK REQUEST – AUTO FIXUP TO CREATE ORA_STIG_PROFILE (AND FUNCTION) FOR BUG 39111855

At the time of that report, the enhancement was not yet available in an AutoUpgrade release because a code merge project was still pending.

DBAs planning an upgrade should therefore check the latest AutoUpgrade release notes and confirm whether the relevant precheck and automatic fixup are available in their installed version. Do not assume that every AutoUpgrade version includes this fix.

7. Recommendations for DBAs

Before upgrading a production database to Oracle AI Database 26ai, consider the following precautions:

  • Run the appropriate AutoUpgrade prechecks before starting the upgrade.

  • Review the source database's security profiles and password verification functions.

  • Keep AutoUpgrade updated to a version supported for your target database release.

  • Review the upgrade logs and Post-Upgrade Status Report carefully.

  • Take and validate the required backups and recovery arrangements before the upgrade.

  • If the error occurs, consult Oracle Support documentation and assess the database state before deciding whether to rerun the upgrade or perform another recovery action.

Conclusion

The ORA-02380: profile ORA_STIG_PROFILE does not exist error can interrupt the Oracle AI Database 26ai upgrade process when the expected security profile is missing.

In the documented scenario, the workaround is straightforward: verify the required password verification function, create the missing profile with the prescribed limits, and rerun the upgrade using AutoUpgrade.

The key takeaway for Oracle DBAs is simple: check security profiles and AutoUpgrade prechecks before beginning a major database upgrade. A small pre-upgrade validation can help prevent avoidable interruptions during a critical maintenance window.

Disclaimer: Always validate the workaround against the applicable Oracle Support note and your database version before executing it in a production environment.

Monday, October 12, 2026

Oracle Database Tip: Generate SQL Scripts to Change User Default Tablespaces 🚀

 Have you ever needed to change the default tablespace for multiple Oracle database users without manually writing individual ALTER USER statements?

Here’s a simple SQL*Plus scripting technique that can save time when working with database administration tasks.

The idea is to generate the SQL commands dynamically from DBA_USERS, spool them into a .sql file, and execute them only after reviewing the generated statements.

🔹 1. Generate a script to alter users to the SYSTEM tablespace

SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET PAGESIZE 0
SET LINESIZE 32767
SET TRIMSPOOL ON
SET VERIFY OFF
SET TERMOUT OFF

SPOOL alter_non_oracle_users_to_system.sql

SELECT 'ALTER USER "' || username ||
       '" DEFAULT TABLESPACE SYSTEM;'
FROM   dba_users
WHERE  oracle_maintained = 'N'
AND    default_tablespace <> 'SYSTEM'
ORDER  BY username;

SPOOL OFF

This script generates ALTER USER statements for non-Oracle-maintained users whose current default tablespace is not SYSTEM.

🔹 2. Generate a script to restore the original default tablespaces

Before changing the users, it's useful to preserve their current default tablespace assignments.

SET ECHO OFF
SET FEEDBACK OFF
SET HEADING OFF
SET PAGESIZE 0
SET LINESIZE 32767
SET TRIMSPOOL ON
SET VERIFY OFF
SET TERMOUT OFF

SPOOL restore_non_oracle_users_default_ts.sql

SELECT 'ALTER USER "' || username ||
       '" DEFAULT TABLESPACE "' ||
       default_tablespace || '";'
FROM   dba_users
WHERE  oracle_maintained = 'N'
AND    default_tablespace <> 'SYSTEM'
ORDER  BY username;

SPOOL OFF

This produces a separate SQL file containing the original default tablespace assignments for the users currently matching the filter.

💡 Why is this approach useful?

  • Automation: Generate commands for multiple users in one query.
  • Consistency: Apply the same change across the intended set of accounts.
  • Reversibility: Keep a separate script to restore the captured tablespace assignments.
  • Maintainability: Store generated scripts for review, auditing, and controlled execution.

⚠️ Important considerations

  • Changing a user's default tablespace does not move existing objects or change their tablespace placement.
  • SYSTEM is a critical Oracle-managed tablespace and should generally not be used as the default tablespace for application users. Prefer an appropriate application tablespace.
  • Generate and review the restoration script before changing the users. The restoration query must be run against the original assignments; after the change, the original tablespace values are no longer available from that query.
  • These scripts depend on access to DBA_USERS and should be tested in a non-production environment first.

The takeaway: A simple SQL query combined with SQL*Plus SPOOL can turn repetitive DBA work into a reusable, reviewable SQL script.

💬 Do you use SQL generation to automate Oracle Database administration tasks?

#OracleDatabase #OracleDBA #SQL #SQLPlus #DatabaseAdministration #Automation