Saturday, December 5, 2026

How to Create a Database Link from an On-Premises Oracle Database to Oracle Autonomous Database

 


By Shashi Ranjan Singh

Introduction

Database Links (DBLinks) are widely used in Oracle Database environments to access objects residing in remote databases. They allow applications and DBAs to query remote tables, execute SQL statements, and exchange data without requiring separate connections for every operation.

In hybrid database environments, where organizations maintain both on-premises Oracle Databases and Oracle Autonomous Database (ADB) on Oracle Cloud Infrastructure (OCI), creating database links between these environments becomes an important requirement.

For example, an application running on an on-premises Oracle Database may need to access customer information stored in an Autonomous Database. Instead of developing a separate integration mechanism, we can use an Oracle Database Link to establish connectivity between the two databases.

In this article, we will explore how to create a database link from an on-premises Oracle Database to an Oracle Autonomous Database using two authentication methods:

  1. Mutual TLS (mTLS) – Requires an Autonomous Database wallet.

  2. TLS – Does not require a client wallet when the Autonomous Database is configured to allow TLS connections.

We will also discuss common configuration mistakes and troubleshooting techniques.

1. Environment Overview

For this demonstration, consider the following architecture.

Source Database (On-Premises)

ParameterValue
Hostnameora-db01.example.com
Database NamePRODDB
PDB NamePRODPDB
Oracle Version19c
Database UserAPP_OWNER

Target Database (OCI Autonomous Database)

ParameterValue
Database NameFINADB
Database Servicefinadb_high
Database UserREMOTE_APP
Connection ProtocolTCPS
OCI RegionMumbai

The objective is to create a database link named FINA_ADB_LINK from the on-premises database PRODPDB to the Autonomous Database FINADB.

The database link will allow users on the source database to access remote objects in the Autonomous Database.

Important: The source Oracle Database must be version 19c or later for the database link configuration described in this article.

2. Understanding TLS and mTLS Authentication

Before creating the database link, we need to understand the authentication options supported by Autonomous Database.

Autonomous Database supports secure connections using TLS and Mutual TLS (mTLS).

The connection method depends on the network configuration of the target Autonomous Database.

2.1 TLS (Transport Layer Security)

TLS provides encrypted communication between the source database and Autonomous Database.

With TLS authentication:

  • Communication is encrypted.

  • A client wallet is not required for the database connection.

  • The client verifies the server certificate.

  • The connection typically uses port 1521.

2.2 mTLS (Mutual Transport Layer Security)

mTLS provides an additional authentication layer by requiring both the client and server to authenticate their identities using certificates.

With mTLS:

  • Communication is encrypted.

  • The client requires an Autonomous Database wallet.

  • The wallet contains the required client certificates and connection configuration.

  • The connection typically uses port 1522.

2.3 How to Check the Authentication Configuration

Log in to the OCI Console and navigate to:

Autonomous Database → FINADB → Network

Check the Mutual TLS Authentication setting.

  • If mTLS is required, you must use the wallet-based connection.

  • If mTLS is not required, you can use the TLS connection without downloading a client wallet.

<IMPORTANT>Make sure the source database server can reach the Autonomous Database endpoint over the required port and that OCI network access controls permit the connection.</IMPORTANT>

3. Creating a DBLink Using mTLS Authentication

In this section, we will create a database link using the Autonomous Database wallet.

Step 1: Download the Autonomous Database Wallet

Log in to the OCI Console and navigate to the target Autonomous Database named FINADB.

Select:

Autonomous Database → FINADB → Database Connection → Download Wallet

Provide a wallet password and download the wallet ZIP file.

For this example, the downloaded file is:

Wallet_FINADB.zip

Step 2: Copy the Wallet to the On-Premises Database Server

Copy the downloaded wallet to the on-premises database server.

For example:

scp Wallet_FINADB.zip oracle@ora-db01.example.com:/tmp/

Connect to the source database server using the Oracle software owner.

Step 3: Create a Dedicated Wallet Directory

It is recommended to maintain a separate wallet directory for each Autonomous Database.

For this demonstration, we will use:

mkdir -p /u01/app/oracle/wallets/FINADB

Extract the wallet:

unzip /tmp/Wallet_FINADB.zip \
-d /u01/app/oracle/wallets/FINADB

Verify the extracted files:

ls -l /u01/app/oracle/wallets/FINADB

You should find files similar to:

cwallet.sso
ewallet.p12
keystore.jks
truststore.jks
sqlnet.ora
tnsnames.ora

