Bajwa Consulting Need senior Oracle DBA help? Performance tuning, Cloud migrations, GoldenGate, backup and DR. Plus 70+ free DBA scripts.
Visit bajwaconsulting.com →

Thursday, December 3, 2026

Agentic AI Explained: What It Means for DBAs

"Agentic AI" is one of the most used terms in technology right now. This post explains what it means in plain language, how an AI agent works, and what it could mean for database administrators, including the risks.

From chatbot to agent

A chatbot answers questions. You ask, it replies, and you do the work. An AI agent is given a goal and works towards it on its own: it plans steps, uses tools (runs a query, reads a file, calls an API), looks at the results and decides what to do next, until the goal is reached or it needs a human.

ChatbotScripted automationAI agent
InputA questionA fixed triggerA goal
StepsOne answerFixed, written in advanceChosen as it goes
Uses toolsNo, or rarelyYes, the same ones every timeYes, picks which ones to use
Handles surprisesNot applicableOnly if you coded for themOften, by reasoning about results
PredictabilityMediumHighLower, needs guardrails

How an agent works

Most agents follow the same loop:

  1. Goal: "Find out why the order database was slow between 2 and 3 pm."
  2. Plan: the model decides the first step, for example "get the top wait events for that hour".
  3. Act: it calls a tool, such as a read-only SQL query or an AWR report.
  4. Observe: it reads the result.
  5. Repeat: based on what it saw, it chooses the next step, such as looking at the top SQL for that wait event, and keeps going until it can answer, or stops and asks a person.

The building blocks

  • A large language model (LLM): the "brain" that understands the goal, reasons about results and writes the next step.
  • Tools: functions the agent is allowed to call, such as run a query, search documents, read a log, open a ticket. The agent can only do what its tools let it do.
  • Memory and context: what has happened so far in this task, plus knowledge it can look up, such as runbooks, past incidents or documentation (often called retrieval-augmented generation, RAG).
  • Instructions and limits: what the agent is for, what it must never do, and when it must ask a human.
  • Orchestration: the code that runs the loop, records every step and enforces the limits. On AWS, for example, Amazon Bedrock Agents provides this as a managed service; there are also open-source frameworks.

Some systems use several agents, each with one job (one gathers data, one analyses, one writes the report), coordinated by a supervisor agent.

What it could mean for DBAs

  • First-response triage: when an alert fires, an agent gathers the alert log, top waits, blocking sessions and recent changes, and writes a summary before the on-call DBA logs in.
  • Health checks and reports: run the daily checks, compare with yesterday and explain only what changed.
  • Runbook assistant: answer "how do we fail over the sales database?" from your own runbooks, with links to the source.
  • Migration helper: compare schemas, list objects that will not convert, and draft the plan for a review.
  • Ticket work: draft the steps for routine requests (new user, add space), for a DBA to approve.

In all of these, the DBA's judgment does not go away. The agent does the gathering and first draft; the DBA decides.

Risks and guardrails

  • Agents can be wrong with confidence. An LLM can misread a result or invent a detail. Check its conclusions against the evidence it shows.
  • Least privilege. Give an agent read-only access to start. Never give it SYSDBA, production write access or the ability to drop objects.
  • Human approval for changes. Anything that changes a system (kill a session, resize, restart, change a parameter) should need a person to approve it.
  • Prompt injection. Text inside a log, ticket or web page can try to give the agent instructions. Treat everything the agent reads as data, and limit what its tools can do.
  • Logging and audit. Record every tool call and result, so you can see exactly what the agent did and why.
  • Data protection. Know where your data goes. Do not send customer data or passwords to a service your company has not approved.
  • Cost. Every step uses model calls. Set limits on how many steps and how much spend one task can use.

How to start

  1. Pick one narrow, read-only task, such as "summarize last night's alert log errors".
  2. Give the agent only the tools that task needs.
  3. Run it alongside your normal process for a few weeks and compare its output with what your team found.
  4. Only then widen its scope, one tool at a time, keeping a human approval step for any change.

Agentic AI is best seen as a fast, tireless junior assistant: very useful for gathering and drafting, but it needs clear limits and a senior person who checks its work.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Tuesday, December 1, 2026

AWS Basics: Your Account, S3, EC2, CloudFront and Route 53

If you are new to Amazon Web Services (AWS), this post covers how to open an account safely and what four of the most used services do: S3, EC2, CloudFront and Route 53. As an example, my own website, bajwaconsulting.com, runs on S3, CloudFront and Route 53.

