Useful DBA Scripts

on 1:52 PM


Check Free/Used space per tablespace :


SELECT /* + RULE */  df.tablespace_name "Tablespace",

       df.bytes / (1024 * 1024) "Size (MB)",
       SUM(fs.bytes) / (1024 * 1024) "Free (MB)",
       Nvl(Round(SUM(fs.bytes) * 100 / df.bytes),1) "% Free",
       Round((df.bytes - SUM(fs.bytes)) * 100 / df.bytes) "% Used"
  FROM dba_free_space fs,
       (SELECT tablespace_name,SUM(bytes) bytes
          FROM dba_data_files
         GROUP BY tablespace_name) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,df.bytes
UNION ALL
SELECT /* + RULE */ df.tablespace_name tspace,
       fs.bytes / (1024 * 1024),
       SUM(df.bytes_free) / (1024 * 1024),
       Nvl(Round((SUM(fs.bytes) - df.bytes_used) * 100 / fs.bytes), 1),
       Round((SUM(fs.bytes) - df.bytes_free) * 100 / fs.bytes)
  FROM dba_temp_files fs,
       (SELECT tablespace_name,bytes_free,bytes_used
          FROM v$temp_space_header
         GROUP BY tablespace_name,bytes_free,bytes_used) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,fs.bytes,df.bytes_free,df.bytes_used
 ORDER BY 4 DESC;

Sample output:


Tablespace                      Size (MB)  Free (MB)     % Free     % Used

------------------------------ ---------- ---------- ---------- -----------------
    UNDOTBS1                               65    17.8125         27         73
     EXAMPLE                               100     22.625         23         75
    USERS                                         5     1.0625         21         79
    TEMP                                         20          2             10         90
   SYSAUX                               625.125     304.5        48      52
   SYSTEM                                  700     9.0625          1         99

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


NLS_LANG parameter :


select DECODE(parameter, 'NLS_CHARACTERSET', 'CHARACTER SET',
'NLS_LANGUAGE', 'LANGUAGE',
'NLS_TERRITORY', 'TERRITORY') name,
value from v$nls_parameters
WHERE parameter IN ( 'NLS_CHARACTERSET', 'NLS_LANGUAGE', 'NLS_TERRITORY');



NAME VALUE
————- —————–
LANGUAGE AMERICAN
TERRITORY AMERICA
CHARACTER SET WE8ISO8859P1

export NLS_LANG=_.

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


Object Count , Object Type for one particular User :



select owner,object_type,count(*) from dba_objects where owner='XXXXXXX' group by owner,object_type;



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

Find running jobs in oracle database :




select sid, job,instance from dba_jobs_running;


‎select sid, serial#,machine, status, osuser,username from v$session where username!='NULL'; --all active users;


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


Find long running jobs in oracle database :


select username,to_char(start_time, 'hh24:mi:ss dd/mm/yy') started, time_remaining remaining, message from v$session_longops where time_remaining = 0 order by time_remaining desc;

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

Find the Size of Schema:


SELECT SUM (bytes / 1024 / 1024) "size"
FROM dba_segments WHERE owner = '&owner';


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



How to shift a table from one tablespace to another.


ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>;


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



Query to catch and generate script to kill the blocking sessions


select 'alter system kill session '''||sid||','||serial#||''';' from v$session where sid in (select * from dba_blockers); 



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


Find the last DDL on Particular Object 


SELECT object_name, object_type, last_ddl_time

FROM dba_objects 
WHERE 
object_name = 'xxxxxxxxxxx';



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


Sessions :



To find total session on particular server ( machine )


select * from gv$session where MACHINE like '%XXXXX%' ;


To find session which are Active


select * from gv$session where MACHINE like '%XXXXX%' AND status='ACTIVE';


ACTIVE - Session currently executing SQL


To find users machines by order 


select machine, count(*) from gv$session group by machine order by 2;


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


To find uptime of instnace


SELECT host_name, instance_name,

       TO_CHAR(startup_time, 'DD-MM-YYYY HH24:MI:SS') startup_time,FLOOR(sysdate-startup_time) days

FROM   v_$instance;


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



SYS.USER$ is an Internal table in Oracle Database


PTIME provides the date the password was last changed.

LCOUNT provides the number of failed logins.
CTIME provides the date the user was created.
LTIME provides the date the user was last locked.

SELECT name " USER NAME ",

ctime " Date user was created ",
ptime " Password was last changed " 
FROM sys.user$
WHERE name = 'XXXX';

** List of all database users and the date when the last password change occurred


select du.username, du.profile, du.account_status, u.ptime last_pwd_change

from dba_users du, sys.user$ u
where du.username = u.name

order by 2, 4;

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



Find unusable indexes:-



SELECT owner, index_name, tablespace_name

FROM   dba_indexes

WHERE  status = 'UNUSABLE';



Index partitions:



SELECT index_owner, index_name, partition_name, tablespace_name
FROM   dba_ind_PARTITIONS
WHERE  status = 'UNUSABLE';

Rebuild unusable indexes 

Indexes:

