Home

Thursday, September 14, 2023

How to find long running sessions in Oracle database

In a daily day to day activities it is required for an Oracle Dba to check long running sessions and long running jobs and tune them or kill them  if required.

In Oracle Database, a "long-running session" typically refers to a database session that has been active for an extended period of time. A session in the context of a database is a user's connection to the database, and it can be initiated by applications, users, or background processes.

Performance Impact: Long-running sessions can sometimes negatively impact the performance of the database. These sessions might hold locks on database objects for an extended duration, blocking other sessions from accessing those objects and potentially leading to deadlocks.

Resource Utilization: Long-running sessions consume database resources such as CPU, memory, and I/O for an extended period. This can affect the overall system's resource availability and may lead to resource contention.

Transaction Management: In a long-running session, it's important to manage transactions effectively. Long-running transactions can make it difficult to recover from failures and can result in large rollback segments if the transaction needs to be rolled back.

Connection Pooling: In some cases, long-running sessions can disrupt connection pooling mechanisms that are commonly used to manage database connections efficiently. If sessions are not released promptly, connection pools may become exhausted, impacting application scalability.

Diagnosis and Monitoring: Long-running sessions can be a sign of issues in the application or database design. Database administrators and developers need to monitor and diagnose long-running sessions to identify performance bottlenecks and optimize database operations.

To address long-running sessions, it's important to:

1.Review and optimize SQL queries and transactions to minimize their impact on the database.

2.Set appropriate timeouts for database connections and transactions.

3.Implement deadlock detection and resolution mechanisms.

4.Use database monitoring and profiling tools to identify and address long-running sessions proactively.

5.Consider implementing session or resource limits to prevent runaway sessions from consuming excessive resources.

6.Managing long-running sessions effectively is an important aspect of database performance tuning and application development to ensure that the database operates efficiently and reliably.


Below are some of the sql queries to find out if there is any long running session or long running jobs


****very good Query to check sql_id's monitor or executing currently*****

set lines 1000 pages 9999 

column sid format 9999 

column serial for 999999

column status format a15

column username format a10 

column sql_text format a80

column module format a30

col program for a30

col SQL_EXEC_START for a20

SELECT * FROM

       (SELECT status,inst_id,sid,SESSION_SERIAL# as Serial,username,sql_id,SQL_PLAN_HASH_VALUE,

     MODULE,program,

         TO_CHAR(sql_exec_start,'dd-mon-yyyy hh24:mi:ss') AS sql_exec_start,

         ROUND(elapsed_time/1000000)                      AS "Elapsed (s)",

         ROUND(cpu_time    /1000000)                      AS "CPU (s)",

         substr(sql_text,1,30) sql_text

       FROM gv$sql_monitor where status='EXECUTING' and module not like '%emagent%' 

       ORDER BY sql_exec_start  desc

       );


SELECT SID, SERIAL#,OPNAME, CONTEXT, SOFAR, TOTALWORK,ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE" FROM GV$SESSION_LONGOPS WHERE OPNAME NOT LIKE '%aggregate%' AND TOTALWORK != 0 AND SOFAR <> TOTALWORK;

                                                                 or

SET LINESIZE 100

SET PAGESIZE 100

SET TRIMOUT ON

SET TRIMSPOOL ON

COLUMN job_name FORMAT A20

COLUMN state FORMAT A15

COLUMN percent_completed FORMAT 999.99

SELECT sid, serial#, username, sql_id, start_time,

 ROUND((sofar/totalwork)*100, 2) AS percent_completed

FROM v$session_longops

WHERE sofar <> totalwork;

SELECT s.sid, s.serial#, s.username, s.sql_id, l.start_time,

       ROUND((l.sofar/l.totalwork)*100, 2) AS percent_completed,

       q.sql_text

FROM v$session_longops l

JOIN v$sql q ON l.sql_id = q.sql_id

JOIN v$session s ON l.sid = s.sid AND l.serial# = s.serial#

WHERE l.sofar <> l.totalwork;

                                                                  or

set lines 300

col TARGET for a40

col SQL_ID for a20

select SID,TARGET||OPNAME TARGET, TOTALWORK, SOFAR,TIME_REMAINING/60 Mins_Remaining, ELAPSED_SECONDS, SQL_ID from v$session_longops where TIME_REMAINING>0 order by TIME_REMAINING; 

                                                         or

set lines 789 pages 789

COL OPNAME FOR A40

COL USERNAME FOR A15

col message for a70

select sid,serial#, to_char(START_TIME,'dd-mm-yy hh:mi:ss ') "Start Time", username, SQL_ID, OPNAME, message,SOFAR,TOTALWORK, round((SOFAR/TOTALWORK)*100) pct_completed,TIMESTAMP,TIME_REMAINING from v$session_longops where TOTALWORK>1 and sid in  (select a.sid FROM gv$session a where a.status='ACTIVE') and SOFAR!=TOTALWORK ;

                                                                          or

set lines 150

set pages 999

col username format a12

col message format a100

col strt format a10

col updtd format a10

col "%" format 999

break on username skip 1