1. Opening an AWS account

  1. Go to aws.amazon.com/free and choose Create free account.
  2. Enter an email address for the account (the root user) and an account name. Use an address you will keep, ideally a shared team address for company accounts.
  3. Choose an account plan. New accounts choose a Free plan or a Paid plan. New customers get up to $200 in credits: $100 at sign-up and up to $100 more by trying key services. The Free plan ends after 6 months or when the credits are used up, whichever comes first.
  4. Add contact details and a payment card (required even for the Free plan), and verify your phone number.
  5. Choose the Basic support plan, which is free.

Free Tier details change from time to time; check the AWS Free Tier page for the current terms before you build anything.

2. Secure the account first

  • Turn on MFA for the root user (Security credentials in the account menu). The root user can do everything, including closing the account.
  • Stop using the root user for daily work. Create an administrator user in IAM Identity Center (or an IAM user with MFA) and sign in with that.
  • Create a budget alert. In Billing, create a monthly cost budget (for example $10) that emails you at 80% and 100%.
  • Pick one Region, for example us-east-1 (N. Virginia) or us-east-2 (Ohio), and create your resources there, so you always know where they are.
  • Never put access keys in code or on GitHub. Use aws configure sso for the AWS CLI instead of long-term keys.

3. Amazon S3: storage for files

Amazon Simple Storage Service (S3) stores files, called objects, in containers called buckets. It is not a disk you mount; you upload and download objects over HTTPS or with the AWS CLI.

  • Bucket names are unique across all of AWS, for example mycompany-db-backups-2026.
  • S3 is designed for very high durability, and copies your data across several Availability Zones in the Region.
  • Storage classes trade price for access speed: S3 Standard for frequent use, Standard-IA for infrequent access, and Glacier classes for archives you rarely read.
  • Lifecycle rules move or delete objects automatically, for example "move backups to Glacier after 30 days, delete after 1 year".
  • New buckets block public access by default. Keep it that way unless you deliberately host public files.
aws s3 mb s3://mycompany-db-backups-2026
aws s3 cp expdp_full.dmp s3://mycompany-db-backups-2026/exports/
aws s3 ls s3://mycompany-db-backups-2026/exports/
aws s3 sync ./website s3://my-website-bucket

DBA uses: database backups and Data Pump dumps, moving files during a migration, and hosting a static website.

4. Amazon EC2: virtual servers

Amazon Elastic Compute Cloud (EC2) gives you virtual servers, called instances, that you control like any Linux or Windows server.

  • Instance type: the size, such as t3.micro (small, for tests) or r6i.2xlarge (memory-optimized, good for databases).
  • AMI: the image the server starts from, such as Oracle Linux, Amazon Linux or Windows Server.
  • EBS volumes: the disks. Choose gp3 for most uses and io2 for demanding databases.
  • Security groups: the firewall. Allow only the ports and source addresses you need, for example SSH from your own IP only.
  • Key pairs: used to log in over SSH. Keep the private key safe.
  • Pricing: On-Demand by the second, or lower prices with Savings Plans or Reserved Instances for servers you run all the time. A stopped instance does not charge for compute, but its EBS disks still cost money.

DBA uses: running Oracle Database on EC2 when you need full control of the database and operating system (single instance and Data Guard work well; Oracle RAC needs special shared-storage solutions on EC2), GoldenGate hubs, and jump hosts for administration.

5. Amazon CloudFront: a fast, secure front door

CloudFront is AWS's content delivery network (CDN). It keeps copies of your website files in edge locations around the world, so visitors download them from a location near them.

  • The origin is where the real files live, often an S3 bucket or a web server.
  • Use an Origin Access Control (OAC) so the S3 bucket stays private and only CloudFront can read it.
  • Add free HTTPS with a certificate from AWS Certificate Manager. For CloudFront, the certificate must be created in us-east-1.
  • After you update files, create an invalidation so visitors get the new version:
aws cloudfront create-invalidation --distribution-id E1234567890ABC --paths "/*"

6. Amazon Route 53: DNS and domains

Route 53 is AWS's DNS service. It turns names like www.example.com into the addresses of your servers or CloudFront distribution.

  • You can register a domain in Route 53, or keep it at your current registrar and point its name servers to Route 53.
  • A hosted zone holds the DNS records for one domain.
  • Common records: A (name to IPv4 address), CNAME (name to another name), MX (mail servers), TXT (verification, such as for Google Search Console).
  • Alias records point the bare domain (example.com) straight to CloudFront or a load balancer, which a normal CNAME cannot do.
  • Health checks and routing policies can send traffic to a standby site if the main one fails.