The exact files may vary depending on the wallet package and OCI configuration.

Step 4: Configure the Wallet Directory

Navigate to the wallet directory and inspect the sqlnet.ora file.

cd /u01/app/oracle/wallets/FINADB

cat sqlnet.ora

The file may contain a wallet directory configuration similar to:

WALLET_LOCATION =
  (SOURCE =
    (METHOD = file)
    (METHOD_DATA =
      (DIRECTORY="?/network/admin")
    )
  )

SSL_SERVER_DN_MATCH=yes

Update the wallet directory to the actual location on the database server:

WALLET_LOCATION =
  (SOURCE =
    (METHOD = file)
    (METHOD_DATA =
      (DIRECTORY="/u01/app/oracle/wallets/FINADB")
    )
  )

SSL_SERVER_DN_MATCH=yes

This ensures that Oracle Net can locate the wallet files.

Note: Keep the wallet directory and file permissions restricted to the appropriate operating-system account. Do not expose wallet passwords or private keys.

Step 5: Configure TNS_ADMIN and Verify Connectivity

Set the TNS_ADMIN environment variable to point to the wallet directory.

export TNS_ADMIN=/u01/app/oracle/wallets/FINADB

Check the Autonomous Database connection aliases:

cat $TNS_ADMIN/tnsnames.ora

You should find connection aliases similar to:

finadb_high =
 (description =
   (retry_count=20)
   (retry_delay=3)
   (address =
     (protocol=tcps)
     (port=1522)
     (host=adb.ap-mumbai-1.oraclecloud.com)
   )
   (connect_data =
     (service_name=finadb_high.adb.oraclecloud.com)
   )
   (security =
     (ssl_server_dn_match=yes)
   )
 )

The hostname and service name above are illustrative. Always use the actual values provided in the downloaded wallet.

Test the connection using SQL*Plus:

sqlplus admin@finadb_high

Enter the Autonomous Database ADMIN password when prompted.

If the connection succeeds, the wallet and network configuration are working.

Step 6: Create a User in Autonomous Database

If you already have a dedicated user for database link connectivity, you can skip this step.

Otherwise, connect to Autonomous Database using the ADMIN account and create a dedicated user.

CREATE USER REMOTE_APP
IDENTIFIED BY "RemoteApp#2026";

GRANT CREATE SESSION TO REMOTE_APP;

GRANT SELECT ANY TABLE TO REMOTE_APP;

For production environments, avoid granting broad privileges such as SELECT ANY TABLE unless they are genuinely required. Prefer granting access to specific schemas and objects.

For example:

GRANT SELECT ON FINANCE.CUSTOMERS TO REMOTE_APP;

GRANT SELECT ON FINANCE.ACCOUNTS TO REMOTE_APP;

Step 7: Create the Database Link on the On-Premises Database

Now connect to the source database PRODPDB using the database user that will own the database link.

For this example, we will create a database link named:

FINA_ADB_LINK

Execute the following SQL statement:

CREATE DATABASE LINK FINA_ADB_LINK
CONNECT TO REMOTE_APP
IDENTIFIED BY "RemoteApp#2026"
USING
'(description=
   (retry_count=20)
   (retry_delay=3)
   (address=
     (protocol=tcps)
     (port=1522)
     (host=adb.ap-mumbai-1.oraclecloud.com)
   )
   (connect_data=
     (service_name=finadb_high.adb.oraclecloud.com)
   )
   (security=
     (my_wallet_directory=/u01/app/oracle/wallets/FINADB)
     (ssl_server_dn_match=true)
   )
 )';

Important: Replace the hostname, service name, and wallet directory with the actual values from your Autonomous Database wallet configuration.

The my_wallet_directory parameter specifies the location of the wallet used for the secure connection.

The ssl_server_dn_match=true setting enables server distinguished-name verification.

Step 8: Test the Database Link

After creating the database link, verify the connection.

SELECT * FROM dual@FINA_ADB_LINK;

Expected output:

D
-
X

Check the remote database identity:

SELECT
    name,
    db_unique_name,
    open_mode
FROM v$database@FINA_ADB_LINK;

If the query executes successfully, the database link is working.

You can also query a remote application table:

SELECT *
FROM FINANCE.CUSTOMERS@FINA_ADB_LINK;

The source database can now access the permitted objects in Autonomous Database.

4. Creating a DBLink Using TLS Authentication (Without Wallet)

Now let's look at the second scenario.

If the target Autonomous Database is configured with mTLS authentication set to Not required, we can create a database link without using the Autonomous Database client wallet.