select username,to_char(start_time,'dd hh24:mi') strt,to_char(last_update_time,'dd hh24:mi') updtd,round(sofar/(totalwork+1)*100) "%", MESSAGE  from gv$session_longops where (SID,SERIAL#) IN (select sid,serial# from gv$session where status ='ACTIVE')  order by username,strt;




Tuesday, September 5, 2023

Why Is My Query Sometimes Slower

 Why Is My Query Sometimes Slower Than Other Times with Higher Consistent Gets Although No Change in Execution Plan? (Doc ID 1558349.1)


SYMPTOMS

A new query is tested on a test database. When the same query is tested in a production environment, the elapsed time is higher.


CHANGES

The procedures in package DBMS_XPLAN indicate no change in execution plan between the two environments.  The test environment is restored back-up of the production database with the same volume of data.


CAUSE

The difference is between executing the query in an isolated environment versus within an environment in which DML is being applied to the table while the query is executing.


SOLUTION:

The activity described above is normal and necessary activity required for Oracle Database to maintain consistency of data.  The only real way to solve this issue is one of following options:


1.Schedule DML activity separately from reporting activity.

2.If slight staleness of the data may be tolerated, then perform reporting activity upon a materialized view or upon a read-only copy of the production database which may be refreshed on a routine schedule.

3.Execute reports against a Data Guard Standby Database opened in read-only mode.


Thursday, August 10, 2023

How to convert 2 Node RAC Physical standby database to snapshot Standby

Steps to convert 2 Node RAC Physical standby database to snapshot Standby

Here in this scenario we have 2 node Primary  and 2 node standby resources :

Prod Db name: Shamsprd0

Standby Db name : Shamssty0

Primary DB : Shamsprd01 &  Shamsprd02 

Standby DB : Shamssty01 & Shamssty02 


STEPS :

A. Check if the standby database is in sync and there are no gaps 

TO check on standby server:

Select a.thread#,b.last_seq,a.applied_seq,a.last_app_timestamp,b.last_seq-a.applied_seq

ARC_DIFF from (Select thread#,MAX(sequence#) applied_seq,MAX(next_time) last_app_timestamp FROM gv$archived_log

where applied='YES' GROUP BY thread#) a,(SELECT thread#,MAX(sequence#) last_seq FROM gv$archived_log GROUP by thread#)

b WHERE a.thread#=b.thread#;


Verify whether flashback is ON, or else start Flashback

If Flashback is Turned OFF, then you need to cancel your MRP and TURN ON Flashback, after which the MRP can be turned ON again

SQL> select flashback_on from v$database;

FLASHBACK_ON

------------------

NO

SQL> select log_mode,flashback_on from gv$database;

LOG_MODE     FLASHBACK_ON

------------ ------------------

ARCHIVELOG   NO

ARCHIVELOG   NO


SQL> show parameter db_recovery_file_dest

NAME                                 TYPE        VALUE

------------------------------------ ----------- ------------------------------

db_recovery_file_dest                string      +RECO

db_recovery_file_dest_size           big integer 2000G


SQL> alter database recover managed standby database cancel;

Database altered.


SQL> alter database flashback on;

 Database altered.


SQL> select log_mode,flashback_on from gv$database;

LOG_MODE     FLASHBACK_ON

------------ ------------------

ARCHIVELOG   YES

ARCHIVELOG   YES


SQL> alter database recover managed standby database disconnect from session;

Database altered.

 

B. Check the Status of your Standby Database and cancel the MRP

SQL> select status,instance_name,database_role,open_mode from gv$database,gv$instance;

STATUS       INSTANCE_NAME    DATABASE_ROLE    OPEN_MODE

------------ ---------------- ---------------- -------------------------------------------------

OPEN         Shamssty01   PHYSICAL STANDBY READ ONLY WITH APPLY

OPEN         Shamssty02   PHYSICAL STANDBY READ ONLY WITH APPLY


SQL> alter database recover managed standby database cancel;

Database altered.

 

C. Bounce the Database to Mount mode

srvctl stop database -d  Shamssty0

srvctl start database -d  Shamssty0 -o mount

 

D. Convert the database to Snapshot Standby Database

SQL> alter database convert to snapshot standby;

 

E. Check the Database Role and then open the Database in Read/Write mode

SQL> select status,instance_name,database_role,open_mode from v$database,v$Instance;

STATUS       INSTANCE_NAME    DATABASE_ROLE    OPEN_MODE

------------ ---------------- ---------------- --------------------

MOUNTED      Shamssty01           SNAPSHOT STANDBY MOUNTED


SQL> alter database open;

Note: Handover the Database for testing team to test from their end

Convert the database from Snapshot Standby to Physical Standby

Once the testing is complete, we need to revert back the database to Physical standby again


A. Shut down the database

$srvctl stop database -d Shamssty0

 

B. Start the database from only 1 Node

This is because, if instances from all nodes are started, it wont let you convert from snapshot to physical standby database

DONOT PERFORM below step

$srvctl start database -d Shamssty0

SQL> alter database convert to physical standby;

alter database convert to physical standby

*

ERROR at line 1:

ORA-38777: database must not be started in any other instance

Started database from 1st node

$srvctl start instance -d Shamssty0 -i Shamssty01 -o mount 

 C. Check the status and convert to Physical Standby

SQL> select status,instance_name,database_role,open_mode from gv$database,gv$Instance;

STATUS       INSTANCE_NAME    DATABASE_ROLE    OPEN_MODE

------------ ---------------- ---------------- ------------------------------------------------------------

MOUNTED      Shamssty0             SNAPSHOT STANDBY MOUNTED


SQL> alter database convert to physical standby;

Database altered.

 

D. Bounce the database

This restart is required to be on the safer side and start instances from all nodes


$srvctl stop database -d Shamssty0

$srvctl start database -d Shamssty0 -o mount


SQL> select status,instance_name,database_role,open_mode from v$database,v$Instance;

STATUS       INSTANCE_NAME    DATABASE_ROLE    OPEN_MODE

------------ ---------------- ---------------- --------------------

MOUNTED      Shamssty0             PHYSICAL STANDBY MOUNTED


 E. Start the recovery and check whether the Physical standby database is in SYNC with the primary or not

SQL> alter database recover managed standby database disconnect from session;

TO check on standby server:

Select a.thread#,b.last_seq,a.applied_seq,a.last_app_timestamp,b.last_seq-a.applied_seq

ARC_DIFF from (Select thread#,MAX(sequence#) applied_seq,MAX(next_time) last_app_timestamp FROM gv$archived_log

where applied='YES' GROUP BY thread#) a,(SELECT thread#,MAX(sequence#) last_seq FROM gv$archived_log GROUP by thread#)

b WHERE a.thread#=b.thread#;

                                                           


Enjoy the work and do like me if you like this article!!!.

Saturday, August 5, 2023

How to purge golden gate trail files

 How to purge golden gate Trail Files

As archive log,clean,reco,Fra clean up Dba should also think about purging golden gate trail files to purge them.

Current usage:

oracle@Shamstech:/home/oracle>df -hP

Filesystem                            Size  Used Avail Use% Mounted on

/data/GG_data                     954G  729G  225G  77% /u03


step1:

oracle@Shamstech:>ggsci

Oracle GoldenGate Command Interpreter for Oracle

Operating system character set identified as UTF-8.

Copyright (C) 1995, 2019, Oracle and/or its affiliates. All rights reserved.


GGSCI (oracle@Shamstech) 1> info all

Program     Status      Group       Lag at Chkpt  Time Since Chkpt

MANAGER     RUNNING

EXTRACT     RUNNING     EXTRCT1      00:00:06      00:00:08

EXTRACT     RUNNING     EXTRCT2      00:00:00      00:00:00

Note: Here there is no lag in GG and GG is in sync


step2:Change the MINKEEPHOURS from 96 yo 48

oracle@Shamstech:>cat mgr.prm

PORT 7809

-- Purge old extract entries.

PURGEOLDEXTRACTS /data/GG_data/dirdat/EXTRCT1/in*, USECHECKPOINTS, MINKEEPHOURS 96


oracle@Shamstech:>ggsci

Oracle GoldenGate Command Interpreter for Oracle


step3:

GGSCI (oracle@Shamstech) 1> refresh mgr

Sending REFRESH request to MANAGER ...

Mgr Params Updated


step4:

GGSCI (oracle@Shamstech) 2> send manager getpurgeoldextracts

Sending GETPURGEOLDEXTRACTS request to MANAGER ...

PurgeOldExtracts Rules

Fileset                              MinHours MinFiles UseCP

/u02/ggdata/dirdat/EXTRCT1/i       48        1   Y

OK

Extract Trails

Filename                        Oldest_Chkpt_Seqno

/u02/ggdata/dirdat/EXTRCT1/in   143864


step5:

GGSCI (oracle@Shamstech) 3> send manager purgeoldextracts


step6: Change the MINKEEPHOURS from 48 to 96

oracle@Shamstech:>cat mgr.prm

PORT 7809

-- Purge old extract entries.

PURGEOLDEXTRACTS /data/GG_data/dirdat/EXTRCT1/in*, USECHECKPOINTS, MINKEEPHOURS 96


After usage: 

oracle@Shamstech:>df -hP

Filesystem                   Size  Used Avail Use% Mounted on

/data/GG_data         954G   96G  859G  10% /u03

Note: The space cleared from /u03 file system after 10mins......


oracle@Shamstech:>ggsci

GGSCI (oracle@Shamstech) 1> refresh MGR

Sending REFRESH request to MANAGER ...

Mgr Params Updated


Enjoy the work and do like me if you like this article!!!

How to clear space from reco disk group on standby server

 +RECO disk group filled up on standby server by 78%:

You have received alert mail  from OEM saying that 

 OEM Alert : RECO Disk group is 78% used on oracle@Shamstech server....

[oracle@Shamstech ~]$ . oraenv

ORACLE_SID = [Shams1] ? Shams1

The Oracle base remains unchanged with value /u01/app/oracle


Check if the standby database is in sync with prod:

Select a.thread#,b.last_seq,a.applied_seq,a.last_app_timestamp,b.last_seq-a.applied_seq

ARC_DIFF from (Select thread#,MAX(sequence#) applied_seq,MAX(next_time) last_app_timestamp FROM gv$archived_log

where applied='YES' GROUP BY thread#) a,(SELECT thread#,MAX(sequence#) last_seq FROM gv$archived_log GROUP by thread#)

b WHERE a.thread#=b.thread#;

   THREAD#   LAST_SEQ APPLIED_SEQ LAST_APP_   ARC_DIFF

---------- ---------- ----------- --------- ----------

          1      10703       10702 04-AUG-20          1

         2      12420       12420 04-AUG-20          0


Connect to Rman prompt:

[oracle@Shamstech ~]$ rman target /

Recovery Manager: Release 19.0.0.0.0 - Production on Fri Aug 4 23:02:25 2023

Version 19.14.0.0.0

Copyright (c) 1982, 2019, Oracle and/or its affiliates.  All rights reserved.

connected to target database: Shams1 (DBID=438985516, not open)

RMAN>crosscheck archivelog all;

Crosschecked 215 objects


RMAN>delete noprompt archivelog until time 'sysdate -1';

......

deleted archived log


RMAN>crosscheck archivelog all;

......

Crosschecked 210 objects

Query to check space check on asm diskgroup:

SQL> select distinct (NAME) "DISKGROUP",round(TOTAL_MB/1024) "Total Size in GB",round(FREE_MB/1024)

"Free Space in GB",round(FREE_MB/TOTAL_MB*100) "Pct Free",round((TOTAL_MB-FREE_MB)/TOTAL_MB*100) "Pct used" from v$ASM_DISKGROUP   ;

Before usage:

DISKGROUP                      Total Size in GB Free Space in GB   Pct Free   Pct used

------------------------------ ---------------- ---------------- ---------- ---------------------------------------------

RECO                                      16384              12779.52                10         78

SQL> !hostname

Shamstech.standby.com

After usage:

DISKGROUP                      Total Size in GB Free Space in GB   Pct Free   Pct used

------------------------------ ---------------- ---------------- ---------- ---------------------------------------------

RECO                                      16384             5646         34         66

SQL> !hostname

Shamstech.standby.com


Note1: Here the standby database is in sync with primary and there is no archive gap and we deleted the applied archive logs applied on standby database keeping 1 day logs.

Note2: If the standby database is not in sync with primary and if there is a archive gap and then we have to  use  RMAN> delete noprompt archivelog until time 'sysdate -3'; 

it means we are deleting applied archive logs and keeping 2days log

You can use the below options  as well

 RMAN> DELETE NOPROMPT ARCHIVELOG UNTIL SEQUENCE =62012;

RMAN>DELETE ARCHIVELOG ALL COMPLETED BEFORE 'sysdate-2';

RMAN>DELETE  ARCHIVELOG ALL BACKED UP 1 TIMES TO DEVICE TYPE sbt;


Enjoy the work and do like me if you like this article!!!

Thursday, August 3, 2023

Useful scripts for Dba's

Tablespace usage script1:

select a.tablespace_name,

        round(sum(a.bytes)/1024/1024) Size_MB,

        round(sum(b.bytes)/1024/1024) free_MB,

         case when round(sum(a.maxbytes)/1024/1024) > 0 then round(sum(a.maxbytes)/1024/1024) else round(sum(a.bytes)/1024/1024) end Max_MB,

        round(sum(a.bytes)/1024/1024) - round(sum(b.bytes)/1024/1024) Used_MB,

        c.bigfile

from (select tablespace_name, sum(bytes) bytes, sum(maxbytes) maxbytes from dba_data_files group by tablespace_name) a,

        (select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) b,

        dba_tablespaces c

where a.tablespace_name = b.tablespace_name (+)

and a.tablespace_name = c.tablespace_name

group by a.tablespace_name, c.bigfile

union

select a.tablespace_name,

        round(sum(a.bytes)/1024/1024) Size_MB,

        round(sum(b.free_space)/1024/1024) free_MB,

        case when round(max(a.maxbytes)/1024/1024) > 0 then round(max(a.maxbytes)/1024/1024) else round(sum(a.bytes)/1024/1024) end Max_MB,

        round(sum(a.bytes)/1024/1024) - round(sum(b.free_space)/1024/1024) Used_MB,

        c.bigfile 

from (select tablespace_name, sum(bytes) bytes, sum(maxbytes) maxbytes from dba_temp_files group by tablespace_name) a,

        DBA_TEMP_FREE_SPACE b,

        dba_tablespaces c

where a.tablespace_name = b.tablespace_name (+)

and a.tablespace_name = c.tablespace_name        

group by a.tablespace_name, c.bigfile ;


Tablespace usage script2:

clear breaks

set linesize 132

set pagesize 60

break on tablespace_name skip 1

col tablespace_name format a15

SELECT df.tablespace_name TABLESPACE, df.total_space TOTAL_SPACE,

fs.free_space FREE_SPACE, df.total_space_mb TOTAL_SPACE_MB,

(df.total_space_mb - fs.free_space_mb) USED_SPACE_MB,

fs.free_space_mb FREE_SPACE_MB,

ROUND(100 * (fs.free_space / df.total_space),2) PCT_FREE

FROM (SELECT tablespace_name, SUM (bytes) TOTAL_SPACE,

      ROUND( SUM (bytes) / 1048576) TOTAL_SPACE_MB

      FROM dba_data_files

      GROUP BY tablespace_name) df,

     (SELECT tablespace_name, SUM (bytes) FREE_SPACE,

       ROUND( SUM (bytes) / 1048576) FREE_SPACE_MB

       FROM dba_free_space

       GROUP BY tablespace_name) fs

WHERE df.tablespace_name = fs.tablespace_name(+)

ORDER BY fs.tablespace_name;


Tablespace usage script3:

set linesize 200

set feedback off

set echo off

set arraysize 25

set heading off

set pagesize 0

set verify off

set wrap on

set tab off

SELECT * FROM (

SELECT c.tablespace_name,

ROUND(a.bytes/1048576,2) MB_Allocated,

ROUND(b.bytes/1048576,2) MB_Free,

ROUND((a.bytes-b.bytes)/1048576,2) MB_Used,

ROUND(b.bytes/a.bytes * 100,2) tot_Pct_Free,

ROUND((a.bytes-b.bytes)/a.bytes,2) * 100 tot_Pct_Used

FROM (SELECT tablespace_name,

SUM(a.bytes) bytes

FROM sys.DBA_DATA_FILES a

GROUP BY tablespace_name) a,

(SELECT a.tablespace_name,

NVL(SUM(b.bytes),0) bytes

FROM sys.DBA_DATA_FILES a,

sys.DBA_FREE_SPACE b

WHERE a.tablespace_name = b.tablespace_name (+)

AND a.file_id = b.file_id (+)

GROUP BY a.tablespace_name) b,

sys.DBA_TABLESPACES c

WHERE a.tablespace_name = b.tablespace_name(+)

AND a.tablespace_name = c.tablespace_name

) WHERE tot_Pct_Used >=0

ORDER BY MB_Free;


Tablespace usage script4:

set lines 223 pages 999;

select tablespace_name,round((USED_SPACE*8)/1024)CURRENT_SIZE_MB,round((TABLESPACE_SIZE*8)/1024) MAX_SIZE_MB,

round(USED_PERCENT,2) USED_PERCENT from DBA_TABLESPACE_USAGE_METRICS where USED_PERCENT>70

order by  USED_PERCENT;


Tablespace usage script5:

select tablespace_name,round((USED_SPACE*8)/1024)CURRENT_SIZE_MB,round((TABLESPACE_SIZE*8)/1024) MAX_SIZE_MB,

round(USED_PERCENT,2) USED_PERCENT from DBA_TABLESPACE_USAGE_METRICS where  tablespace_name like '%TEMP%' order by USED_PERCENT;


Tablespace usage script6:

select tablespace_name,round((USED_SPACE*8)/1024)CURRENT_SIZE_MB,round((TABLESPACE_SIZE*8)/1024) MAX_SIZE_MB,

round(USED_PERCENT,2) USED_PERCENT from DBA_TABLESPACE_USAGE_METRICS where  tablespace_name like '%DATA%' order by USED_PERCENT;


calculate how much undo tablespace we need exactly:

SELECT d.undo_size/(1024*1024) "ACTUAL UNDO SIZE [MByte]",

       SUBSTR(e.value,1,25) "UNDO RETENTION [Sec]",

       (TO_NUMBER(e.value) * TO_NUMBER(f.value) *

       g.undo_block_per_sec) / (1024*1024)

      "NEEDED UNDO SIZE [MByte]"

  FROM (

       SELECT SUM(a.bytes) undo_size

         FROM v$datafile a, v$tablespace b, dba_tablespaces c

        WHERE c.contents = 'UNDO' AND c.status = 'ONLINE'

          AND b.name = c.tablespace_name AND a.ts# = b.ts#

       ) d,

      v$parameter e, v$parameter f,

       (

       SELECT MAX(undoblks/((end_time-begin_time)*3600*24))

         undo_block_per_sec

         FROM v$undostat

       ) g

 WHERE e.name = 'undo_retention' AND f.name = 'db_block_size';

Solution:

Increasing UNDO tablespace size is not the solution for this.

Run Undo advisory

Increase UNDO Retension Period

Enable Undo Retention Guarantee

Run this Select Query during non-business hours where heavy transactions are not happening.

Tune the Query


Displays Space Usage for Each Datafile:

SET PAUSE ON

SET PAUSE 'Press Return to Continue'

SET PAGESIZE 60

SET LINESIZE 300

COLUMN "Tablespace Name" FORMAT A20

COLUMN "File Name" FORMAT A80

SELECT  Substr(df.tablespace_name,1,20) "Tablespace Name",

        Substr(df.file_name,1,80) "File Name",

        Round(df.bytes/1024/1024,0) "Size (M)",

        decode(e.used_bytes,NULL,0,Round(e.used_bytes/1024/1024,0)) "Used (M)",

        decode(f.free_bytes,NULL,0,Round(f.free_bytes/1024/1024,0)) "Free (M)",

        decode(e.used_bytes,NULL,0,Round((e.used_bytes/df.bytes)*100,0)) "% Used"

FROM    DBA_DATA_FILES DF,

       (SELECT file_id,

               sum(bytes) used_bytes

        FROM dba_extents

        GROUP by file_id) E,

       (SELECT sum(bytes) free_bytes,

               file_id

        FROM dba_free_space

        GROUP BY file_id) f

WHERE    e.file_id (+) = df.file_id

AND      df.file_id  = f.file_id (+)

ORDER BY df.tablespace_name,

         df.file_name

/

col "Tablespace" for a22

col "Used MB" for 99,999,999

col "Free MB" for 99,999,999

col "Total MB" for 99,999,999

select df.tablespace_name "Tablespace",

totalusedspace "Used MB",

(df.totalspace - tu.totalusedspace) "Free MB",

df.totalspace "Total MB",

round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace))

"Pct. Free"

from

(select tablespace_name,

round(sum(bytes) / 1048576) TotalSpace

from dba_data_files

group by tablespace_name) df,

(select round(sum(bytes)/(1024*1024)) totalusedspace, tablespace_name

from dba_segments

group by tablespace_name) tu

where df.tablespace_name = tu.tablespace_name ;

Tablespace                 Used MB     Free MB    Total MB  Pct. Free

---------------------- ----------- ----------- ----------- ----------

SYSAUX                       2,786         814       3,600         23


To check the space available in that particular tablespace:

select c.tablespace_name,

round(decode(d.autoext,NULL,decode(e.free,NULL,0,e.free)/(1024*1024),(f.maxsz+decode(g.nonauto_sz,NULL,0,g.nonauto_sz)-f.totsz+decode(e.free,NULL,0,e.free))/ (1024*1024))) free_mb,

round(f.totsz/(1024*1024)) Total_mb,

round((f.maxsz+decode(g.nonauto_sz,NULL,0,g.nonauto_sz))/(1024*1024)) maxsize_mb,

decode(d.autoext, NULL, 'NO','YES') ae,

round(decode(d.autoext,NULL,(f.totsz-decode(e.free,NULL,0,e.free))/f.totsz*100,(f.totsz-decode(e.free,NULL,0,e.free))/(f.maxsz+decode(g.nonauto_sz,NULL,0,g.nonauto_sz))*100)) as Used_pct

from dba_tablespaces c,

(select a.tablespace_name, count(b.autoextensible) autoext

from dba_tablespaces a, dba_data_files b

where a.tablespace_name = b.tablespace_name(+) and b.autoextensible = 'YES'

group by a.TABLESPACE_NAME

having count(b.autoextensible) > 0) d,

(select tablespace_name, sum(bytes) free

from dba_free_space

group by tablespace_name) e,

(select df1.tablespace_name, sum(df1.bytes) totsz, sum(df1.maxbytes) maxsz

from dba_data_files df1, dba_tablespaces ts1

where ts1.tablespace_name = df1.tablespace_name

group by df1.tablespace_name) f,

(select df2.tablespace_name, sum(df2.bytes) nonauto_sz

from dba_data_files df2, dba_tablespaces ts2

where ts2.tablespace_name = df2.tablespace_name and df2.autoextensible = 'NO'

group by df2.tablespace_name) g

where c.tablespace_name = d.tablespace_name(+) and

c.tablespace_name = e.tablespace_name(+) and

c.tablespace_name = f.tablespace_name and

c.tablespace_name = g.tablespace_name(+) and c.tablespace_name like '%DATA%' order by c.tablespace_name;


Script to check usage of each datafile in a tablespace:

set lines 200 pages 600

col file_name for a70

select file_name,autoextensible,ceil(maxbytes/(1024*1024)) maxsize_mb, ceil(bytes/(1024*1024)) cursize_mb from dba_data_files where tablespace_name='DATA';


Script to check space in temp file:

select file_name,autoextensible,ceil(maxbytes/(1024*1024)) maxsize_mb, ceil(bytes/(1024*1024)) cursize_mb from dba_temp_files where tablespace_name='TEMP';


check the free space available in the ASM Disk group

set lines 200

SELECT name,total_mb/1024 "TOTAL(GB)",(total_mb-free_mb)/1024 "USED(GB)",free_mb/1024 "FREE(GB)",(free_mb/total_mb)*100 "FREE PERCENTAGE" FROM v$asm_diskgroup;


Script to check space in particular asm diskgroup:

set lines 200

SELECT name,total_mb/1024 "TOTAL(GB)",(total_mb-free_mb)/1024 "USED(GB)",free_mb/1024 "FREE(GB)",(free_mb/total_mb)*100 "FREE PERCENTAGE" 

FROM v$asm_diskgroup; where name='DATA';


Asm Rebalance query:

SET pagesize 299

SET lines 2999

SELECT GROUP_NUMBER,

       OPERATION,

       STATE,

       POWER,

       ACTUAL,

       ACTUAL,

       EST_MINUTES

FROM gv$asm_operation;


HOW TO ASM ADD DISK:

ALTER DISKGROUP DATA ADD DISK'/devices/hdisk'; 

ALTER DISKGROUP DATA ADD DISK'/devices/hdisk*' REBALANCE POWER 1024 WAIT;

ALTER DISKGROUP DATA ADD DISK'/devices/hdisk5' NAME DATA5,'/devices/hdisk6' NAME DATA6,'/devices/hdisk7' NAME DATA7,'/devices/hdisk8' NAME DATA8,


Drop disk in Asm diskgroup:

ALTER DISKGROUP data DROP DISK DATA_5;

ALTER DISKGROUP data UNDROP DISKS;

sqlplus '/ as sysasm'

SQL> alter diskgroup Mars_data mount;

Diskgroup altered.


Script to check space Diskgroup :

select distinct (NAME) "DISKGROUP",round(TOTAL_MB/1024) "Total Size in GB",round(FREE_MB/1024) 

"Free Space in GB",round(FREE_MB/TOTAL_MB*100) "Pct Free",round((TOTAL_MB-FREE_MB)/TOTAL_MB*100) "Pct used" from gv$ASM_DISKGROUP where NAME='&DS';


Query to check FRA percentage used:

show parameter db_recovery_file_dest;

col name format a20

clear breaks

clear computes 

select name

,      round(space_limit / 1024 / 1024) size_mb

,      round(space_used  / 1024 / 1024) used_mb

,      decode(nvl(space_used,0),0,0,round((space_used/space_limit) * 100)) pct_used

from v$recovery_file_dest

order by name

/


To find ASM Diskgroup and Disks status:

select GROUP_NUMBER,DISK_NUMBER,MOUNT_STATUS,HEADER_STATUS,MODE_STATUS,STATE,VOTING_FILE,name,path from v$asm_disk;


Query to find out which asm diskgroup occupied much space in database

set verify off

column file_name format a50 word_wrapped

column smallest format 999,990 heading "Smallest|Size|Poss."

column currsize format 999,990 heading "Current|Size"

column savings format 999,990 heading "Poss.|Savings"

break on report

compute sum of savings on report

column value new_val blksize

select value from v$parameter where name = 'db_block_size';

/

select file_name,

ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,

ceil( blocks*&&blksize/1024/1024) currsize,

ceil( blocks*&&blksize/1024/1024) -

ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings

from dba_data_files a,

( select file_id, max(block_id+blocks-1) hwm

from dba_extents

group by file_id ) b

where a.file_id = b.file_id(+) order by savings desc

/


Enjoy the work and do like me if you like this article!!!.

Tuesday, August 1, 2023

Top 108 Database Administrator Interview Questions

 1.What will happened if the database archive log destination is full and what will happened to the application transactions 

2.How do you decommission a oracle database 

3.What is psu, cpu and ru patches difference

4.What are the steps for upgrades from 11g to 12c and 12c to 19c

5.What to do if my query or batch job is taking time 

6.What is database character set what is the difference between al32utf8 and other character set

7.Checklist before installing a oracle database and creating databases

8.How make the expdp and impdp to run faster lets say there is 5tb of db how to make it faster what are the various parameters

9.Yesterday the query is taking 5mins and today its taking 30mins why and what are the steps

10.You have completed patching on dev, test and preprod and now think you were doing patching on production environment and its taking much time so how can you handle this

11.You were doing upgrades from 11g to 19c and you were found invalid objects during upgrade and how can you fix those things

12.Have you done cross platform migrations and migration from on premises to cloud

14.Top things you will be checking in awr report

15.Golden gate exposure

16.What are the parameters to check while creating container database and pluggable database max, how many containers databases we can create

17.What is acfs, cachefusion, shared pool, scan ip, virtual ip, logical standby, physical standby db

18.How many ip's we need to configure for 2node rac

19.Can you please tell the steps to upgrade 2 node rac

20.Steps to apply a patch on dataguard environment and command to start a mrp process

21.what are the high level steps to apply a patch and how can you rollback a patch

22.What if my pfile and spfile is lost and how we start the database and what is the default location of pfile

23.What if control file is lost and how can we recover with rman

24.How the select, update, delete statement  works in oracle database

25.How to recover if redo log member is lost and how to add a redo member to a grop

26.How to recovery if datafile is lost

27.A datafile was wrongly added on file system instead of ASM disk group. How to move it to the ASM disk group again?

28.How to apply a patch on 2node rac with standby database

29.How to configure fast start failover

30.What is ocr, olr, crsd, cssd and voting disk

31.What is cache fusion, cache coherence

32.What is vip, scanip how the nodes communicates each other

33.What is difference between rman and expdp

35.How to resolve block corruption with rman and will it resolve thru expdp

36.What is the role of pga during update statement

37.What is sql profile and db profile and how it works and how can you change the Plug a better plan hash value

38.I have a backup taken at 12.10AM and 12.30AM and how to restore the backup taken at 12.10 only

39.What is normal change and expedite change

40.I have a 4 node rac and if node is evicted then how to resolve it and how to relocate the services from one node to another node command to check the services

41.What is latch and how does it will occur and how to resolve it

42.My application is hanging and how do you trouble shoot it quickly

43.Suddenly the database performance is low after adding a disk to asm

44.What is backup piece

45.How to backup control file with rman

46.What is catalogue command in rman 

47.Can we backup a online redo log file

48.What are the high level patching steps on oracle rac database

49.What is asm_power_limit what is the default value in higher versions

50.What is split brain syndrome

51.What  if my ocr is corrupted and what are the steps and how to take a backup of ocr and voting disk

52.What if one of my voting disk is corrupted out of 5 voting disk

53.One of my table is dropped how to recover that table alone in oracle 12c

54.Junior dba removed oracle home with rm -rf command what will happen to the db can we recover the db

55.Junior dba removed the restore point from my primary database how to recover to the last restore point and is it possible to restore to the last restore point

56.You have upgraded the database from 11g to 12c or 19c after some days the application team wants to restore to the older version

57.How to restore if my compatible parameter is not set or if you have set the compatible parameter then can we restore to older version?

58.How to configure a 4 node rac what are the high level steps

59.How to upgrade the rac database/primary db with standby with lesser downtime

59.Orainventory is corrupted and how to recreate it

60.How to convert from noncdb to cdb 

61.How to convert from nonasm to asm

62.Do you a have any basic knowledge in sqlservers

63.Do you a basic knowledge in goldengate

64.How to covert from physical standby to logical standby and physical to snapshot standby database

65.What Happened to Database, Suddenly Listener Got Down and how can you troubleshoot listener issues

66.What is oracle fine grained auditing and 

67.What will you do if you see the cpu usage is 90 or 100% 

68.What is in-memory, sga and pga and is sga and pga are dynamic parameters and how to increase memory the sga and pga and what prechecks you will do

69.How can you fin dout that there is a shortage of memory in the server and how will you increase it

70.What is crsctl disable/enable crs

71.What are the different types of rman backups available in rman and how to speed up the rman backup

72.What is cumulative and differential and what is full backup and level0 backup

73.What is block change tracking in rman

74.How many ip's do we need to configure for 2 node rac and 5 node rac and which ip's are to be in same subnet

75.What is public, private, scan ip and vip 

76.What is Addm, Ash, and Awr and what are the things you will check in these reports

77.How can you find out if there are any vulnerabilities in oracle database

78.What are the things you will run after db creation how many ways you can create the db

79.What are the v$views, baseviews, dictionary views how to update these views

80.What are ways you can do for oracle database migration, what are the things you will check before migration

81.Which migration method did you used in your earlier project

82.What are the new features in oracle 19c,21c and which feature have you used in your recent project

83.How can you read the dumpfile if the logfile are not there

84.How many redundancy available in asm and what are those by default if we add a disk what is the redundancy

85.What is password file in oracle database

86.What is character set and how many types of character set in oracle

87.What is proactive and reactive tunning 

88.What is pctfree and pctused

89.What are the waitevents in oracle rac and how to resolve it

90.What is haip in oracle rac

91.What if the private connection fails in oracle rac what are the steps to take inorder to avoid it

92.What is dB sequential and dbscaterred wait events and how to resolve

93.What is fragmentation how to resolve it

94.What to do if there heavy bulk inserts and updates on the db level

95.What is automatic and manual memory management

96.What to do if there are heavy sorts in oracle database what need to check at the pga and temporary tablespace level

97.What are hints and name some of the hints that we used

98.How to avoid the swiping and memory issues at the Linux os level

99.How can we run the rman backup job from a particular node in oracle rac, how can we configure the services to run on a particular node in oracle rac

100.What is MGMT database in Oracle 12c?

101.How to log all the dml activity of user on a table

102.If we apply a patch on 12c pdb and cdb will it apply to all or only to cdb

103.What does the AWR DB time represent?

104.I have taken export of A,B,C and D schemas and while importing if i mention remap_schema=A:B and 

what will happen if i don't mention remap_schema=C:D and how it works

105.What is the difference between  data guard and physical standby database

106.What are the mandatory background process for a oracle database, a rac and grid

107.Db is dropped but no space is released from asm disk ?

108.What is the difference between crosscheck, validate, obsolete and expired

                                                       

         



Enjoy the work and do like me if you like this article!!!

Sunday, July 30, 2023

Backup oracle home through tar command

Steps to take oracle home backup through tar command
  0)Dbname1:/u01/app/oracle/product/12.1.0/dbhome
  1)Go to oracle home cd /u01/app/oracle/product/12.1.0/
  2)ls -lrt
  3)run this command tar -czvf     /bkup/datapump/dbname1/dbname1_bkp_node1.tar.gz dbhome
  4)This is my backup location /bkup/datapump/dbname1