How they fit together: a static website

Visitor --> Route 53 (www.example.com)
        --> CloudFront (HTTPS, cached at the edge)
        --> S3 bucket (private, holds the HTML, CSS and images)

This setup costs very little for a small site, has no servers to patch, and handles traffic spikes on its own.

Avoiding surprise bills

  • Set a budget alert on day one.
  • Stop or terminate EC2 instances you are not using, and delete their EBS volumes and snapshots if you no longer need them.
  • Release unused Elastic IP addresses and delete NAT gateways from test setups; both charge by the hour.
  • Check Billing → Bills and Cost Explorer once a week while you are learning.

If you are a DBA moving databases to AWS, my book AWS for Database Administrators: From On-Premises to Cloud covers these services and many more in depth, with hands-on labs.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Sunday, November 29, 2026

Python Cheat Sheet for DBAs

A one-page Python 3 cheat sheet for DBAs and anyone starting with Python. Every example runs as shown in Python 3.9 or later.

Running Python

python3 --version
python3                      # interactive shell, exit() to leave
python3 myscript.py          # run a script

# Virtual environment: one per project, keeps packages separate
python3 -m venv ~/venvs/dba
source ~/venvs/dba/bin/activate
pip install oracledb

Variables and types

name = "ORCL"              # str
port = 1521                # int
used_pct = 82.5            # float
is_open = True             # bool
nothing = None             # no value

type(port)                 # <class 'int'>
int("42"), float("3.5"), str(1521)

Strings

s = "  Oracle Database  "
s.strip()                  # 'Oracle Database'
s.lower(), s.upper()
s.replace("Oracle", "PostgreSQL")
"ORA-00600".startswith("ORA-")      # True
"a,b,c".split(",")         # ['a', 'b', 'c']
"-".join(["2026", "11", "25"])      # '2026-11-25'

db, pct = "ORCL", 82.456
print(f"{db} tablespace is {pct:.1f}% full")   # ORCL tablespace is 82.5% full

Lists

dbs = ["ORCL", "TEST", "DEV"]
dbs.append("PROD")
dbs[0]                     # 'ORCL'
dbs[-1]                    # 'PROD'
dbs[1:3]                   # ['TEST', 'DEV']
len(dbs)                   # 4
"DEV" in dbs               # True
sorted(dbs)
dbs.remove("TEST")

Dictionaries

db = {"name": "ORCL", "port": 1521, "version": "19c"}
db["name"]                 # 'ORCL'
db.get("owner", "unknown") # default if the key is missing
db["port"] = 1522
for key, value in db.items():
    print(key, value)

Tuples and sets

point = (10, 20)           # tuple: cannot be changed
x, y = point               # unpacking

hosts = {"db1", "db2", "db1"}   # set: {'db1', 'db2'}, no duplicates
hosts.add("db3")
{"db1", "db2"} & {"db2", "db3"}  # {'db2'} intersection

Conditions and loops

if used_pct >= 90:
    print("CRITICAL")
elif used_pct >= 80:
    print("WARNING")
else:
    print("OK")

for db in dbs:
    print(db)

for i, db in enumerate(dbs, start=1):
    print(i, db)

count = 0
while count < 3:
    count += 1

for n in range(5):         # 0, 1, 2, 3, 4
    if n == 3:
        break

Comprehensions

squares = [n * n for n in range(5)]                 # [0, 1, 4, 9, 16]
usage = {"USERS": 91.2, "SYSAUX": 64.0, "DATA": 88.5}
full = [t for t, pct in usage.items() if pct > 85]  # ['USERS', 'DATA']
upper = {db: db.lower() for db in dbs}

Functions

def pct_used(used_mb, total_mb, decimals=1):
    """Return the percentage used."""
    return round(used_mb / total_mb * 100, decimals)

pct_used(850, 1000)                 # 85.0
pct_used(total_mb=1000, used_mb=850, decimals=0)

def log(*messages, level="INFO"):
    print(level, *messages)

Errors

try:
    pct = pct_used(850, 0)
except ZeroDivisionError:
    pct = None
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    print("done")

raise ValueError("port must be a number")

Files

with open("alert_ORCL.log") as f:          # file closes automatically
    for line in f:
        if "ORA-" in line:
            print(line.rstrip())