SELECT 'alter index '||owner||'.'||index_name||' rebuild tablespace '||tablespace_name ||';'
 FROM   dba_indexes WHERE  status = 'UNUSABLE';

Index partitions:

SELECT 'alter index '||owner||'.'||index_name ||' rebuild partition '||PARTITION_NAME||' TABLESPACE '||tablespace_name ||';'
FROM   dba_ind_partitions
WHERE  status = 'UNUSABLE';

Now verify the status of the index, it will be VALID



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


How to Check the installed Oracle Software is 32/64 bit ?


select length(addr)*4 || '-bits' word_length from v$process where rownum=1;

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


IDLE SESSIONS FOR MORE THAN 1 HOUR


select sid,serial#,username,trunc
(last_call_et/3600,2)||' hr'
last_call_et
from V$session where
last_call_et > 3600 and username is not null;

How to Change the Administrator Password in Windows Server 2003, 2008 R2, or 2012

on 1:37 PM

Change your Server Administrator Password in Windows Server 2012 :

1.    Log into your server via Remote Desktop.
2.    Press your Windows key and type Administrative Tools.
3.    Double click on Computer Management.
4.    Expand Local Users and Groups.
5.    Click on Users. 
6.    Right click on Administrator , Click on Set Password > Proceed. 
7.    Type your new password in both fields then press OK.

Change your Sever Administrator Password in Windows Server 2008 R2 :

1.    Log into your server via Remote Desktop.
2.    Right click on Computer  and select Manage.
3.    Double click Configuration.
4.    Expand Local Users and Groups and then select Users.
5.    Right click on Administrator and choose Set Password and then click Proceed.
6.    Type in the new password and select OK.

Change your Sever Administrator Password in Windows Server 2003 :

1.    Log into your server via Remote Desktop.
2.    Right click on My Computer  and select Manage.
3.    Expand Local Users and Groups and then select Users.
4.    Right click on Administrator and choose Set Password and then click Proceed.
5.    Type in the new password and select OK.


Trace IP address / machine of user logging in database with wrong password

on 3:19 AM

Enable audit in database with parameter AUDIT_TRAIL
SQL> show parameter audit_trail;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
audit_trail                          string      DB_EXTENDED
 Enable session auditing
SQL> audit session;

Audit succeeded.
 Check DBA_AUDIT_TRAIL view:
SQL> select os_username, userhost, username, action_name, timestamp, returncode
  2  from dba_audit_trail
  3  where returncode=1017;

OS_USERNAME
--------------------------------------------------------------------------------
USERHOST
--------------------------------------------------------------------------------
USERNAME                       ACTION_NAME                  TIMESTAMP RETURNCODE
------------------------------ ---------------------------- --------- ----------
pierre
WORKGROUP\PC-de-pierre
HR                             LOGON                        22-FEB-11       1017
1017 stands for ORA-1017 Oracle error:
oerr ora 1017
01017, 00000, "invalid username/password; logon denied"
// *Cause:
// *Action:
OS_USERNAME is OS account name of user that is trying to connect to Oracle
USERHOST is the machine name where executable has tried to connect.

Connect to the Oracle database via JDBC

on 1:49 PM

For connecting Java application with the Oracle Database :

Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
Connection URL: The connection URL for the oracle10G database is 

jdbc:oracle:thin:@localhost:1521:xe 


 jdbc : API, 

oracle : database, 
thin : driver, 
localhost : is the server name on which oracle is running, we may also use IP address, 
1521 : is the port number 
XE : is the Oracle service name. 

You may get all these informations from the tnsnames.ora file.


Username: The default username for the oracle database is system.

Password: Password is given by the user at the time of installing the oracle database.