This approach is simpler because we only need to configure the appropriate Oracle Net connection descriptor.

Step 1: Get the TLS Connection String from OCI

Log in to the OCI Console and navigate to:

Autonomous Database → FINADB → Database Connection

Select the TLS connection option and copy the connection string.

For TLS connectivity, the connection generally uses port 1521.

The hostname and service name must match the values provided by OCI.

Step 2: Configure the TNS Entry on the Source Database Server

Edit the tnsnames.ora file on the on-premises database server.

vi $ORACLE_HOME/network/admin/tnsnames.ora

Add the following entry:

FINADB_TLS =
 (description =
   (retry_count=20)
   (retry_delay=3)
   (address =
     (protocol=tcps)
     (port=1521)
     (host=adb.ap-mumbai-1.oraclecloud.com)
   )
   (connect_data =
     (service_name=finadb_high.adb.oraclecloud.com)
   )
   (security =
     (ssl_server_dn_match=yes)
   )
 )

Save the file.

Note: Use the TLS connection descriptor supplied by OCI. Do not assume that changing the port from 1522 to 1521 in an mTLS descriptor is sufficient for every environment.

Step 3: Verify the TLS Connection

Set the appropriate Oracle Net configuration directory if required:

export TNS_ADMIN=$ORACLE_HOME/network/admin

Test the connection:

tnsping FINADB_TLS

You can also test an actual database connection using SQL*Plus:

sqlplus admin@FINADB_TLS

If the connection is successful, proceed with database link creation.

Step 4: Create the Database Link

Connect to the source database PRODPDB and execute:

CREATE DATABASE LINK FINA_ADB_LINK
CONNECT TO REMOTE_APP
IDENTIFIED BY "RemoteApp#2026"
USING 'FINADB_TLS';

Here:

  • FINA_ADB_LINK is the database link name.

  • REMOTE_APP is the remote Autonomous Database username.

  • FINADB_TLS is the TNS alias configured on the source database server.

Step 5: Test the Database Link

Execute:

SELECT * FROM dual@FINA_ADB_LINK;

You should receive:

D
-
X

This confirms that the database link can connect to the Autonomous Database using TLS without a client wallet.

5. Common Errors and Troubleshooting

While configuring database links between on-premises Oracle Database and Autonomous Database, you may encounter a few common errors.

Let's discuss some of them.

5.1 ORA-29002: SSL Transport Detected Invalid or Obsolete Server Certificate

This error can occur when the connection descriptor uses an IP address instead of the original Autonomous Database hostname.

For example, avoid configuring:

(host=10.10.20.15)

Instead, use the original hostname supplied by OCI:

(host=adb.ap-mumbai-1.oraclecloud.com)

The hostname is important for SSL certificate verification and server identity matching.

Also verify that the client wallet and trusted certificates are valid.

5.2 ORA-02085: Database Link Connects to Another Database

You may encounter the following error:

ORA-02085: database link FINA_ADB_LINK connects to FINADB

This can happen when the GLOBAL_NAMES parameter is enabled and the database link name does not match the remote database's global database name.

Check the parameter on the source database:

SHOW PARAMETER global_names;

If it is enabled, Oracle enforces global database link naming rules.

You can check the remote database global name using:

SELECT * FROM global_name@FINA_ADB_LINK;

If your operational requirements permit non-matching database link names, the DBA can evaluate setting GLOBAL_NAMES to FALSE.

ALTER SYSTEM SET GLOBAL_NAMES=FALSE SCOPE=BOTH;

Important: This is a database-wide configuration change. Evaluate the impact on existing database links and application dependencies before changing it in production.

5.3 ORA-12154: TNS Could Not Resolve the Connect Identifier

This error commonly occurs when Oracle Net cannot resolve the TNS alias.

Check the following:

  • Verify that the tnsnames.ora file contains the correct alias.

  • Confirm that TNS_ADMIN points to the expected directory.

  • Check for syntax errors in the connection descriptor.

  • Verify that the database process can access the required Oracle Net configuration files.

Useful command:

tnsping FINADB_TLS

5.4 ORA-12541: TNS No Listener

This error indicates that the connection cannot reach the expected listener endpoint.

Check:

  • Network connectivity from the source server.

  • Firewall rules for the required TCPS port.

  • OCI network security lists or NSGs.

  • Autonomous Database endpoint accessibility.

  • DNS resolution of the OCI hostname.

For example:

nslookup adb.ap-mumbai-1.oraclecloud.com