with open("report.txt", "w") as f:
    f.write("All databases OK\n")

import csv, json
with open("dbs.csv") as f:
    for row in csv.DictReader(f):
        print(row["name"])

data = json.loads('{"name": "ORCL"}')
text = json.dumps(data, indent=2)

Useful modules

import os, sys, datetime, subprocess, re

os.environ.get("ORACLE_SID")
os.path.exists("/u01/app/oracle")
datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
re.findall(r"ORA-\d{5}", line)
result = subprocess.run(["df", "-h"], capture_output=True, text=True)
print(result.stdout)
sys.exit(1)                # exit with an error code

Classes (the basics)

class Database:
    def __init__(self, name, port=1521):
        self.name = name
        self.port = port

    def dsn(self, host):
        return f"{host}:{self.port}/{self.name}"

orcl = Database("ORCL")
orcl.dsn("dbhost1")        # 'dbhost1:1521/ORCL'

Connecting to Oracle with python-oracledb

import getpass
import oracledb

conn = oracledb.connect(user="system",
                        password=getpass.getpass("Password: "),
                        dsn="dbhost1:1521/ORCLPDB1")
with conn.cursor() as cur:
    cur.execute("""
        SELECT tablespace_name, ROUND(used_percent, 1)
        FROM   dba_tablespace_usage_metrics
        WHERE  used_percent > :limit
        ORDER  BY 2 DESC""", limit=80)
    for name, pct in cur:
        print(f"{name:20} {pct:5.1f}%")
conn.close()

Never put passwords in a script. Ask for them with getpass, read them from an environment variable, or use a wallet or a secrets manager. Always use bind variables (:limit), never string formatting, to pass values into SQL.

Script template

#!/usr/bin/env python3
"""Check something and exit with 0 (OK) or 1 (problem)."""
import sys

def main():
    problems = []
    # ... checks go here ...
    for p in problems:
        print(p)
    return 1 if problems else 0

if __name__ == "__main__":
    sys.exit(main())

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Friday, November 27, 2026

Splunk for DBAs: Basics and the SPL Commands I Use Most

Splunk collects machine data (log files, metrics, events) into indexes and lets you search it with the Search Processing Language (SPL). For a DBA, that means one place to search alert logs, listener logs, OS logs and application errors across every server. This post covers the basics and the SPL commands I use most.

Key terms

TermMeaning
IndexWhere data is stored, for example oracle or os. Always name the index in your search; it is much faster.
SourcetypeThe format of the data, such as oracle:alert or linux_secure. It decides how fields are extracted.
SourceThe file or input the event came from, such as /u01/app/oracle/diag/.../alert_ORCL.log.
HostThe server that sent the event.
EventOne record, usually one log entry, with a timestamp.
FieldA named value in an event, such as host or an extracted ora_error.
ForwarderThe Universal Forwarder agent on each server that sends files to Splunk.

Your first searches

Open Search & Reporting, pick a time range in the time picker (for example "Last 24 hours"), and type:

index=oracle sourcetype=oracle:alert "ORA-"

Search terms are combined with AND by default. Use OR and NOT in capitals, and quotes for exact phrases:

index=oracle ("ORA-00600" OR "ORA-07445") NOT host=testdb*
index=os sourcetype=linux_secure "Failed password"

Click a field in the left sidebar to see its top values, and click a value to add it to the search.

The pipe

Like in a Unix shell, | passes the results of one command to the next. The first part finds events; the commands after the pipes shape them:

index=oracle "ORA-" | stats count by host | sort - count

SPL commands I use most

CommandWhat it doesExample
statsCounts, sums, averages by field| stats count by host
timechartStatistics over time, for a chart| timechart span=1h count by host
top / rareMost or least common values| top limit=10 ora_error
tableShow only chosen fields| table _time host ora_error
sortSort results (- means descending)| sort - count
dedupKeep one event per value| dedup host
rexExtract a field with a regular expression| rex "(?<ora_error>ORA-\d{5})"
evalCalculate a new field| eval gb=round(bytes/1024/1024/1024,2)
whereFilter on a calculated condition| where count > 10
renameRename fields for display| rename count AS "Errors"
head / tailFirst or last N results| head 20
lookupAdd fields from a CSV lookup table| lookup db_owners host OUTPUT team
transactionGroup related events into one| transaction host maxspan=5m

Useful searches for DBAs

ORA- errors in alert logs, by database server and error code:

