Oracle DBA Queries and Commands

Search by task, Oracle view, or command to check sessions, storage, backups, and standby databases. SQL examples target Oracle Database 19c. Run shell commands in the indicated environment.

๐ŸŽฏ For learners and working DBAs ๐Ÿ“‹ 99 entries ๐Ÿ”’ Copy-enabled

The colour dot represents the safety level of each query

Safe โ€” Read-Only Query
Use Carefully in Production
Review Before Execution
๐Ÿ”

99 entries shown

๐Ÿ”Ž

No queries found

Try fewer words or choose All to search every category.

Instance & Database Status10

Instance Status Read-only

Shows instance name, status, database status, logins, and host name
๐Ÿ’ก Run this first when connecting to a database โ€” confirms the instance is up and accepting logins.
SELECT instance_name, status, database_status,
       logins, host_name
FROM   v$instance;

Database Info & Role Read-only

Database name, creation date, log mode, open mode, and database role
๐Ÿ’ก Verify whether this is a Primary or Standby โ€” essential at the start of any DR activity.
SELECT name, created, log_mode,
       open_mode, database_role
FROM   v$database;

DB Instance & Startup Time Read-only

Host name, instance name, open mode, and database startup timestamp
๐Ÿ’ก Shows when the database was last started โ€” useful to detect unexpected restarts in production.
SELECT HOST_NAME, name, INSTANCE_NAME, open_mode,
       TO_CHAR(startup_time,'DD-MON-YYYY HH24:MI:SS') "DB Startup Time"
FROM   v$database, sys.v_$instance;

Current SCN Read-only

Retrieves the current System Change Number of the database
๐Ÿ’ก The SCN is the database's internal clock โ€” used in PITR and standby synchronisation checks.
SELECT current_scn FROM v$database;

Current Redo Log Info Read-only

Active redo log thread, sequence, first and next change numbers
๐Ÿ’ก Shows which redo log group is currently active โ€” important when monitoring log switches or archiving issues.
SELECT thread#, sequence#, first_change#, next_change#
FROM   v$log;

Archive Log Info Read-only

Lists recent archive logs with thread, sequence, applied status, and timestamps
๐Ÿ’ก Helps verify archive logs are being generated and applied โ€” key check for Data Guard environments.
SELECT thread#, sequence#, applied,
       first_time, next_time
FROM   v$archived_log
ORDER  BY sequence# DESC
FETCH  FIRST 20 ROWS ONLY;

Total Database Size Read-only

Approximate size of database files, counting one online redo member per group.
๐Ÿ’ก Treat this as a component estimate. Additional redo members, archived logs, backups, and other recovery-area files consume space separately.
SELECT (SELECT SUM(bytes)/1024/1024/1024 FROM dba_data_files)
     + (SELECT NVL(SUM(bytes),0)/1024/1024/1024 FROM dba_temp_files)
     + (SELECT SUM(bytes)/1024/1024/1024 FROM v$log)
     + (SELECT SUM(block_size*file_size_blks)/1024/1024/1024 FROM v$controlfile)
       AS "Total Size GB"
FROM   dual;

All Database Parameters Read-only

Lists all initialization parameters and their current values
๐Ÿ’ก Use this to review or audit the current database configuration โ€” helpful before and after any parameter change.
SELECT name || '=' || value
FROM   v$parameter
ORDER  BY name;

Query Specific Parameter Read-only

Query the current value of a specific initialization parameter
๐Ÿ’ก Replace the parameter name as needed โ€” useful for quickly checking sga_target, pga_aggregate_target, undo_retention, etc.
SELECT name, value, description
FROM   v$parameter
WHERE  name = 'undo_retention'; -- change parameter name

Control File Locations Read-only

Lists all control file paths and their status
๐Ÿ’ก Always verify control file locations after a restore or migration โ€” missing or inaccessible control files will prevent database startup.
SELECT name, status, is_recovery_dest_file
FROM   v$controlfile;

Multitenant โ€” CDB & PDB6

List All PDBs Read-only

Shows all pluggable databases with con_id, name, open mode, and restricted status
๐Ÿ’ก Run from CDB$ROOT โ€” shows the full list of PDBs and their current state. Any PDB in MOUNTED state needs to be opened.
-- Run from CDB$ROOT as SYSDBA
SELECT con_id, name, open_mode, restricted
FROM   v$pdbs
ORDER  BY con_id;

Switch to a PDB Container Use carefully

Changes the current session context to the specified pluggable database
๐Ÿ’ก Run this after connecting to CDB$ROOT โ€” required before running DBA tasks inside a specific PDB. Replace PDBNAME with your actual PDB name.
-- Choose one operation below; uncomment only the required statement.
-- Switch session into a specific PDB
-- ALTER SESSION SET CONTAINER = PDBNAME;

-- Verify current container
-- SHOW CON_NAME

-- Switch back to root
-- ALTER SESSION SET CONTAINER = CDB$ROOT;

Open / Close a PDB Review first

Commands to open or close a pluggable database โ€” run from CDB$ROOT
๐Ÿ’ก Always verify which PDB you are opening/closing before executing. The SAVE STATE option makes the open persist across CDB restarts.
-- Choose one operation below; uncomment only the required statement.
-- Open a specific PDB (run from CDB$ROOT)
-- ALTER PLUGGABLE DATABASE PDBNAME OPEN;

-- Open all PDBs
-- ALTER PLUGGABLE DATABASE ALL OPEN;

-- Close a specific PDB
-- ALTER PLUGGABLE DATABASE PDBNAME CLOSE IMMEDIATE;

-- Save state (auto-open after CDB restart)
-- ALTER PLUGGABLE DATABASE PDBNAME SAVE STATE;

Show Current Container Read-only

Displays the name of the container (CDB$ROOT or PDB name) the session is currently in
๐Ÿ’ก Always run this first in a multitenant environment to confirm you are in the right container before executing DDL or DML.
SHOW CON_NAME

-- Or using SQL
SELECT SYS_CONTEXT('USERENV','CON_NAME') AS current_container FROM dual;

Create PDB Local User Review first

