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

Generating SQL scripts using the VALUES clause

Generating SQL Scripts Using the VALUES Clause in Oracle AI Database 26ai 🚀

Sometimes, a small SQL feature can make a big difference in developer productivity.

Oracle AI Database 26ai introduces a table value constructor for SELECT, allowing the VALUES clause to act as an inline table in the FROM or WITH clause.

Why is this useful? You can work with a small set of values directly in SQL without creating a physical table or writing multiple UNION ALL statements.

💡 A practical use case: Dynamically generating SQL scripts

Suppose you're building Oracle database demos or lab environments and need to create database users with specific privileges.

Instead of manually writing every GRANT statement, you can generate them dynamically:

select
'grant ' || privilege || ' to singhsha;'
from
(
values
('create assertion'),
('create domain'),
('create job'),
('create mle'),
('create session'),
('debug connect session'),
('execute dynamic mle'),
('create materialized view'),
('create procedure'),
('create property graph'),
('create sequence'),
('create synonym'),
('create table'),
('create trigger'),
('create type'),
('create view')
) p (privilege);

The VALUES clause creates an inline table named p, with a column called privilege. The SELECT statement then generates a GRANT command for each row.

The result? A ready-to-review list of SQL statements that can be incorporated into an initialization script, checked into Git, and reused when setting up demo environments.

Which results in this neat script:

grant create assertion to singhsha; grant create domain to singhsha; grant create job to singhsha; grant create mle to singhsha; grant create session to singhsha; grant debug connect session to singhsha; grant execute dynamic mle to singhsha; grant create materialized view to singhsha; grant create procedure to singhsha; grant create property graph to singhsha; grant create sequence to singhsha; grant create synonym to singhsha; grant create table to singhsha; grant create trigger to singhsha; grant create type to singhsha; grant create view to singhsha;

After careful review, it can be deployed to my demo/lab environment and checked into Git.


Why I like this approach

✅ Less boilerplate SQL

✅ Better readability and maintainability

✅ No need for repetitive UNION ALL queries

✅ Convenient generation of scripts for database initialization, migrations, and administrative tasks

The generated statements should always be reviewed before execution, particularly when dealing with database privileges.

The takeaway: The VALUES clause isn't just a convenient way to define inline data. In Oracle AI Database 26ai, it can also simplify the process of generating SQL scripts dynamically.

📚 Explore the Oracle AI Database 26ai documentation to learn more about the VALUES clause.

Happy scripting!

#OracleDatabase #Oracle26ai #SQL #DatabaseDevelopment #Automation #PLSQL