index=oracle sourcetype=oracle:alert "ORA-"
| rex "(?<ora_error>ORA-\d{5})"
| stats count by host ora_error
| sort - count

Hourly trend of ORA- errors, one line per host:

index=oracle sourcetype=oracle:alert "ORA-"
| timechart span=1h count by host

Databases that restarted in the last 7 days (set the time picker to "Last 7 days"):

index=oracle sourcetype=oracle:alert "Starting ORACLE instance"
| table _time host
| sort - _time

Failed SSH logins on database servers:

index=os sourcetype=linux_secure "Failed password"
| rex "from (?<src_ip>\d+\.\d+\.\d+\.\d+)"
| stats count by host src_ip
| where count > 5

Listener connections per service per hour:

index=oracle sourcetype=oracle:listener "establish"
| rex "SERVICE_NAME=(?<service>[^\)]+)"
| timechart span=1h count by service

SPL does not use -- for comments. To add a comment inside a search, wrap it in three backticks: ```count errors per host```.

Sourcetype names depend on how your Splunk admin set up the inputs. Run index=oracle | stats count by sourcetype to see what you have.

Saving searches, alerts and dashboards

  • Save As → Report keeps a search you run often.
  • Save As → Alert runs the search on a schedule and emails you (or opens a ticket) when there are results. For example: "ORA-00600 in the last 15 minutes, any host".
  • Save As → Dashboard Panel adds the chart to a dashboard, such as a daily database health page.

Tips for fast searches

  • Always start with index= and, if you can, sourcetype=.
  • Use the smallest time range that answers your question.
  • Filter as early as possible, before the first pipe, and use stats rather than transaction when you can.
  • Use | fields host ora_error early to carry only the fields you need.

To practice, Splunk offers a free trial of Splunk Enterprise and free introductory training on its website.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Thursday, November 26, 2026

SQL Server Trusted Connections: Who Am I Connected As?

A question I get from Oracle DBAs who also look after SQL Server: an ODBC connection can use a user ID and password, or a trusted connection. With a trusted connection, who am I connected as? And can a query show that name?

What a trusted connection is

A trusted connection is Windows Authentication. SQL Server does not get a user name and password from the ODBC settings. Instead, Windows passes along the identity of the process that opens the connection, using Kerberos or NTLM. Any user ID typed into the ODBC data source is ignored.

Usually that is the person logged in to the machine, but not always:

  • A program running as a Windows service or scheduled task connects as that service account, for example DOMAIN\svc_reports.
  • A program started with Run as different user connects as that user.
  • A web application in IIS connects as its application pool account, unless it is set up to pass on the browser user's identity.

The query: who am I?

SELECT SUSER_SNAME()     AS login_name,      -- DOMAIN\username for a trusted connection
       ORIGINAL_LOGIN()  AS original_login,  -- the real login, even after EXECUTE AS
       SYSTEM_USER       AS system_user,
       USER_NAME()       AS database_user;   -- the database user it maps to (often dbo)

Use ORIGINAL_LOGIN() in code that may run under EXECUTE AS; SUSER_SNAME() then shows the impersonated login instead.

The detailed version: how did I authenticate?

SELECT s.login_name,
       s.nt_domain,
       s.nt_user_name,          -- filled in only for Windows authentication
       s.original_login_name,
       s.host_name,
       c.auth_scheme            -- KERBEROS or NTLM = trusted; SQL = user id/password
FROM   sys.dm_exec_sessions    s
JOIN   sys.dm_exec_connections c ON c.session_id = s.session_id
WHERE  s.session_id = @@SPID;
Connection typelogin_nament_user_nameauth_scheme
Trusted (Windows)DOMAIN\yournameyournameKERBEROS or NTLM
User ID / passwordthe SQL loginemptySQL

Seeing a user's own session needs no extra permission. To see other people's sessions in sys.dm_exec_sessions, you need VIEW SERVER STATE (in SQL Server 2022 and later, VIEW SERVER PERFORMANCE STATE is enough).

For Oracle DBAs

The closest Oracle equivalents are OS-authenticated users (IDENTIFIED EXTERNALLY, the old OPS$ accounts) and Kerberos authentication. To see who you are in Oracle:

SELECT SYS_CONTEXT('USERENV','SESSION_USER')        AS db_user,
       SYS_CONTEXT('USERENV','OS_USER')             AS os_user,
       SYS_CONTEXT('USERENV','AUTHENTICATION_METHOD') AS auth_method,
       SYS_CONTEXT('USERENV','HOST')                AS client_host