This will create a .tar.gz file in /bkup/datapump/dbname1 location

  Steps to take grid home backup through tar command
  0)ASM1:/u01/app/grid/product/12.2.0/grid
  1)Go to oracle home cd /u01/app/grid/product/12.2.0
  2)ls -lrt
  3)run this command tar -czvf     /bkup/datapump/asm1/grid_bkp_node1.tar.gz grid
  4)This is my backup location /bkup/datapump/asm1

This will create a .tar.gz file in /bkup/datapump/asm1 location


Enjoy the work and do like me if you like this article!!!

Wednesday, July 19, 2023

Dba daily weekly monthly tasks

 A Database Administrator (DBA) plays a critical role in managing and maintaining an organization's databases, ensuring their availability, security, and optimal performance. The tasks of a DBA can be categorized into daily, weekly, and monthly responsibilities. Here's an overview of each:

Schedule some of the below jobs for an easy and peaceful Dba job.

1. Schedule a cronjob for every hour to Check the Database Availability. 

2. Schedule a cronjob for every hour to clean the trace files like .trc,.trm,.xml,.aud files.

3. Schedule a cronjob for every hour to check file system alerts

4. Schedule a cronjob for every hour to check free space in tablespaces

5. Schedule a cronjob for every hour to clean the trace files like .trc,.trm,.xml,.aud