Creates a local user inside a specific PDB (not a common CDB user)
๐Ÿ’ก Local users exist only in the PDB โ€” switch into the PDB container first. Common users start with C## prefix and exist across all PDBs.
-- SQL*Plus: connect to the intended PDB as an authorized administrator.
SHOW CON_NAME
SET VERIFY OFF
ACCEPT new_pwd CHAR PROMPT 'New password: ' HIDE
CREATE USER pdb_user IDENTIFIED BY "&new_pwd";
UNDEFINE new_pwd
GRANT CREATE SESSION TO pdb_user;

PDB Datafile Locations Read-only

Shows datafile paths for each PDB in the CDB โ€” useful for storage planning and migration
๐Ÿ’ก Run from CDB$ROOT โ€” shows which datafiles belong to each PDB by con_id. Essential reference before cloning or unplugging a PDB.
-- Run from CDB$ROOT
SELECT p.name AS pdb_name, d.name AS datafile_path,
       ROUND(d.bytes/1024/1024/1024,2) AS size_gb
FROM   v$datafile d
JOIN   v$pdbs p ON d.con_id = p.con_id
ORDER  BY p.name, d.name;

Tablespace & Storage8

Tablespace Usage % Read-only

Used MB and remaining headroom against maximum capacity, using the block size of each tablespace.
๐Ÿ’ก Run this daily to catch any tablespace approaching full capacity before it causes errors in production. DBA_TABLESPACE_USAGE_METRICS reference
SET LINESIZE 180 PAGESIZE 100
COLUMN tablespace_name FORMAT A30
SELECT m.tablespace_name, ROUND(m.used_percent, 2) AS used_pct,
       ROUND(m.tablespace_size * t.block_size / POWER(1024,3), 2) AS max_capacity_gb,
       ROUND(m.used_space * t.block_size / POWER(1024,2), 2) AS used_mb,
       ROUND((m.tablespace_size - m.used_space) * t.block_size / POWER(1024,3), 2) AS headroom_gb
FROM   dba_tablespace_usage_metrics m
JOIN   dba_tablespaces t ON t.tablespace_name = m.tablespace_name
ORDER BY m.used_percent DESC;

Tablespace Total vs Free Read-only

Allocated datafile space and currently free extents together for permanent and undo tablespaces.
๐Ÿ’ก A quick side-by-side comparison of how much space each tablespace has versus how much is actually free.
SELECT a.tablespace_name, ROUND(a.allocated/POWER(1024,3),2) AS allocated_gb,
       ROUND(NVL(f.free_bytes,0)/POWER(1024,3),2) AS free_gb
FROM   (SELECT tablespace_name, SUM(bytes) allocated FROM dba_data_files
        GROUP BY tablespace_name) a
LEFT JOIN (SELECT tablespace_name, SUM(bytes) free_bytes FROM dba_free_space
           GROUP BY tablespace_name) f ON f.tablespace_name = a.tablespace_name
ORDER BY a.tablespace_name;

Tablespace Datafiles Read-only

Lists all datafiles with tablespace name, file path, size in GB, and autoextend setting
๐Ÿ’ก Check autoextend settings to avoid surprise disk space exhaustion when a tablespace grows.
SELECT tablespace_name, file_name,
       bytes/1024/1024/1024 AS size_gb,
       autoextensible
FROM   dba_data_files
ORDER  BY tablespace_name;

Validate Datafiles Use carefully

Check file number, name, and current status of all datafiles
๐Ÿ’ก A file in OFFLINE or RECOVER status needs immediate attention โ€” run this daily to stay aware of any datafile issues.
SELECT file#, name, status
FROM   v$datafile;

Temp Tablespace Files Read-only

Lists temporary tablespace files with name and size in MB
๐Ÿ’ก Temp tablespace holds sort operations and hash joins โ€” knowing its size helps diagnose ORA-1652 errors.
SELECT tablespace_name, file_name,
       bytes/1024/1024 AS size_mb
FROM   dba_temp_files;

Temp Tablespace Current Usage Read-only

Real-time used and free GB in temp tablespace based on active sort segments
๐Ÿ’ก Shows how much temp space is actually in use right now โ€” useful during heavy query loads.
SELECT A.tablespace_name AS tablespace, D.gb_total,
       ROUND(SUM(A.used_blocks * D.block_size)/1024/1024/1024,2) AS gb_used,
       ROUND(D.gb_total - SUM(A.used_blocks * D.block_size)/1024/1024/1024,2) AS gb_free
FROM   v$sort_segment A,
       (SELECT B.name, C.block_size,
               ROUND(SUM(C.bytes)/1024/1024/1024,2) AS gb_total
        FROM   v$tablespace B, v$tempfile C
        WHERE  B.ts# = C.ts#
        GROUP  BY B.name, C.block_size) D
WHERE  A.tablespace_name = D.name
GROUP  BY A.tablespace_name, D.gb_total;

Tablespace Usage (Specific) Read-only

Detailed usage metrics for a specific tablespace โ€” change the name as needed
๐Ÿ’ก Use this to deep-dive into a single tablespace โ€” handy when a specific tablespace is reported as full.
SELECT *
FROM   dba_tablespace_usage_metrics
WHERE  tablespace_name = 'USERS'; -- change name

Datafile Block Corruption Review first

Returns details of any datafile block corruptions detected
๐Ÿ’ก An empty result here is good news. Any rows mean data blocks are corrupt and must be investigated immediately.
SELECT * FROM v$database_block_corruption;

Sessions & Locks7

Active Sessions Read-only

Lists all active sessions with SID, serial#, username, program, and machine
๐Ÿ’ก Your starting point when users report slowness โ€” shows who is connected and actively working.
SELECT sid, serial#, username, status,
       program, machine
FROM   v$session
WHERE  status = 'ACTIVE';

Session Count by Status Read-only

Total session count grouped by status (ACTIVE / INACTIVE)
๐Ÿ’ก A sudden spike in ACTIVE sessions often signals a problem โ€” this gives you the count at a glance.
SELECT status, COUNT(*)
FROM   v$session
GROUP  BY status;

Blocking Sessions Use carefully

Shows which sessions are blocking others โ€” includes blocker and waiter details
๐Ÿ’ก Check the blocking instance, SID, serial number, and transaction before deciding how to intervene.
SELECT w.inst_id AS waiting_inst, w.sid AS waiting_sid, w.username AS waiting_user,
       b.inst_id AS blocking_inst, b.sid AS blocking_sid, b.serial# AS blocking_serial,
       b.username AS blocking_user, w.event