FROM   dual;

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

ORA-22992: Loading BLOB Text over a Database Link (19c/21c)

A reader's question: a table on a remote database stores plain text in a BLOB column (a CLOB would have been the better choice). Loading it into a staging area over a database link took 218 minutes. Converting the BLOB to VARCHAR2 pieces in a view on the source cut it to 2 minutes. But putting the pieces back together into one CLOB on the target failed with:

ORA-22992: cannot use LOB locators selected from remote tables

Here is why it happens, and the approach I recommend for Oracle 19c and 21c.

The setup

The view on the source database returns two VARCHAR2 pieces for normal rows, and a CLOB only for the large ones:

CREATE OR REPLACE VIEW owner.table_v AS
SELECT id,
       date_col,
       UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(blob_col, 2000, 1))    AS clob_pt1,
       UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(blob_col, 2000, 2001)) AS clob_pt2,
       CASE WHEN DBMS_LOB.GETLENGTH(blob_col) > 4000
            THEN TO_CLOB(blob_col, NLS_CHARSET_ID('AL32UTF8'))
       END AS clob_col
FROM   owner.source_table;

Why 2000? DBMS_LOB.SUBSTR on a BLOB returns a RAW, and a RAW in SQL is limited to 2000 bytes (with the default MAX_STRING_SIZE=STANDARD), so two pieces cover the first 4000 bytes.

On the target, both of these work on their own:

-- Short rows: concatenate the two VARCHAR2 pieces
INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_pt1 || clob_pt2
FROM   owner.table_v@db_lnk;

-- Long rows: copy the remote CLOB straight in
INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_col
FROM   owner.table_v@db_lnk;

But this fails with ORA-22992:

INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col,
       CASE WHEN clob_col IS NOT NULL
            THEN clob_col
            ELSE clob_pt1 || clob_pt2
       END
FROM   owner.table_v@db_lnk;

Why it fails

The CASE statement is not the real problem; the remote LOB is. Oracle can copy a remote LOB column as it is into a local LOB column. That is a supported distributed operation. But once the remote LOB is part of an expression evaluated on the local database, such as a CASE, a concatenation or a function call, Oracle needs the remote LOB's locator locally, and that is what ORA-22992 refuses.

  • Plain copy of a remote LOB column: works.
  • Remote LOB inside a local expression: can fail with ORA-22992.
  • Expression evaluated fully on the remote side (for example inside the view): usually works.

Oracle 12.2 and later relaxed many remote LOB restrictions, but mixing a remote LOB with locally built values in one expression can still fail, depending on the plan. Test on your exact versions.

Also check the logic: the overflow CLOB should win when it is present, so the CASE must return clob_col when it is NOT NULL. Swapping the branches is an easy mistake.

Recommended fix: two inserts

Both halves already work separately, so keep them separate:

-- 1. Rows that fit in the two pieces (no remote LOB involved)
INSERT /*+ APPEND */ INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, TO_CLOB(clob_pt1 || clob_pt2)
FROM   owner.table_v@db_lnk
WHERE  clob_col IS NULL;
COMMIT;

-- 2. Large rows: plain copy of the remote CLOB
INSERT /*+ APPEND */ INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_col
FROM   owner.table_v@db_lnk
WHERE  clob_col IS NOT NULL;
COMMIT;

The COMMIT after each insert is needed: after a direct-path (APPEND) insert, the same session cannot touch that table again until it commits (ORA-12838).

Most rows go through the fast first insert; only the few large rows pay the LOB cost in the second.

A UNION ALL of the two queries in one INSERT looks neater, but Oracle may still combine both branches into one expression and raise ORA-22992 again. The two separate statements are the safer choice.

Watch the BLOB-to-text conversion

  • Use the right conversion. From 12.2, TO_CLOB(blob_col, csid) converts a BLOB to a CLOB using the character set you name, such as NLS_CHARSET_ID('AL32UTF8'). On older versions, use DBMS_LOB.CONVERTTOCLOB in PL/SQL. Find out which character set the application really used to write the BLOBs.
  • Multibyte characters can be split. UTL_RAW.CAST_TO_VARCHAR2 works on bytes. With UTF-8 text, a character can be cut in half at byte 2000, which gives a corrupted character in both pieces. If the text is not plain ASCII, check rows near the boundary, or use the CLOB path for all of them.
  • Measure length in bytes. Use DBMS_LOB.GETLENGTH(blob_col), which returns bytes for a BLOB, to decide which rows need the CLOB path.