5.5 ORA-01017: Invalid Username or Password

This error indicates that the authentication credentials supplied for the remote database are incorrect or cannot be authenticated.

Verify:

  • Remote username.

  • Remote password.

  • Whether the user is locked or expired.

  • Whether the database link was created with the correct credentials.

If necessary, recreate the database link with the correct credentials.

6. Important DBA Considerations

Before implementing this configuration in production, keep the following points in mind:

  1. Database Version: Ensure the source Oracle Database is running a supported version (19c or later for this approach).

  2. Network Connectivity: Verify that the on-premises server can reach the Autonomous Database endpoint over the required port.

  3. Wallet Management: For mTLS, keep the wallet in a secure location and establish a process for wallet rotation and updates.

  4. RAC Environment: If the source database is running on RAC, ensure that the wallet is accessible from every node where database processes may establish outbound connections. A shared ACFS location is one possible approach.

  5. TNS_ADMIN Configuration: Ensure that Oracle Net configuration is available to the database server processes, not just the interactive shell session.

  6. Privileges: Grant only the minimum required privileges to the remote database user.

  7. Connection Testing: Always test the database link with a simple query before using it in application code or production jobs.

  8. Password Security: Avoid embedding production passwords directly in scripts, SQL deployment logs, or shared documentation. Use appropriate secret-management procedures.

7. Conclusion

Creating a database link from an on-premises Oracle Database to Oracle Autonomous Database is straightforward once the required network and authentication configurations are understood.

The main difference between TLS and mTLS connectivity is the requirement for a client wallet.

With mTLS, we need to download and configure the Autonomous Database wallet on the source database server and provide its location in the database link connection descriptor.

With TLS, provided that the Autonomous Database allows TLS connections, we can configure a TNS alias and create the database link using the standard USING clause.

Both approaches provide secure connectivity between on-premises Oracle Database and Autonomous Database, enabling organizations to integrate their existing database environments with Oracle Cloud Infrastructure.

Happy Learning!

— Shashi Ranjan Singh

Stop and Start All Oracle Database Homes Using Shell Script and SRVCTL

 

By Shashi Ranjan Singh

Managing multiple Oracle Database Homes on a single server can become challenging, especially when you need to stop and start all database instances without shutting down the Grid Infrastructure services.

In Oracle RAC and standalone environments managed by Oracle Restart or Grid Infrastructure, the srvctl utility provides an efficient way to manage database services and instances.

In this article, we will explore how to automate the shutdown and startup of all Oracle Database Homes configured in /etc/oratab using simple shell scripts and the srvctl stop home and srvctl start home commands.

1. Why Do We Need This Script?

Consider a server hosting multiple Oracle Database versions, with several databases running from different Oracle Homes.

During certain maintenance activities, such as Oracle Database patching or Grid Infrastructure maintenance, you may need to stop all database instances while keeping Grid Infrastructure services running.

One approach is to use:

crsctl stop crs

However, this command stops the entire Clusterware stack, including Grid Infrastructure services.

In some maintenance scenarios, shutting down Grid Infrastructure is unnecessary. We only need to stop the database instances and bring them back online after the maintenance activity.

Oracle provides the following SRVCTL commands for this purpose:

  • srvctl stop home: Stops the resources associated with a specified Oracle Home and saves their state.

  • srvctl start home: Restarts the resources using the previously saved state file.

Instead of executing these commands manually for every Oracle Home, we can automate the process using shell scripts.

2. Environment Details

Let's consider the following example environment.

Hostname: ora-prod-db02

Oracle user: oracle

Grid Infrastructure Home:

/u01/app/19.0.0/grid

Oracle Database Homes:

/u01/app/oracle/product/12.2.0.1/dbhome_1
/u01/app/oracle/product/19.0.0/dbhome_1
/u01/app/oracle/product/19.0.0/dbhome_2
/u01/app/oracle/product/21.0.0/dbhome_1

Databases running on the server:

DatabaseOracle Home
FINCDB19.0.0/dbhome_1
HRDB19.0.0/dbhome_1
SALESCDB19.0.0/dbhome_2
PAYDB12.2.0.1/dbhome_1
REPORTCDB21.0.0/dbhome_1

The objective is to stop all database instances across these Oracle Homes without stopping ASM or Grid Infrastructure services.

3. Understanding the /etc/oratab File

The /etc/oratab file contains the database SID and corresponding Oracle Home information.

Let's look at an example:

[oracle@ora-prod-db02 ~]$ cat /etc/oratab