In this example, system is the username and oracle is the password of the Oracle database.
  1. import java.sql.*;  
  2. class OracleCon{  
  3. public static void main(String args[]){  
  4. try{  
  5. //step1 load the driver class  
  6. Class.forName("oracle.jdbc.driver.OracleDriver");  
  7.   
  8. //step2 create  the connection object  
  9. Connection con=DriverManager.getConnection(  
  10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  11.   
  12. //step3 create the statement object  
  13. Statement stmt=con.createStatement();  
  14.   
  15. //step4 execute query  
  16. ResultSet rs=stmt.executeQuery("select * from emp");  
  17. while(rs.next())  
  18. System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
  19.   
  20. //step5 close the connection object  
  21. con.close();  
  22.   
  23. }catch(Exception e){ System.out.println(e);}  
  24.   
  25. }  
  26. }  

Difference between DDL, DML and DCL commands

on 11:40 PM


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use


Environment Variable for Oracle Database

on 12:28 AM

How to check if ORACLE_HOME is set already?


To check specific environment variable set:
$ echo $ORACLE_HOME

To check all the environment variables set:

$ env

On Windows Systems:

To check specific environment variable set:


C:\> set ORACLE_HOME

OR

C:\echo %ORACLE_HOME%

To check all the environment variables set:

C:\> set

Or

C:\> env

Other way, to check the ORACLE_HOME, is as follows.
Start -> Run -> Regedit (enter) -> HKEY_LOCAL_MACHINE -> SOFTWARE –> ORACLE

i.e. My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE

How to check using sqlplus command:
To find the ORACLE_HOME path in Oracle Database

How to set the ORACLE_HOME environment variable?
On Unix/Linux Systems:

Define the ORACLE_HOME value in the user profile file i.e. .bash_profile or .profile

ORACLE_HOME=$ORACLE_BASE/product/10.2.0
export ORACLE_HOME

On Windows Systems:

My Computer -> Properties -> Advanced -> Environment Variables -> System Variables -> New/Edit/Delete (to set the variables)

After setting the environment variables as above, open a fresh CMD tool and check whether they set properly or not. Do not try on already opened CMD tool to make sure the variables set or not.

Another way to physically set the variables as follow at the DOS prompt:

C:\> set ORACLE_HOME=C:\oracle\app\product\10.2.0
C:\> echo %ORACLE_HOME%

Linux 


export ORACLE_SID=COREDB

export ORACLE_HOME=/u01/home/app/product/11.2.0/dbhome_1
export PATH=$ORACLE_HOME/bin:$PATH:

Tablespace in Oracle

on 12:23 AM

A Tablespace is a container for segments (tables, indexes, etc). A database consists of one or more tablespaces, each made up of one or more data files. Tables and indexes are created within a particular tablespace.

When a New database is created, it will have the following tablespaces :


SYSTEM (the data dictionary)

SYSAUX (optional database components)
TEMP (temporary tablespace)
UNDOTBS1 (undo tablespace, contains pre image data)
USERS (default users tablespace created)

Syntax :


Create tablespace

Datafile '/u01/home/prd/cmm.dbf' size 100m 
autoextend on 
next 100m maxsize unlimited;

Check Free/Used space per tablespace :


SELECT /* + RULE */  df.tablespace_name "Tablespace",

       df.bytes / (1024 * 1024) "Size (MB)",
       SUM(fs.bytes) / (1024 * 1024) "Free (MB)",
       Nvl(Round(SUM(fs.bytes) * 100 / df.bytes),1) "% Free",
       Round((df.bytes - SUM(fs.bytes)) * 100 / df.bytes) "% Used"
  FROM dba_free_space fs,
       (SELECT tablespace_name,SUM(bytes) bytes
          FROM dba_data_files
         GROUP BY tablespace_name) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,df.bytes
UNION ALL
SELECT /* + RULE */ df.tablespace_name tspace,
       fs.bytes / (1024 * 1024),
       SUM(df.bytes_free) / (1024 * 1024),
       Nvl(Round((SUM(fs.bytes) - df.bytes_used) * 100 / fs.bytes), 1),
       Round((SUM(fs.bytes) - df.bytes_free) * 100 / fs.bytes)
  FROM dba_temp_files fs,
       (SELECT tablespace_name,bytes_free,bytes_used
          FROM v$temp_space_header
         GROUP BY tablespace_name,bytes_free,bytes_used) df
 WHERE fs.tablespace_name (+)  = df.tablespace_name
 GROUP BY df.tablespace_name,fs.bytes,df.bytes_free,df.bytes_used
 ORDER BY 4 DESC;

Sample output:


Tablespace                      Size (MB)  Free (MB)     % Free     % Used
------------------------------ ---------- ---------- ---------- -----------------
    UNDOTBS1                               65    17.8125         27         73
     EXAMPLE                               100     22.625         23         75
    USERS                                         5     1.0625         21         79
    TEMP                                         20          2             10         90
   SYSAUX                               625.125     304.5        48      52
   SYSTEM                                  700     9.0625          1         99

Oracle Data Pump (expdp and impdp) in Oracle Database 11g

on 5:09 PM

Oracle Data Pump is a newer, faster and more flexible alternative to the "exp" and "imp" utilities used in previous Oracle versions. In addition to basic import and export functionality data pump provides a PL/SQL API and support for external tables.

Table Exports/Imports
expdp system@databasename tables=EMP,DEPT directory=TEST_DIR dumpfile=EMP_DEPT.dmp logfile=expdpEMP_DEPT.log

impdp system@databasename tables=EMP,DEPT directory=TEST_DIR dumpfile=EMP_DEPT.dmp logfile=impdpEMP_DEPT.log
Schema Exports/Imports

expdp system@databasename schemas=SCOTT directory=TEST_DIR dumpfile=SCOTT.dmp logfile=expdpSCOTT.log

impdp system@databasename schemas=SCOTT directory=TEST_DIR dumpfile=SCOTT.dmp logfile=impdpSCOTT.log


Database Exports/Imports

expdp system@databasename full=Y directory=TEST_DIR dumpfile=DB11G.dmp logfile=expdpDB11G.log

impdp system@databasename
  full=Y directory=TEST_DIR dumpfile=DB11G.dmp logfile=impdpDB11G.log

To Create a Logical Directory : 


CREATE DIRECTORY datapump AS 'C:\oradata\datapump';

GRANT EXP_FULL_DATABASE  to scott;

GRANT READ, WRITE ON DIRECTORY datapump to scott;