6. Schedule a cronjob after business hours to take Rman incremental backup

7. Schedule a cronjob after business hours to gather the specific schema stats

8. Schedule a cronjob to check space on all the mount points

9. Schedule a cronjob on weekends to take full export 

10.Schedule a cronjob on weekend to take rman full backup

11.Schedule a cronjob to gather the dictionary stats, system stats

12.Schedule a cronjob for schema refresh as per the client requirement

13.Schedue a cronjob to check the Goldendale extract, manager,replicat process

14.Configure alerts on your business mail and monitor them

15.Configure OEM if you are managing, supporting multiple Linux, Aix, Solarix and Sql servers 

16.Configure ServiceNow, Jira, Remedy or SolarWinds or any  ticketing tool if you are working on a big MNC client.

1.https://www.servicenow.com/ 2.https://www.bmc.com/it-solutions/remedy-itsm.html# 3.https://www.solarwinds.com/company/contact-us.

Daily Tasks :
1.Check the mails from your team, application teams team
2.Monitor the alert mails
3.Participate in a daily meeting with your team members to discuss the daily issues and weekend tasks and plan accordingly
4.Update the daily issues like P1,P2 call and other issues in a share point
5.Working on Adhoc requirement from application team like Password reset, query long running, Killing session, generating report, creating a 
  table, Updating/Inserting/Deleting a data on table, gathering stats, creating a new user, permission issues etc.
6.Work with OS team for any OS level issues
7.Working on Db pending tasks
8.Maintaining a proper documentation  

Weekly Tasks:
1.Applying patches on databases as per oracle requirement
2.Installing, Creating and configuring new database builds
3.Adding new storage disk to the existing disk groups
4.Participate in a weekly meeting and track it in a share point 

Monthly Tasks:
1.Create a plan for Dr Test on production and standby database 
2.Schema refresh from production to development for application testing  
3.Schema migration from one Linux server to another Linux server 
4.Working on tables defragmentation 
5.Create partitions on big tables
6.Check the database growth and update in share point and discuss with team
7.Working with auditing team

Note: For all the above weekly and monthly task need to get the approval from application team and Centre for advisor board(CAB)

Remember that the specific tasks and frequency may vary depending on the organization's size, the complexity of the database environment, and the nature of the applications relying on the databases. Good organization, attention to detail, and proactive monitoring are essential qualities for a successful DBA to manage these tasks efficiently.


Enjoy the work and do like me if you like this article!!!

Latest Posts

Number of failed login attempts exceeds threshold value

Number of failed login attempts exceeds threshold value alert message comes from OEM. How to check what and which user is causing this? how ...

Popular Posts