FROM   gv$session w
JOIN   gv$session b ON b.inst_id = w.blocking_instance AND b.sid = w.blocking_session
WHERE  w.blocking_session_status = 'VALID'
ORDER BY w.inst_id, w.sid;

Kill a Session Review first

Template to kill a specific session โ€” replace SID and SERIAL# values
๐Ÿ’ก Use this after identifying a problematic session from Active Sessions or Blocking Sessions queries above.
-- Find SID and SERIAL# first, then run:
ALTER SYSTEM KILL SESSION '&SID,&SERIAL#' IMMEDIATE;

Long Running Queries Use carefully

Active sessions running SQL for more than 60 seconds with elapsed time
๐Ÿ’ก Elapsed time starts with this execution and includes time spent waiting. V$SESSION reference
SET LINESIZE 200 PAGESIZE 100
COLUMN username FORMAT A24
COLUMN sql_id FORMAT A13
SELECT s.sid, s.serial#, s.username, s.sql_id, s.sql_exec_start,
       ROUND((SYSDATE - s.sql_exec_start) * 86400) AS elapsed_secs
FROM   v$session s
WHERE  s.type = 'USER' AND s.status = 'ACTIVE'
AND    s.sql_exec_start < SYSDATE - 60/86400
ORDER BY s.sql_exec_start;

Long Operation Progress Use carefully

Progress for instrumented long operations on active sessions, by RAC instance, SID, and serial number.
๐Ÿ’ก Essential during Data Pump imports/exports and RMAN jobs โ€” shows % complete, elapsed time, and estimated finish time. V$SESSION_LONGOPS reference
SET LINESIZE 200 PAGESIZE 100
COLUMN opname FORMAT A36
COLUMN units FORMAT A14
SELECT a.inst_id, a.sid, a.serial#, a.opname, a.sofar, a.totalwork, a.units,
       ROUND(100 * a.sofar / NULLIF(a.totalwork,0),1) AS pct_complete,
       a.elapsed_seconds, a.time_remaining AS remaining_secs
FROM   gv$session_longops a
JOIN   gv$session s ON s.inst_id = a.inst_id AND s.sid = a.sid AND s.serial# = a.serial#
WHERE  a.totalwork > a.sofar AND s.status = 'ACTIVE'
ORDER BY a.start_time;

Current SQL per Session Read-only

Shows the SQL currently being executed by each active session
๐Ÿ’ก Useful when you need to see exactly what SQL a specific session is running โ€” critical for performance diagnostics.
SELECT s.sid, s.serial#, s.username, s.status,
       s.machine, q.sql_text
FROM   v$session s
JOIN   v$sql q ON s.sql_id = q.sql_id AND s.sql_child_number = q.child_number AND s.con_id = q.con_id
WHERE  s.status = 'ACTIVE'
AND    s.username IS NOT NULL
ORDER  BY s.sid;

Performance Monitoring6

Top SQL by CPU Read-only

Top 10 SQL statements ranked by CPU time from shared pool
๐Ÿ’ก Identify the most CPU-hungry queries currently in the shared pool โ€” key starting point for performance tuning.
SELECT sql_id, executions, cpu_time,
       elapsed_time, disk_reads,
       SUBSTR(sql_text,1,80) AS sql_text
FROM   v$sql
ORDER  BY cpu_time DESC
FETCH  FIRST 10 ROWS ONLY;

Top Wait Events Read-only

System-wide wait events ranked by total wait time
๐Ÿ’ก Wait events reveal where the database is spending its time. High "db file sequential read" often means index/IO issues.
SELECT event, total_waits, total_timeouts,
       ROUND(time_waited/100,2) AS time_waited_secs,
       ROUND(average_wait/100,4) AS avg_wait_secs
FROM   v$system_event
WHERE  wait_class <> 'Idle'
ORDER  BY time_waited DESC
FETCH  FIRST 15 ROWS ONLY;

Buffer Cache Hit Ratio Read-only

Instance-wide buffer cache hit ratio from cumulative cache access statistics.
๐Ÿ’ก Use interval deltas and I/O wait times to investigate a slowdown. A single percentage cannot establish a memory shortage.
SELECT ROUND(100 * (1 - SUM(CASE WHEN name = 'physical reads cache' THEN value ELSE 0 END)
       / NULLIF(SUM(CASE WHEN name IN ('consistent gets from cache','db block gets from cache')
                         THEN value ELSE 0 END),0)),2) AS cache_hit_pct
FROM v$sysstat
WHERE name IN ('physical reads cache','consistent gets from cache','db block gets from cache');

SGA Component Sizes Read-only

Current sizes of all SGA components in MB
๐Ÿ’ก Shows how memory is distributed across the buffer cache, shared pool, and large pool โ€” useful when tuning memory.
SELECT component,
       ROUND(current_size/1024/1024,2) AS current_mb,
       ROUND(min_size/1024/1024,2)     AS min_mb,
       ROUND(max_size/1024/1024,2)     AS max_mb
FROM   v$sga_dynamic_components
ORDER  BY current_size DESC;

Undo Segment Usage Read-only

Active, unexpired, and expired undo extents per segment
๐Ÿ’ก On RAC, check extent status from the instance using that undo tablespace.
SELECT tablespace_name, segment_name, status, COUNT(*) AS extents,
       ROUND(SUM(bytes)/1048576,2) AS size_mb
FROM   dba_undo_extents
GROUP BY tablespace_name, segment_name, status
ORDER BY tablespace_name, segment_name, status;

Top SQL by Disk Reads Read-only

Top 10 SQL statements ranked by physical disk reads
๐Ÿ’ก High disk reads indicate missing indexes, full table scans, or insufficient buffer cache. These are prime candidates for SQL tuning.
SELECT sql_id, executions, disk_reads,
       ROUND(disk_reads/NULLIF(executions,0),1) AS reads_per_exec,
       SUBSTR(sql_text,1,80) AS sql_text
FROM   v$sql
ORDER  BY disk_reads DESC
FETCH  FIRST 10 ROWS ONLY;

Backup & RMAN6