Better long-term options

  • Convert on the source. If you control the source database, convert the BLOB to a CLOB there once, in a staging table or a column, with the correct character set. The target then does a plain CLOB copy, which works over a database link.
  • Extended data types. With MAX_STRING_SIZE=EXTENDED (12c and later), VARCHAR2 and RAW in SQL can be up to 32767 bytes, so one piece can carry much more text without a LOB. Changing this parameter cannot be undone and requires running utl32k.sql in upgrade mode, so plan it carefully and test it first.
  • Fix the data type. If the column only ever holds text, ask the application owner to change it to a CLOB. That removes the conversion problems at the root.

Why the view made it 100 times faster

Fetching LOBs over a database link is slow because each LOB value can need extra network round trips. VARCHAR2 values travel in normal row batches. Turning most LOB values into VARCHAR2 on the source side, so only the few large rows are fetched as LOBs, is what took the load from 218 minutes to 2. A SQL trace of both versions would show the difference in round trips.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Wednesday, November 25, 2026

Oracle GoldenGate Bidirectional Replication: On-Premises to AWS EC2

This post sets up bidirectional (active-active) replication with Oracle GoldenGate between an on-premises Oracle database and an Oracle database running on Amazon EC2. Both databases accept changes, and each change is copied to the other side. It is a common pattern during a cloud migration: you keep both sides live, move users over gradually, and keep a way back.

The commands use GoldenGate 21c or later (Microservices Architecture) with the Admin Client. Classic Architecture was deprecated in 19c and is not available in 21c and later, so new setups should use Microservices.

The setup

SideDatabaseExtractReplicat
On premisesONPREM (19c, PDB SALESPDB)EXTAREPA (applies changes from AWS)
AWS EC2AWSDB (19c, PDB SALESPDB)EXTBREPB (applies changes from on premises)

Each side runs its own GoldenGate deployment. A distribution path sends each side's trail files to the other side over a secure WebSocket connection.

Before you start: active-active rules

  • Every replicated table needs a primary key or unique key. Without one, GoldenGate cannot find the right row to update on the other side.
  • Avoid key collisions. If both sides insert rows using sequences, give each side its own range. The simplest way is odd and even numbers: on premises START WITH 1 INCREMENT BY 2, on AWS START WITH 2 INCREMENT BY 2. Identity columns need the same treatment.
  • Stop the loop. A change applied by Replicat must not be captured again by the local Extract and sent back. Integrated Replicat tags its transactions, and Extract excludes them with TRANLOGOPTIONS EXCLUDETAG.
  • Plan for conflicts. If the same row is changed on both sides at the same moment, one change must win. Oracle's automatic conflict detection and resolution (latest timestamp wins) handles most cases.
  • Triggers and cascading deletes should fire only for local user changes, not for rows applied by Replicat. Integrated Replicat suppresses triggers by default; check any custom code that runs on DML.

1. Network between on premises and AWS

  • Connect the data center and the VPC with Site-to-Site VPN or Direct Connect. Do not open GoldenGate ports to the internet.
  • Allow the GoldenGate ports between the two deployments only, in the EC2 security group and the on-premises firewall. The ports are the ones you chose when you created the deployments (Service Manager, Administration, Distribution and Receiver services).
  • Use TLS certificates for the deployments so the distribution paths use wss://.

2. Prepare both databases

Run on both ONPREM and AWSDB, in CDB$ROOT unless noted:

-- ARCHIVELOG mode and force logging
SELECT log_mode, force_logging FROM v$database;
ALTER DATABASE FORCE LOGGING;

-- Minimal supplemental logging and the GoldenGate parameter
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
ALTER SYSTEM SET enable_goldengate_replication = TRUE SCOPE=BOTH;
ALTER SYSTEM SET streams_pool_size = 2G SCOPE=BOTH;   -- for integrated Extract and Replicat

-- GoldenGate administrator (common user)
CREATE USER c##ggadmin IDENTIFIED BY "ChangeMe#2026" CONTAINER=ALL;
GRANT DBA TO c##ggadmin CONTAINER=ALL;
EXEC DBMS_GOLDENGATE_AUTH.GRANT_ADMIN_PRIVILEGE('C##GGADMIN', container => 'ALL');

Use a strong password of your own and store it only in the GoldenGate credential store.