PAYDB:/u01/app/oracle/product/12.2.0.1/dbhome_1:N
FINCDB:/u01/app/oracle/product/19.0.0/dbhome_1:N
HRDB:/u01/app/oracle/product/19.0.0/dbhome_1:N
SALESCDB:/u01/app/oracle/product/19.0.0/dbhome_2:N
REPORTCDB:/u01/app/oracle/product/21.0.0/dbhome_1:N
+ASM:/u01/app/19.0.0/grid:N

We will use this file as the source to identify all configured Oracle Database Homes.

Notice that multiple databases can share the same Oracle Home. Therefore, we need to remove duplicate Oracle Home paths before executing the SRVCTL commands.

We also need to exclude the ASM entry because our objective is to manage database instances only.

4. Shell Script to Stop All Oracle Database Homes

Create a shell script named stop_all_dbhomes.sh.

#!/bin/bash

ORATAB="/etc/oratab"

# Extract unique Oracle Database Homes
for DBHOME in $(grep -v '^#' "$ORATAB" \
    | grep -v '^+' \
    | cut -d: -f2 \
    | sort -u)
do

    echo "=========================================="
    echo "Stopping Database Home: $DBHOME"
    echo "=========================================="

    if [ -x "$DBHOME/bin/srvctl" ]; then

        # Preserve the previous state file
        if [ -f "$DBHOME/state_file.log" ]; then
            mv "$DBHOME/state_file.log" \
               "$DBHOME/state_file.old"
        fi

        # Stop database resources from this Oracle Home
        "$DBHOME/bin/srvctl" stop home \
            -o "$DBHOME" \
            -s "$DBHOME/state_file.log"

        if [ $? -eq 0 ]; then
            echo "Successfully stopped: $DBHOME"
        else
            echo "ERROR: Failed to stop: $DBHOME"
        fi

    else
        echo "ERROR: SRVCTL not found in $DBHOME"
    fi

done

echo "=========================================="
echo "Database Home shutdown operation completed"
echo "=========================================="

Make the script executable:

chmod +x stop_all_dbhomes.sh

Execute the script using the Oracle software owner:

./stop_all_dbhomes.sh

Expected Output

[oracle@ora-prod-db02 ~]$ ./stop_all_dbhomes.sh

==========================================
Stopping Database Home: /u01/app/oracle/product/12.2.0.1/dbhome_1
==========================================
Successfully stopped: /u01/app/oracle/product/12.2.0.1/dbhome_1

==========================================
Stopping Database Home: /u01/app/oracle/product/19.0.0/dbhome_1
==========================================
Successfully stopped: /u01/app/oracle/product/19.0.0/dbhome_1

==========================================
Stopping Database Home: /u01/app/oracle/product/19.0.0/dbhome_2
==========================================
Successfully stopped: /u01/app/oracle/product/19.0.0/dbhome_2

==========================================
Stopping Database Home: /u01/app/oracle/product/21.0.0/dbhome_1
==========================================
Successfully stopped: /u01/app/oracle/product/21.0.0/dbhome_1

==========================================
Database Home shutdown operation completed
==========================================

5. Verify That All Database Instances Are Stopped

After executing the shutdown script, verify the database background processes.

ps -ef | grep pmon

Expected output:

grid      2451      1  0 10:15 ?  00:00:00 asm_pmon_+ASM
oracle   28140      1  0 10:20 ?  00:00:00 grep pmon

As shown above, the ASM instance is still running, while the database PMON processes are no longer present.

This confirms that database instances have been stopped without shutting down the ASM instance.

6. Shell Script to Start All Oracle Database Homes

Once the maintenance activity is completed, we can start the database instances using the state files generated during the shutdown operation.

Create another shell script named start_all_dbhomes.sh.

#!/bin/bash

ORATAB="/etc/oratab"

# Extract unique Oracle Database Homes
for DBHOME in $(grep -v '^#' "$ORATAB" \
    | grep -v '^+' \
    | cut -d: -f2 \
    | sort -u)
do

    echo "=========================================="
    echo "Starting Database Home: $DBHOME"
    echo "=========================================="

    if [ -x "$DBHOME/bin/srvctl" ]; then

        if [ -f "$DBHOME/state_file.log" ]; then

            # Start database resources using saved state
            "$DBHOME/bin/srvctl" start home \
                -o "$DBHOME" \
                -s "$DBHOME/state_file.log"

            if [ $? -eq 0 ]; then
                echo "Successfully started: $DBHOME"
            else
                echo "ERROR: Failed to start: $DBHOME"
            fi

        else
            echo "WARNING: State file not found for $DBHOME"
        fi

    else
        echo "ERROR: SRVCTL not found in $DBHOME"
    fi