RMAN Backup Job Status Read-only

Last 10 RMAN backup jobs with status, start/end times and elapsed duration
๐Ÿ’ก Run this every morning as part of your daily DBA check โ€” immediately shows if last night's backup succeeded or failed.
SELECT session_key, input_type, status,
       TO_CHAR(start_time,'DD-MON-YYYY HH24:MI') AS start_time,
       TO_CHAR(end_time,'DD-MON-YYYY HH24:MI')   AS end_time,
       ROUND(elapsed_seconds/60,1) AS elapsed_min
FROM   v$rman_backup_job_details j
ORDER  BY j.start_time DESC
FETCH  FIRST 10 ROWS ONLY;

RMAN Backup Pieces Use carefully

Lists recent backup pieces with handle, completion time, and size in GB
๐Ÿ’ก These records have AVAILABLE status in the RMAN repository. Use RMAN validation to check readability.
SELECT handle,
       TO_CHAR(completion_time,'DD-MON-YYYY HH24:MI') AS completed,
       ROUND(bytes/1024/1024/1024,2) AS size_gb, status
FROM   v$backup_piece
WHERE  status = 'A'
ORDER  BY completion_time DESC;

Fast Recovery Area Usage Read-only

FRA size, used space, reclaimable space, and percentage used
๐Ÿ’ก If FRA usage exceeds 85%, the database may stop archiving. Monitor this daily to prevent ORA-00257 errors.
SELECT name AS fra_location,
       ROUND(space_limit/1024/1024/1024,2)   AS limit_gb,
       ROUND(space_used/1024/1024/1024,2)    AS used_gb,
       ROUND(space_reclaimable/1024/1024,2)  AS reclaimable_mb,
       ROUND((space_used/NULLIF(space_limit,0))*100,2) AS used_pct
FROM   v$recovery_file_dest;

Archive Log Generation Rate Read-only

Number of archive logs generated per day with total size in GB
๐Ÿ’ก Helps understand how quickly the database generates archive logs โ€” critical for sizing the FRA.
WITH logs AS (
  SELECT resetlogs_change#, thread#, sequence#, MIN(first_time) AS first_time,
         MAX(blocks * block_size) AS log_bytes
  FROM   v$archived_log WHERE archived = 'YES' AND blocks > 0
  GROUP BY resetlogs_change#, thread#, sequence#
)
SELECT TRUNC(first_time) AS log_date, COUNT(*) AS logs_generated,
       ROUND(SUM(log_bytes)/POWER(1024,3),2) AS size_gb
FROM logs GROUP BY TRUNC(first_time) ORDER BY log_date DESC;

Datafiles Not Backed Up Use carefully

Datafiles without a backup-set record in the last seven days in the control file.
๐Ÿ’ก Image copies and aged-out records need separate checks in RMAN. V$BACKUP_DATAFILE reference
SELECT d.file#, d.name, MAX(b.completion_time) AS last_backup
FROM   v$datafile d
LEFT JOIN v$backup_datafile b
       ON b.file# = d.file# AND b.creation_change# = d.creation_change#
GROUP BY d.file#, d.name
HAVING MAX(b.completion_time) IS NULL OR MAX(b.completion_time) < SYSDATE - 7
ORDER BY d.file#;

Archive Copies by Completion Date Read-only

Recorded archive copies by completion date, including additional destinations and repeated archives.
๐Ÿ’ก For unique sequences and their volume, use Archive Log Generation Rate.
SELECT TRUNC(completion_time) AS log_date,
       COUNT(*) AS log_count,
       ROUND(SUM(blocks*block_size)/1024/1024/1024,2) AS size_gb
FROM   v$archived_log
GROUP  BY TRUNC(completion_time)
ORDER  BY log_date DESC;

Users & Privileges7

All Database Users Read-only

Username, account status, lock date, expiry date, default tablespace, profile, and last login
๐Ÿ’ก Full user inventory โ€” shows locked/expired accounts, last login time, and which profile each user is under.
SELECT username, account_status, lock_date, expiry_date,
       default_tablespace, created, profile, last_login
FROM   dba_users
ORDER  BY username;

Locked or Expired Accounts Read-only

All user accounts that are currently locked, expired, or both
๐Ÿ’ก Quickly identify accounts needing attention โ€” locked accounts often indicate failed login attempts.
SELECT username, account_status, expiry_date, profile
FROM   dba_users
WHERE  account_status LIKE '%LOCKED%'
   OR  account_status LIKE '%EXPIRED%'
ORDER  BY username;

DBA Role Members Use carefully

Lists all users and roles that have been granted the DBA role
๐Ÿ’ก The DBA role has full database privileges โ€” this should have very few entries. Any unexpected users here is a security concern.
SELECT grantee, granted_role, admin_option, default_role
FROM   dba_role_privs
WHERE  granted_role = 'DBA'
ORDER  BY grantee;

System Privileges by User Use carefully

Lists all system privileges granted to each user or role
๐Ÿ’ก Useful for security audits โ€” shows who has been granted powerful privileges like CREATE ANY TABLE or DROP ANY INDEX.
SELECT grantee, privilege, admin_option
FROM   dba_sys_privs
ORDER  BY grantee, privilege;

Role Grants Use carefully

Lists all role assignments to users and other roles
๐Ÿ’ก Shows the full role hierarchy โ€” useful when troubleshooting access issues or auditing who has what permissions.
SELECT grantee, granted_role, admin_option, default_role
FROM   dba_role_privs
ORDER  BY grantee;

Object Privileges by User Use carefully

All object-level privileges (SELECT, INSERT, etc.) granted to users
๐Ÿ’ก Identifies which users have direct object access โ€” important for data security reviews and least-privilege enforcement.
SELECT grantee, owner, table_name, privilege, grantable
FROM   dba_tab_privs
ORDER  BY grantee, owner, table_name;

Unlock User Account Review first

Template to unlock a locked user account and optionally reset the password
๐Ÿ’ก Use this when a user is locked out โ€” always verify with the application team first.
-- Choose one operation below; uncomment only the required statement.
-- Unlock account
-- ALTER USER &username ACCOUNT UNLOCK;

-- Reset password (optional)
-- ALTER USER &username IDENTIFIED BY &new_password;