3. Credentials and schema logging (each side)

In the Admin Client, connected to that side's deployment:

ALTER CREDENTIALSTORE ADD USER c##ggadmin@onprem-scan:1521/ONPREM ALIAS onprem_root DOMAIN OracleGoldenGate
ALTER CREDENTIALSTORE ADD USER c##ggadmin@onprem-scan:1521/SALESPDB ALIAS onprem_pdb DOMAIN OracleGoldenGate

DBLOGIN USERIDALIAS onprem_pdb DOMAIN OracleGoldenGate
ADD SCHEMATRANDATA sales ALLCOLS

Do the same on AWS with aliases aws_root and aws_pdb.

4. Automatic conflict detection and resolution

Turn on Oracle's automatic CDR for each replicated table, on both databases. It adds a hidden timestamp column and resolves update conflicts with "latest timestamp wins":

BEGIN
  FOR t IN (SELECT table_name FROM dba_tables WHERE owner = 'SALES') LOOP
    DBMS_GOLDENGATE_ADM.ADD_AUTO_CDR(schema_name => 'SALES', table_name => t.table_name);
  END LOOP;
END;
/
SELECT table_owner, table_name FROM dba_gg_auto_cdr_tables;

5. Extract on each side

Parameter file for EXTA (on premises). EXTB on AWS is the same with its own names:

EXTRACT exta
USERIDALIAS onprem_root DOMAIN OracleGoldenGate
EXTTRAIL ea
TRANLOGOPTIONS EXCLUDETAG 00        -- skip changes applied by the local Replicat
DDL INCLUDE MAPPED
TABLE salespdb.sales.*;
DBLOGIN USERIDALIAS onprem_root DOMAIN OracleGoldenGate
ADD EXTRACT exta, INTEGRATED TRANLOG, BEGIN NOW
REGISTER EXTRACT exta DATABASE CONTAINER (salespdb)
ADD EXTTRAIL ea, EXTRACT exta
START EXTRACT exta

6. Initial load

If the AWS database starts empty, load it from on premises before starting the Replicats. The safest method is an export at a known SCN (Data Pump FLASHBACK_SCN), then starting the AWS Replicat after that SCN. I describe it step by step in my tutorial on GoldenGate initial load at SCN. Do not allow users to change data on AWS until the initial load is complete and REPB has caught up.

7. Distribution paths

From the on-premises deployment, send trail ea to AWS; from the AWS deployment, send trail eb back:

-- On premises
ADD DISTPATH dp_to_aws SOURCE trail://localhost:9002/services/v2/sources?trail=ea
    TARGET wss://ec2-gg.example.internal:9103/services/v2/targets?trail=ra

-- On AWS
ADD DISTPATH dp_to_onprem SOURCE trail://localhost:9002/services/v2/sources?trail=eb
    TARGET wss://onprem-gg.example.internal:9103/services/v2/targets?trail=rb

Replace the host names and ports with your own Distribution and Receiver service ports.

8. Replicat on each side

REPLICAT repb
USERIDALIAS aws_pdb DOMAIN OracleGoldenGate
DBOPTIONS INTEGRATEDPARAMS (parallelism 4)
MAP salespdb.sales.*, TARGET sales.*;
ADD REPLICAT repb, INTEGRATED, EXTTRAIL ra
START REPLICAT repb, AFTERCSN 4517823     -- the SCN of the initial load

Integrated Replicat tags its transactions with tag 00 by default, which is why each Extract uses EXCLUDETAG 00. Start REPA on premises the same way, reading trail rb.

9. Test before you trust it

  1. Insert a row on premises; it should appear on AWS within seconds. Repeat in the other direction.
  2. Update the same row on both sides at almost the same time; check that both end up with the newer value and that DBA_APPLY_ERROR is empty.
  3. Check that the row did not bounce back and forth: the trail statistics should show it once in each direction.
  4. Watch lag: INFO ALL and LAG REPLICAT repb in the Admin Client, or the Performance Metrics page in the web UI.
  5. Stop the network link for a few minutes and restart it; both sides should catch up without errors.

Day-to-day checks

INFO ALL
STATS REPLICAT repb, TOTAL, LATEST
VIEW REPORT repb

-- In the database
SELECT apply_name, status FROM dba_apply;
SELECT * FROM dba_apply_error;

Oracle GoldenGate is licensed separately from the database. Check your license before you build this in production, and test the whole design, including conflicts and a cutover, on test databases first.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.