done

echo "=========================================="
echo "Database Home startup operation completed"
echo "=========================================="

Make the script executable:

chmod +x start_all_dbhomes.sh

Execute the script:

./start_all_dbhomes.sh

Expected Output

[oracle@ora-prod-db02 ~]$ ./start_all_dbhomes.sh

==========================================
Starting Database Home: /u01/app/oracle/product/12.2.0.1/dbhome_1
==========================================
Successfully started: /u01/app/oracle/product/12.2.0.1/dbhome_1

==========================================
Starting Database Home: /u01/app/oracle/product/19.0.0/dbhome_1
==========================================
Successfully started: /u01/app/oracle/product/19.0.0/dbhome_1

==========================================
Starting Database Home: /u01/app/oracle/product/19.0.0/dbhome_2
==========================================
Successfully started: /u01/app/oracle/product/19.0.0/dbhome_2

==========================================
Starting Database Home: /u01/app/oracle/product/21.0.0/dbhome_1
==========================================
Successfully started: /u01/app/oracle/product/21.0.0/dbhome_1

==========================================
Database Home startup operation completed
==========================================

7. Verify That All Database Instances Are Online

After executing the startup script, check the PMON processes again.

ps -ef | grep pmon

Expected output:

grid      2451      1  0 10:15 ?  00:00:00 asm_pmon_+ASM
oracle   30210      1  0 10:45 ?  00:00:00 ora_pmon_PAYDB
oracle   30215      1  0 10:45 ?  00:00:00 ora_pmon_FINCDB
oracle   30220      1  0 10:45 ?  00:00:00 ora_pmon_HRDB
oracle   30225      1  0 10:45 ?  00:00:00 ora_pmon_SALESCDB
oracle   30230      1  0 10:45 ?  00:00:00 ora_pmon_REPORTCDB

All database instances are online again, and the ASM instance has remained running throughout the operation.

8. Understanding the Script Logic

Let's understand the commands used in both scripts.

Step 1: Remove commented lines

grep -v '^#' /etc/oratab

This excludes lines starting with # from the /etc/oratab file.

Step 2: Exclude ASM entries

grep -v '^+'

ASM entries generally start with +, such as +ASM. We exclude these entries because we only want Oracle Database Homes.

Step 3: Extract Oracle Home paths

cut -d: -f2

The colon (:) is used as the field delimiter, and -f2 extracts the second field containing the Oracle Home path.

Step 4: Sort and remove duplicate Oracle Homes

sort -u

This sorts the Oracle Home paths and removes duplicates.

For example, if three databases are configured under the same Oracle Home, that home will appear only once in the output.

Step 5: Execute SRVCTL commands

For each unique Oracle Home, the script executes:

$DBHOME/bin/srvctl stop home \
    -o $DBHOME \
    -s $DBHOME/state_file.log

The -o parameter specifies the Oracle Home, while -s specifies the state file used to save the resource state.

During startup, the same state file is supplied to the corresponding srvctl start home command.

9. Important Considerations

Before implementing these scripts in a production environment, consider the following points:

  1. Run the scripts using the appropriate Oracle software owner and ensure that the user has the required permissions.

  2. Verify that the /etc/oratab file contains the correct Oracle Home paths.

  3. Ensure that the respective Oracle Home contains a compatible srvctl utility.

  4. Keep the state files safe until the startup operation is completed.

  5. Review the SRVCTL output and verify the actual resource status rather than relying only on the script's exit code.

  6. Test the scripts in a non-production environment before using them during planned maintenance.

Important: srvctl stop home and srvctl start home behavior and supported resource types can vary across Oracle versions and configurations. Validate the commands against the installed Oracle version and Oracle Restart or RAC environment. These scripts are not a replacement for a complete Clusterware shutdown or startup procedure.

10. Conclusion

When managing multiple Oracle Database Homes on the same server, manually stopping and starting individual database instances can be time-consuming and error-prone.

By combining the /etc/oratab file with shell scripting and SRVCTL, we can automate the shutdown and startup of database resources across multiple Oracle Homes.

The biggest advantage of this approach is that we can stop and restart database instances while keeping Grid Infrastructure services, including ASM, running.

This can be particularly useful during database maintenance and patching activities where shutting down the complete Grid Infrastructure stack is not required.

Happy Learning!

— Shashi Ranjan Singh

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.