Data Guard9

Data Guard Role & Protection Mode Use carefully

Database role, protection mode, protection level, open mode, and switchover status
๐Ÿ’ก First query to run on any Data Guard database โ€” confirms whether you are on the Primary or Standby.
SELECT name, db_unique_name, database_role,
       protection_mode, protection_level,
       open_mode, switchover_status
FROM   v$database;

Apply Lag & Transport Lag Read-only

Shows apply lag and transport lag โ€” run on standby database
๐Ÿ’ก Transport lag measures redo delivery. Apply lag also includes received redo waiting for apply. Check DATUM_TIME across samples for stale measurements.
SELECT name, value, unit, time_computed, datum_time
FROM   v$dataguard_stats
WHERE  name IN ('apply lag','transport lag');

Primary Last Archived Sequence Use carefully

Highest archived sequence per redo thread in the current incarnation.
๐Ÿ’ก An active online log can contain newer redo than the latest archived sequence.
SELECT thread#, MAX(sequence#) AS "Last Seq Archived"
FROM   v$archived_log val, v$database vdb
WHERE  val.resetlogs_change# = vdb.resetlogs_change#
GROUP  BY thread#
ORDER  BY thread#;

Sequence Applied vs Received (Standby) Use carefully

Highest received and fully applied archived sequences per thread on a physical standby.
๐Ÿ’ก Equal maxima alone cannot establish synchronization. Check transport lag, apply lag, and the timestamp of the latest measurement.
SELECT a.thread#, MAX(a.sequence#) AS last_received,
       MAX(CASE WHEN a.applied = 'YES' THEN a.sequence# END) AS last_applied
FROM   v$archived_log a
WHERE  a.registrar = 'RFS'
AND    a.resetlogs_change# = (SELECT resetlogs_change# FROM v$database)
GROUP BY a.thread#
ORDER BY a.thread#;

Managed Standby Processes Use carefully

Shows all active MRP, RFS, and Archiver processes on the standby
๐Ÿ’ก WAIT_FOR_LOG can be normal on a caught-up standby. Compare receipt and apply progress over time.
SELECT process, status, thread#,
       sequence#, block#, blocks
FROM   v$managed_standby
ORDER  BY process;

Start / Stop MRP (Apply Process) Review first

Commands to start and stop the Managed Recovery Process on the standby
๐Ÿ’ก Use START to begin real-time redo apply, and CANCEL to stop it cleanly before a switchover or maintenance.
-- Choose one operation below; uncomment only the required statement.
-- Start real-time redo apply
-- ALTER DATABASE RECOVER MANAGED STANDBY DATABASE
-- DISCONNECT FROM SESSION;

-- Stop MRP (cancel apply)
-- ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

Redo Log Gap Check Use carefully

Shows the archive gap currently blocking recovery on a physical standby.
๐Ÿ’ก Recheck after resolving each gap. An empty result alone does not establish zero transport lag. V$ARCHIVE_GAP reference
SELECT thread#, low_sequence#, high_sequence#
FROM   v$archive_gap
ORDER BY thread#, low_sequence#;

Standby Redo Log Verification Use carefully

Shows all online and standby redo log files with group, type, thread, size, and member path
๐Ÿ’ก Standby redo logs (SRLs) must be present and properly sized for real-time apply. Each SRL should match the primary redo log size.
SELECT f.group#, f.type, f.member, l.thread#, ROUND(l.bytes/1048576) AS size_mb
FROM   v$logfile f
JOIN   (SELECT group#, thread#, bytes FROM v$log
        UNION ALL
        SELECT group#, thread#, bytes FROM v$standby_log) l ON l.group# = f.group#
ORDER BY f.group#, f.member;

Logical Standby Progress Read-only

Applied SCN vs newest SCN โ€” shows how far behind a logical standby is
๐Ÿ’ก SCN distance measures database changes. Compare the applied and newest timestamps to assess elapsed time.
-- Run on Logical Standby
SELECT APPLIED_SCN, NEWEST_SCN,
       (NEWEST_SCN - APPLIED_SCN) AS difference
FROM   V$LOGSTDBY_PROGRESS;

-- State of Logical Standby
SELECT STATE FROM V$LOGSTDBY_STATE;

Database Objects6

Invalid Objects Read-only

Count of invalid objects grouped by owner and object type
๐Ÿ’ก Invalid procedures, functions, or packages cause application errors. Run this after any database upgrade or patching activity.
SELECT owner, object_type, COUNT(*) AS invalid_count
FROM   dba_objects
WHERE  status = 'INVALID'
GROUP  BY owner, object_type
ORDER  BY owner, object_type;

Object Counts by Type Read-only

Total count of database objects grouped by type (tables, indexes, views, etc.)
๐Ÿ’ก Gives a bird's-eye view of the database schema โ€” useful for capacity planning and comparing environments.
SELECT object_type, COUNT(*) AS total_count
FROM   dba_objects
WHERE  object_type IN ('TABLE','INDEX','VIEW','PROCEDURE',
       'FUNCTION','PACKAGE','TRIGGER','SEQUENCE','SYNONYM')
GROUP  BY object_type
ORDER  BY total_count DESC;

Object Counts by Owner Read-only

Total objects per schema owner grouped by type
๐Ÿ’ก Use this to understand which application schemas contain the most objects โ€” helpful during migrations and schema reviews.
SELECT owner, object_type, COUNT(*) AS cnt
FROM   dba_objects
GROUP  BY owner, object_type
ORDER  BY owner, object_type;

Largest Tables by Segment Size Read-only

Top 20 largest tables by allocated segment size in GB
๐Ÿ’ก Helps identify space-hogging tables โ€” useful for storage planning and deciding which tables might benefit from partitioning.
SELECT owner, segment_name,
       ROUND(bytes/1024/1024/1024,3) AS size_gb
FROM   dba_segments
WHERE  segment_type = 'TABLE'
ORDER  BY bytes DESC
FETCH  FIRST 20 ROWS ONLY;

Database Directories Read-only

Lists all Oracle directory objects with owner and filesystem path
๐Ÿ’ก Directory objects are used by Data Pump, UTL_FILE, and external tables โ€” knowing where they point is essential during migrations.
SELECT owner, directory_name, directory_path
FROM   dba_directories
ORDER  BY owner, directory_name;

Recompile All Invalid Objects Review first

Uses UTL_RECOMP to recompile all invalid schema objects in parallel
๐Ÿ’ก Run this after database upgrades, patching, or schema changes to restore all invalid objects to VALID status.
-- Choose one operation below; uncomment only the required statement.
-- Recompile all invalid objects (parallel)
-- EXEC UTL_RECOMP.RECOMP_PARALLEL(4);

-- Or recompile all serially
-- EXEC UTL_RECOMP.RECOMP_SERIAL;

Health Check7

Tablespaces Nearing Capacity Read-only

Tablespaces above 75% of their effective maximum capacity, including available autoextend headroom.
๐Ÿ’ก Your most important daily check โ€” catches tablespaces heading toward full before applications throw ORA-01653 errors.
SET LINESIZE 180 PAGESIZE 100
COLUMN tablespace_name FORMAT A30
SELECT m.tablespace_name, ROUND(m.used_percent, 2) AS used_pct,
       ROUND(m.tablespace_size * t.block_size / POWER(1024,3), 2) AS max_capacity_gb,
       ROUND(m.used_space * t.block_size / POWER(1024,2), 2) AS used_mb,
       ROUND((m.tablespace_size - m.used_space) * t.block_size / POWER(1024,3), 2) AS headroom_gb
FROM   dba_tablespace_usage_metrics m
JOIN   dba_tablespaces t ON t.tablespace_name = m.tablespace_name
WHERE  m.used_percent > 75
ORDER BY m.used_percent DESC;

ASM Disk Group Usage Read-only

Shows allocated GB, free GB, and percentage used for each ASM disk group
๐Ÿ’ก If you are using ASM storage, run this daily โ€” a disk group nearing full will cause database writes to fail.
SELECT name,
       ROUND(total_mb/1024,2) AS allocated_gb,
       ROUND(free_mb/1024,2)  AS free_gb,
       ROUND(((total_mb-free_mb)/NULLIF(total_mb,0))*100,2) AS pct_used
FROM   v$asm_diskgroup_stat
ORDER  BY pct_used DESC;

Segment Size by Owner Read-only

Total segment size in GB for every schema owner, largest first
๐Ÿ’ก Quickly shows which application schemas are consuming the most storage โ€” standard check during capacity reviews.
SELECT owner,
       ROUND(SUM(bytes)/1024/1024/1024,2) AS size_gb
FROM   dba_segments
WHERE  bytes > 0
GROUP  BY owner
ORDER  BY size_gb DESC;

Segment Size by Owner & Type Read-only

Breaks down storage usage by schema owner and segment type (tables, indexes, LOBs)
๐Ÿ’ก Useful when a specific schema uses unexpected disk space โ€” shows whether tables, indexes, or LOBs are driving the growth.
SELECT owner, segment_type,
       ROUND(SUM(bytes)/1024/1024/1024,2) AS size_gb
FROM   dba_segments
WHERE  bytes > 0
GROUP  BY owner, segment_type
ORDER  BY owner, size_gb DESC;

FRA Health Check Read-only

Fast Recovery Area size, used space, and percentage used in one quick query
๐Ÿ’ก FRA filling up is one of the most common causes of database downtime. Keep usage below 80% to maintain safe archiving headroom.
SELECT ROUND(space_limit/1048576,0)      AS limit_mb,
       ROUND(space_used/1048576,0)       AS used_mb,
       ROUND(space_reclaimable/1048576,0) AS reclaimable_mb,
       ROUND((space_used/NULLIF(space_limit,0))*100,2) AS pct_used
FROM   v$recovery_file_dest;

Invalid Object Summary Read-only

Quick count of all invalid objects in the database with owner breakdown
๐Ÿ’ก A daily check โ€” any increase in invalid object count after a deployment or maintenance window needs immediate attention.
SELECT COUNT(*) AS total_invalid FROM dba_objects WHERE status = 'INVALID';

-- Detail breakdown by owner
SELECT owner, COUNT(*) AS invalid_count
FROM   dba_objects
WHERE  status = 'INVALID'
GROUP  BY owner
ORDER  BY invalid_count DESC;

Active Session Overview Read-only

Current count of active vs inactive sessions and total connections
๐Ÿ’ก A quick pulse check of database load โ€” abnormally high ACTIVE sessions compared to normal baseline signals a potential problem.
SELECT status, type, COUNT(*) AS session_count
FROM   v$session
GROUP  BY status, type
ORDER  BY status, type;

Oracle RAC โ€” Real Application Clusters12

Check Cluster Service Status Read-only

Verifies whether the CRS stack is online on one or all RAC nodes
๐Ÿ’ก Run this as the first check when investigating a RAC node issue โ€” confirms whether the Clusterware stack is up.
# Check CRS stack on the local node
crsctl check crs

# Check cluster on all nodes
crsctl check cluster -all

Cluster Resources Status (Detailed) Read-only

Displays all cluster resources in a formatted table with online/offline state per node
๐Ÿ’ก The most complete RAC health snapshot โ€” every resource is listed with its state on each node.
crsctl stat res -t

Stop / Start Cluster Services Review first

Gracefully stops or starts the Clusterware stack on a specific node or across the entire cluster
๐Ÿ’ก Always stop a specific node first during planned maintenance to avoid disrupting the whole cluster.
# Choose one operation below; uncomment only the required statement.
# Stop cluster on node rac1
# crsctl stop cluster -n rac1

# Stop cluster on ALL nodes
# crsctl stop cluster -all

# Start cluster on node rac1
# crsctl start cluster -n rac1

# Start cluster on ALL nodes
# crsctl start cluster -all

Voting Disk Location Read-only

Shows the location and status of all voting disks used by CSS to determine cluster membership
๐Ÿ’ก Voting disks are critical for RAC quorum โ€” if a node cannot reach the majority, it will be evicted from the cluster.
crsctl query css votedisk

RAC Database Status via SRVCTL Read-only

Shows the current running status of a RAC database and its instances across all cluster nodes
๐Ÿ’ก Replace 'oradb' with your actual database unique name. Shows which instances are running on which nodes.
# Replace 'oradb' with your actual database name
srvctl status database -d oradb

OCR File Integrity Check Read-only

Checks the Oracle Cluster Registry (OCR) disk location and verifies its integrity
๐Ÿ’ก The OCR stores cluster configuration. Run ocrcheck after cluster issues to confirm the registry is not corrupt.
ocrcheck

Cluster Name & Version Read-only

Displays the cluster name and version of the Oracle Clusterware installation
๐Ÿ’ก Run these from the Grid home to see the cluster name and active Clusterware version.
cemutlo -n
crsctl query crs activeversion

Enable / Disable CRS Auto Restart Review first

Controls whether Oracle Clusterware automatically starts when the server boots up
๐Ÿ’ก Disable auto restart before OS-level patching so the cluster does not come up automatically after a reboot. Always re-enable once maintenance is complete.
# Choose one operation below; uncomment only the required statement.
# Disable CRS auto-restart on server reboot
# crsctl disable crs

# Re-enable CRS auto-restart
# crsctl enable crs

RAC Listener Status Read-only

Shows the status of all RAC listeners managed by SRVCTL across all cluster nodes
๐Ÿ’ก In a RAC environment always use SRVCTL to manage listeners โ€” not lsnrctl directly, which bypasses cluster awareness.
srvctl status listener

Stop / Start HAS (Oracle Restart) Review first

Stops or starts the High Availability Service stack โ€” used on standalone Grid Infrastructure environments
๐Ÿ’ก Use these Oracle Restart commands on a standalone Grid Infrastructure host. Stopping HAS can stop the databases and services it manages.
# Choose one operation below; uncomment only the required statement.
# Stop the High Availability Service
# crsctl stop has

# Start the High Availability Service
# crsctl start has

# Check HAS status
# crsctl check has

Cluster Interconnect Details Read-only

Displays all network interfaces registered with Oracle Interface Configuration tool
๐Ÿ’ก The private interconnect carries Cache Fusion traffic. Confirm the correct interface is configured for the interconnect and not the public network.
oifcfg getif

ASMCMD โ€” List All Diskgroups Read-only

Lists mounted ASM disk groups, capacity, free space, and redundancy.
๐Ÿ’ก Run lsdg at the ASMCMD prompt. Use lsdsk to inspect individual disks.
lsdg

Linux Commands for Oracle DBAs15

Oracle Error Lookup (oerr) Read-only

Look up the cause and recommended action for any ORA-, TNS-, RMAN- or EXP/IMP error from the command line, without searching the web first
๐Ÿ’ก Run it from the OS shell on the database server as the oracle user, not inside SQL*Plus. ORACLE_HOME must be set (use . oraenv). Use it as a first step when an error shows up in the alert log or an application log.
# Run on the DB server as oracle user (not in SQL*Plus)
. oraenv                         # Set ORACLE_HOME (enter SID when asked)

# Look up an error (replace 6000 with any ORA number)
oerr ora 6000
oerr ora 1555                    # Example: snapshot too old
oerr ora 00600                   # Leading zeros are optional

# Other error prefixes
oerr tns 12541                   # Listener / network errors
oerr rman 3009                   # RMAN errors
oerr exp 00091                   # Export errors (also: imp, sp2, pls)

# Handy variations
for e in 1555 1652 4031; do oerr ora $e; done   # Several at once
oerr ora 1555 | grep -iE "cause|action"         # Only Cause and Action
grep -i "snapshot too old" $ORACLE_HOME/rdbms/mesg/oraus.msg   # Search by text

Navigation Commands Read-only

Essential directory and file system navigation commands for daily DBA use
๐Ÿ’ก Always run pwd first when SSH-ing to a new server โ€” confirm your location before running any command in production.
pwd              # Print current directory
ls -l            # List with permissions, owner, size
ls -la           # Include hidden files
ls -lh           # Human-readable sizes
cd /u01/app      # Go to absolute path
cd ..            # Go one level up
cd ~             # Go to home directory
cd -             # Go to previous directory
clear            # Clear terminal (Ctrl+L)

Disk Space Usage Read-only

Check disk space usage on filesystems and directories
๐Ÿ’ก As a DBA, run df -h daily to check filesystem space โ€” especially /u01, /u02, and archive log destinations to prevent ORA-00257.
df -h                      # All mounted filesystems (human-readable)
df -h /u01                 # Specific filesystem
du -sh /u01/app/oracle     # Size of a directory
du -sh /u02/archivelogs/*  # Archive log sizes
du -h --max-depth=1 /u01   # Directory sizes one level deep

Process Monitoring Read-only

Monitor running processes, CPU and memory usage โ€” essential for DBA performance checks
๐Ÿ’ก Use ps -ef | grep ora to quickly confirm Oracle background processes are running. top shows real-time CPU and memory consumption.
ps -ef | grep ora          # All Oracle processes
ps -ef | grep pmon         # Check PMON is running
ps aux | sort -rk 3 | head # Top CPU consumers
top                        # Real-time process monitor
top -u oracle              # Oracle user processes only
free -h                    # Memory and swap usage

File Permissions & Ownership Use carefully

Change file permissions and ownership โ€” critical for Oracle software installations
๐Ÿ’ก Oracle datafiles and binaries must have correct ownership (oracle:oinstall) and permissions. Incorrect permissions prevent startup.
ls -l filename             # View current permissions

# chmod โ€” change permissions
chmod 755 script.sh        # rwxr-xr-x (scripts)
chmod 640 oracle.conf      # rw-r-----  (config files)
chmod 600 orapwORCL        # rw-------- (password file)

# chown โ€” change owner
chown oracle:oinstall file

Alert Log Monitoring Read-only

Commands to monitor the Oracle alert log and search for errors in real-time
๐Ÿ’ก Always monitor the alert log after any database operation โ€” it is the first place Oracle reports errors, crashes, and important events.
# Tail the alert log in real-time
tail -100f $ORACLE_BASE/diag/rdbms/ORCL/ORCL/trace/alert_ORCL.log

# Search for ORA- errors in alert log
grep -i "ORA-" alert_ORCL.log | tail -50

# Search for errors in last 100 lines
tail -100 alert_ORCL.log | grep -i "error\|ORA-\|fatal"

# Find alert log location from SQL
SELECT value FROM v$diag_info WHERE name = 'Diag Trace';

Oracle Environment Variables Read-only

Check and set Oracle environment variables โ€” required before running Oracle commands
๐Ÿ’ก Always verify your environment variables before running sqlplus or RMAN โ€” wrong ORACLE_SID will connect to the wrong database.
# Check current Oracle environment
echo $ORACLE_HOME
echo $ORACLE_SID
echo $ORACLE_BASE
echo $PATH

# Set Oracle environment variables
export ORACLE_BASE=/u01/app/oracle
export ORACLE_HOME=$ORACLE_BASE/product/19.0.0.0/dbhome_1
export ORACLE_SID=ORCL
export PATH=$ORACLE_HOME/bin:$PATH

# List all environment variables
env | grep -i oracle

SSH & File Transfer (SCP) Use carefully

Connect to remote servers and transfer files between hosts
๐Ÿ’ก Use SCP to transfer Oracle software binaries, backup files, and scripts between servers. Always verify the destination path before transferring large files.
# SSH to a remote server
ssh oracle@192.168.1.100
ssh -p 22 oracle@hostname

# Copy file TO remote server
scp /local/file.tar oracle@remote:/destination/

# Copy file FROM remote server
scp oracle@remote:/path/file.tar /local/path/

# Copy directory recursively
scp -r /local/dir oracle@remote:/destination/

# Check SSH connectivity
ssh -v oracle@hostname  # verbose output

grep, awk, sed โ€” Text Processing Read-only

Powerful text filtering tools used daily by Oracle DBAs for log analysis and scripting
๐Ÿ’ก grep with -i is case-insensitive โ€” essential for searching Oracle logs. awk is ideal for extracting columns from structured output.
# grep โ€” search for patterns
grep -i "ora-" alert_ORCL.log   # Case-insensitive
grep -n "error" file.txt         # Show line numbers
grep -v "SQL*Net" file.txt       # Exclude matches
grep -E "ORA-00257|ORA-01555"    # Multiple patterns

# awk โ€” extract columns
df -h | awk '{print $1, $5}'     # Show col 1 and 5
ps -ef | awk '{print $1, $8}'    # User and command

# sed โ€” stream editor
sed 's/OLDVALUE/NEWVALUE/g' file # Replace text
sed -n '10,20p' file.txt         # Print lines 10-20

Network Connectivity Checks Read-only

Test network connectivity and check Oracle listener port availability
๐Ÿ’ก Always check port 1521 connectivity from the application server before troubleshooting TNS errors โ€” the issue may be a firewall rule, not Oracle.
ping -c 4 hostname          # Test basic connectivity
traceroute hostname          # Trace network path

# Check if port 1521 is listening
netstat -tlnp | grep 1521
ss -tlnp | grep 1521

# Test port reachability from client
telnet db-server 1521

# Check tnsping (Oracle)
tnsping ORCL               # Test TNS connection

Cron Jobs (Scheduled Tasks) Use carefully

Schedule Oracle backup scripts and maintenance tasks using crontab
๐Ÿ’ก Always test your script manually before adding to cron. Redirect stdout and stderr to a log file so you can see failures in cron-executed scripts.
# Edit the crontab for the oracle user
crontab -e

# View current crontab
crontab -l

# Crontab format: MIN HOUR DOM MON DOW COMMAND
# Run RMAN backup every night at 11:00 PM
0 23 * * * /home/oracle/scripts/rman_backup.sh >> /tmp/rman_backup.log 2>&1

# Run archive log cleanup every 6 hours
0 */6 * * * /home/oracle/scripts/clean_archivelogs.sh

# Check cron service is running
systemctl status crond

vi / vim Editor Essentials Use carefully

Essential vi/vim commands for editing Oracle configuration files on Linux
๐Ÿ’ก vi is available on every Unix/Linux server โ€” even minimal installations. Master these basic commands to edit listener.ora, tnsnames.ora, and bash_profile.
vi filename             # Open file in vi editor

# MODES:
# Press 'i'    โ†’ Insert mode (start typing)
# Press 'Esc'  โ†’ Return to command mode

# SAVING & QUITTING (command mode):
:w               # Save file
:q               # Quit (no changes)
:wq              # Save and quit
:q!              # Quit without saving
:wq!             # Force save and quit

# NAVIGATION (command mode):
gg               # Go to first line
G                # Go to last line
:n               # Go to line number n
/searchterm      # Search forward
n                # Next search result

YUM Package Management Use carefully

Install Oracle pre-requisite packages and manage software using YUM
๐Ÿ’ก Always install oracle-database-preinstall-19c before installing Oracle Database โ€” it automatically sets kernel parameters and creates the oracle user.
# Install Oracle 19c pre-install package
yum install -y oracle-database-preinstall-19c

# Install common packages
yum install -y vim wget curl net-tools

# Check if a package is installed
rpm -qa | grep oracle

# Check installed package version
rpm -q oracle-database-preinstall-19c

Archive & Compress Files Use carefully

Create, extract, and manage compressed archives โ€” used for Oracle software and backup transfers
๐Ÿ’ก Choose an extraction directory and inspect the archive contents before extracting files.
# Create a compressed tar archive
tar -czf archive.tar.gz /path/to/dir

# Extract a tar archive
tar -xzf archive.tar.gz

# List contents without extracting
tar -tzf archive.tar.gz

# Unzip Oracle software
unzip LINUX.X64_193000_db_home.zip -d /u01/app/oracle/product/19.0.0.0/dbhome_1/

# Check file size
ls -lh archive.tar.gz
du -sh /path/to/directory

User & Group Management Review first

Create Oracle OS users and groups required for Oracle Database and Grid Infrastructure installation
๐Ÿ’ก The oracle user must be in the oinstall, dba, and asmdba groups. Wrong group membership is one of the most common Oracle installation failures.
# Create groups
groupadd oinstall
groupadd dba
groupadd asmdba
groupadd asmadmin

# Create oracle user
useradd -g oinstall -G dba,asmdba oracle
passwd oracle

# Create grid user (for Grid Infrastructure)
useradd -g oinstall -G asmdba,asmadmin grid
passwd grid

# Check user groups
id oracle
id grid

# Add existing user to a group
usermod -aG dba oracle