Showing posts with label administration. Show all posts
Showing posts with label administration. Show all posts

Monday, August 19, 2024

Identify and Terminate Sessions in oracle

 

First, you have to identify the session to be killed with alter system kill session.

Step-by-Step Instructions to Identify and Terminate a Session:


Invoke SQL*Plus:

First, open SQL*Plus to begin the process.

Query V$SESSION to Identify the Session:

Use the following query to retrieve the session details. This will list all active sessions with their respective SID, SERIAL#, STATUS, SCHEMANAME, and PROGRAM.


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session;

The SID (Session Identifier) and SERIAL# values of the Oracle session to be killed can then be identified from this output.


Execute the ALTER SYSTEM Command:

Substitute the identified SID and SERIAL# values and issue the alter system kill session command.


ALTER SYSTEM KILL SESSION 'sid,serial#';

Handling Sessions Marked for Kill:

Sometimes, Oracle is not able to kill the session immediately with the alter system kill session command alone. Upon issuing the command, the session may be 'marked for kill' and will be terminated as soon as possible.


Forcing Session Termination:

In the case where a session is 'marked for kill' and not terminated immediately, you can force the termination by adding the immediate keyword:


ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

Verify Termination:

To ensure that the session has been terminated, re-query the V$SESSION dynamic performance view:


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session WHERE SID = 'sid' AND SERIAL# = 'serial#';

The value of the STATUS column will be 'ACTIVE' when the session is making a SQL call and 'INACTIVE' if it is not.


Confirm PMON Cleanup:

After the Process Monitor (PMON) has cleaned up the session, the row will be removed from V$SESSION. Re-query to confirm:


SELECT SID, SERIAL#, STATUS, SCHEMANAME, PROGRAM FROM v$session WHERE SID = 'sid' AND SERIAL# = 'serial#';

Handling RAC Environments:

In a Real Application Clusters (RAC) environment, you can optionally specify the INST_ID, which is shown when querying the GV$SESSION view. This allows you to kill a session on a different RAC node.


ALTER SYSTEM KILL SESSION 'sid,serial#,@inst_id';

By following these detailed steps, you can efficiently identify and terminate a session using SQL*Plus, ensuring minimal disruption and maintaining database integrity.

Thursday, February 8, 2024

Optimizing Storage and Performance with Oracle Database Advanced Compression

 Optimizing Storage and Performance with Oracle Database Advanced Compression

In the world of database management, the challenge of balancing performance with storage efficiency is ever-present. Oracle's Advanced Compression feature offers a robust solution to this by reducing storage footprint, optimizing performance, and saving costs — all without compromising data integrity. In this post, we’ll dive into how you can leverage advanced compression in Oracle, with practical examples and straightforward code snippets.

  Why Use Advanced Compression in Oracle?

Advanced Compression isn't just about saving storage; it enhances data retrieval speed by minimizing the amount of data that needs to be read from disk. This is especially beneficial for larger tables or indices that experience heavy I/O operations. Advanced Compression works across various Oracle database objects and data types, from tables and indexes to LOBs and backups.

  Types of Compression in Oracle Database

Oracle provides several types of compression suited to various workloads:

1. Basic Table Compression: Suitable for read-only or static tables, it compresses data as it's loaded.
2. OLTP Table Compression: Designed for transactional environments, it works dynamically on data inserts and updates.
3. Hybrid Columnar Compression (HCC): Available only on Exadata and a few other Oracle storage solutions, it’s ideal for data warehouses and archival tables.
4. Index Compression: Reduces the storage for indexes by compressing repeated values.

Let’s walk through these options with examples using a hypothetical table and index.

  1. Basic Table Compression

To start, let’s look at Basic Table Compression, commonly used for data warehousing or infrequently updated tables.

Suppose we have a table `Employee_Records` that stores historical data and is rarely modified:

 SQL :
CREATE TABLE Employee_Records (
    employee_id NUMBER,
    first_name VARCHAR2(50),
    last_name VARCHAR2(50),
    department_id NUMBER,
    hire_date DATE
) COMPRESS BASIC;
 

Here, we specify `COMPRESS BASIC`, which instructs Oracle to compress the data during bulk insert operations. Keep in mind that this is ideal for tables where data modifications are infrequent, as Basic Compression doesn’t automatically recompress on updates.

  2. OLTP Table Compression

For transactional tables with frequent updates, OLTP Table Compression is more appropriate. Oracle's advanced algorithm ensures that as rows are inserted or updated, the data remains compressed without additional manual intervention.

Let’s use `Order_Details`, a table holding real-time sales data:

 SQL :
CREATE TABLE Order_Details (
    order_id NUMBER,
    product_id NUMBER,
    quantity NUMBER,
    order_date DATE,
    customer_id NUMBER
) COMPRESS FOR OLTP;
 

With `COMPRESS FOR OLTP`, this table will dynamically compress data during both inserts and updates, keeping storage usage low while maintaining fast performance.

Tip: OLTP compression is a powerful way to balance performance and space in high-transaction environments. However, it requires some CPU overhead, so monitor performance in CPU-bound systems.

  3. Hybrid Columnar Compression (HCC)

HCC is an exclusive feature for Exadata, ZFS, and Oracle Cloud customers. It combines row and column storage, making it highly efficient for queries that scan large datasets. HCC can offer multiple levels, like `COMPRESS FOR QUERY` and `COMPRESS FOR ARCHIVE`, allowing you to optimize for retrieval speed or maximum storage savings.

Using `Sales_Archive` as an example table:

 SQL :
CREATE TABLE Sales_Archive (
    sale_id NUMBER,
    region VARCHAR2(30),
    sale_amount NUMBER,
    sale_date DATE
) COMPRESS FOR QUERY HIGH;
 

In this case, `COMPRESS FOR QUERY HIGH` balances both storage efficiency and query performance, ideal for analytic queries on historical data. For long-term storage where frequent access isn’t necessary, consider `COMPRESS FOR ARCHIVE HIGH`.

  4. Index Compression

Finally, Index Compression can be particularly beneficial for large indexes with repeating values. By compressing the key prefix, Oracle significantly reduces index size, speeding up queries.

Imagine we have a commonly queried index on the `Employee_Records` table:

 SQL :
CREATE INDEX idx_employee_department 
ON Employee_Records (department_id, last_name, first_name) COMPRESS 1;
 

In this example, `COMPRESS 1` compresses the leading column (`department_id`) in the index. If more columns contain duplicate values, you can increase the compression level. Index compression works well in cases where there’s repetition, such as departmental groupings, making it a great fit for HR or CRM databases.

  Monitoring and Verifying Compression Benefits

To see the benefits of compression, you can query Oracle's data dictionary to monitor the space savings:

 SQL :
SELECT segment_name, 
       segment_type, 
       bytes / 1024 / 1024 AS size_MB 
FROM   dba_segments 
WHERE  segment_name = 'EMPLOYEE_RECORDS';
 

By running this query before and after enabling compression, you can quantify the storage savings directly.

  Considerations and Best Practices

1. Testing: Test compression in a non-production environment to assess CPU overhead and performance impact.
2. Monitoring: Regularly monitor space and CPU metrics to ensure that compression is meeting your goals without overtaxing system resources.
3. Reorganizing Tables: Consider periodically reorganizing heavily updated tables with OLTP compression to maintain optimal storage savings.

  Conclusion

Oracle's Advanced Compression provides a flexible toolkit for database administrators looking to optimize both storage and performance. By selecting the right type of compression for each workload, you can achieve substantial space savings while maintaining fast access times. Try implementing compression gradually, starting with non-critical tables, and measure the impact to find the best fit for your database environment.

Thursday, December 15, 2016

java.lang.SecurityException: The jurisdiction policy files are not signed by a trusted signer



I was trying to Install OID (Oracle Identity Manager) and I got this error :

Problem:




        at oracle.as.install.engine.modules.configuration.standard.StandardConfigActionManager.start(StandardConfigActionManager.java:186)
        at oracle.as.install.engine.modules.configuration.boot.ConfigurationExtension.kickstart(ConfigurationExtension.java:81)
        at oracle.as.install.engine.modules.configuration.ConfigurationModule.run(ConfigurationModule.java:86)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.SecurityException: Can not initialize cryptographic mechanism
        at javax.crypto.JceSecurity.<clinit>(JceSecurity.java:88)
        ... 31 more
Caused by: java.lang.SecurityException: The jurisdiction policy files are not signed by a trusted signer!
        at javax.crypto.JarVerifier.verifyPolicySigned(JarVerifier.java:328)
        at javax.crypto.JceSecurity.loadPolicies(JceSecurity.java:317)
        at javax.crypto.JceSecurity.setupJurisdictionPolicies(JceSecurity.java:262)
        at javax.crypto.JceSecurity.access$000(JceSecurity.java:48)
        at javax.crypto.JceSecurity$1.run(JceSecurity.java:80)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.crypto.JceSecurity.<clinit>(JceSecurity.java:77)



Cause:

My current version of java was 1.8.* which is not fully supported.
In this case JDK 1.8.0.1 is installed on all nodes in the cluster and JCE local policy version 6 was used for AES 256 kerberos encryption. JCE must be in sync with the JDK version.
      
[oracle@linux06 jdk1.8.0_111]$ cd ..
[oracle@linux06 java]$ ls
default  jdk1.8.0_111  latest
[oracle@linux06 java]$ cd default/
[oracle@linux06 default]$ ls
bin        javafx-src.zip  man          THIRDPARTYLICENSEREADME-JAVAFX.txt
COPYRIGHT  jre             README.html  THIRDPARTYLICENSEREADME.txt
db         lib             release
include    LICENSE         src.zip


Solution:

Download :

For Java 6 use :
http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

For Java 7 use :
http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

For java 8 use :
http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html        

********************    ********************    ********************
Update java with with new java unlimted jusrisdiction :
********************    ********************    ********************

After download and unzip :

[oracle@linux06 JCE]$ unzip jce_policy-8.zip
Archive:  jce_policy-8.zip
   creating: UnlimitedJCEPolicyJDK8/
  inflating: UnlimitedJCEPolicyJDK8/local_policy.jar
  inflating: UnlimitedJCEPolicyJDK8/README.txt
  inflating: UnlimitedJCEPolicyJDK8/US_export_policy.jar
[oracle@linux06 JCE]$ ls -ll
total 16
-rw-rw-r--. 1 oracle oracle 8409 Dec 14 10:39 jce_policy-8.zip
drwxrwxr-x. 2 oracle oracle 4096 Dec 20  2013 UnlimitedJCEPolicyJDK8
[oracle@linux06 JCE]$ pwd
/u01/app/SFTW/JCE
[oracle@linux06 JCE]$ ls
jce_policy-8.zip  UnlimitedJCEPolicyJDK8
[oracle@linux06 JCE]$ cd UnlimitedJCEPolicyJDK8/
[oracle@linux06 UnlimitedJCEPolicyJDK8]$ ls
local_policy.jar  README.txt  US_export_policy.jar

********************    ********************    ********************
as root user backup and replace files (US_export_policy & local_policy.jar)
********************    ********************    ********************

[oracle@linux06 security]$ su root
Password:
[root@linux06 security]# ls
blacklist          java.policy    local_policy.jar
blacklisted.certs  java.security  trusted.libraries
cacerts            javaws.policy  US_export_policy.jar
[root@linux06 security]# cd /usr/java/default/jre/lib/security
[root@linux06 security]# mv US_export_policy.jar US_export_policy.jar_bak
[root@linux06 security]# mv local_policy.jar local_policy.jar_bak
[root@linux06 security]# ls -ll
total 164
-rw-r--r--. 1 root root   4054 Sep 22 18:23 blacklist
-rw-r--r--. 1 root root   1273 Sep 22 18:23 blacklisted.certs
-rw-r--r--. 1 root root 112860 Sep 22 18:23 cacerts
-rw-r--r--. 1 root root   2466 Sep 22 18:23 java.policy
-rw-r--r--. 1 root root  27358 Sep 22 18:23 java.security
-rw-r--r--. 1 root root     98 Sep 22 18:23 javaws.policy
-rw-r--r--. 1 root root   3405 Sep 22 18:35 local_policy.jar_bak
-rw-r--r--. 1 root root      0 Sep 22 18:23 trusted.libraries
-rw-r--r--. 1 root root   2920 Sep 22 18:35 US_export_policy.jar_bak
[root@linux06 security]# pwd
/usr/java/default/jre/lib/security
[root@linux06 security]# cp /u01/app/SFTW/JCE/UnlimitedJCEPolicyJDK8/US_export_policy.jar /usr/java/default/jre/lib/security
[root@linux06 security]# cp /u01/app/SFTW/JCE/UnlimitedJCEPolicyJDK8/local_policy.jar /usr/java/default/jre/lib/security
[root@linux06 security]# ls -ll
total 172
-rw-r--r--. 1 root root   4054 Sep 22 18:23 blacklist
-rw-r--r--. 1 root root   1273 Sep 22 18:23 blacklisted.certs
-rw-r--r--. 1 root root 112860 Sep 22 18:23 cacerts
-rw-r--r--. 1 root root   2466 Sep 22 18:23 java.policy
-rw-r--r--. 1 root root  27358 Sep 22 18:23 java.security
-rw-r--r--. 1 root root     98 Sep 22 18:23 javaws.policy
-rw-r--r--. 1 root root   3035 Dec 14 10:47 local_policy.jar
-rw-r--r--. 1 root root   3405 Sep 22 18:35 local_policy.jar_bak
-rw-r--r--. 1 root root      0 Sep 22 18:23 trusted.libraries
-rw-r--r--. 1 root root   3023 Dec 14 10:46 US_export_policy.jar
-rw-r--r--. 1 root root   2920 Sep 22 18:35 US_export_policy.jar_bak

Monday, November 14, 2016

Is it safe to move/recreate alertlog while the database is up and running



 Is it safe to move/recreate alertlog while the database is up and running??


It is totally safe to "mv" or rename it while we are running. Since chopping part of it out would be lengthly process, there is a good chance we would write to it while you are editing it so I would not advise trying to "chop" part off -- just mv the whole thing and we'll start anew in another file.

If you want to keep the last N lines "online", after you mv the file, tail the last 100 lines to "alert_also.log" or something before you archive off the rest.



[oracle@Linux03 trace]$ ls -ll alert_*
-rw-r-----. 1 oracle oracle   
488012 Nov 14 10:23 alert_orcl.log

I will rename the existing alertlog file to something
 
[oracle@Linux03 trace]$ mv alert_orcl.log alert_orcl_Pre_14Nov2016.log

[oracle@Linux03 trace]$ ls -ll alert_*
-rw-r-----. 1 oracle oracle 488012 Nov 14 15:42 alert_orcl_Pre_14Nov2016.log
[oracle@Linux03 trace]$ ls -ll alert_*


Now let's create some activity that will need to update the alertlog.

[oracle@Linux03 bin]$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.2.0 Production on Mon Nov 14 16:23:02 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> alter system switch logfile;

System altered.

SQL> /

lets see if the new alertlog file has been created.

[oracle@Linux03 trace]$ ls -ll alert_*
-rw-r-----. 1 oracle oracle    249 Nov 14 16:23 alert_orcl.log
-rw-r-----. 1 oracle oracle 488012 Nov 14 15:42 alert_orcl_Pre_14Nov2016.log

Tuesday, October 11, 2016

expdp content=data_only

[oracle@oracle1 dpump]$ expdp atest/password directory=dpump dumpfile=test_tab1.dmp content=data_only tables=test_tab1 logfile=test_tab1.log

Export: Release 11.2.0.1.0 - Production on Wed Feb 11 10:58:23 2015

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

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
Starting "ATEST"."SYS_EXPORT_TABLE_01":  atest/******** directory=dpump dumpfile=test_tab1.dmp content=data_only tables=test_tab1 logfile=test_tab1.log
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
. . exported "ATEST"."TEST_TAB1"                         5.937 KB      11 rows
Master table "ATEST"."SYS_EXPORT_TABLE_01" successfully loaded/unloaded
******************************************************************************
Dump file set for ATEST.SYS_EXPORT_TABLE_01 is:
  /u01/app/oracle/dpump/test_tab1.dmp
Job "ATEST"."SYS_EXPORT_TABLE_01" successfully completed at 10:58:26

[oracle@oracle1 dpump]$ clear
[oracle@oracle1 dpump]$ impdp atest2/password directory=dpump dumpfile=test_tab1.dmp content=data_only logfile=test_tab1_imp.log TABLE_EXISTS_ACTION=truncate remap_schema=atest:atest2

Import: Release 11.2.0.1.0 - Production on Wed Feb 11 10:58:50 2015

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

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
Master table "ATEST2"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
Starting "ATEST2"."SYS_IMPORT_FULL_01":  atest2/******** directory=dpump dumpfile=test_tab1.dmp content=data_only logfile=test_tab1_imp.log TABLE_EXISTS_ACTION=truncate remap_schema=atest:atest2
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
. . imported "ATEST2"."TEST_TAB1"                        5.937 KB      11 rows
Job "ATEST2"."SYS_IMPORT_FULL_01" successfully completed at 10:58:52

Thursday, September 29, 2016

ALTER SYSTEM KILL SESSION


Note : Killing sessions can be very destructive if you kill the wrong session, so be very careful when identifying the session to be killed.
 
There could be a number of reasons to kill non-essential Oracle user processes. In Oracle the alter system kill session command allows us to kill these Oracle sessions. 

The alter system kill session command requires two unique arguments that uniquely identify the Oracle session, the session identifier and serial number.

First you have to identify the session to be killed with alter system kill session.

select SID,SERIAL#,STATUS,SCHEMANAME,PROGRAM from v$session;


The SID and SERIAL# values of the Oracle session to be killed can then be substituted and the alter system kill session command issued.

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#';


Sometimes Oracle is not able to kill the session immediately with the alter system kill session  command alone. Upon issuing the alter system kill session  command, the session will be 'marked for kill'. It will then be killed as soon as possible.


In the case of a session being 'marked for kill' after issuing the alter system kill session  command and not killed immediately, the alter system kill session  command can be forced by adding the immediate keyword:

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE; 


In a RAC environment, you optionally specify the INST_ID, shown when querying the GV$SESSION view. This allows you to kill a session on different RAC node.

SQL> ALTER SYSTEM KILL SESSION 'sid,serial#,@inst_id';


References :


Automate Kill SNIPED SESSION Oracle Database


If you have configured IDLE_TIME inr your user profile.

IDLE_TIME 

Specify the permitted periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit

Lets say a session has been idle for 10 Minutes. Session will continue to show as idle even after the idle_time for that user,as specified in that user's profile, has expired. When the user attempts to run a transaction against the database after the idle_time has expired, the database will disconnect the user by terminating the session. After this, the
session will no longer show in v$session. So, even if the session appears to be idle for a duration slightly more then your 10 minutes -- it is already "dead", it just doesn't show as dead yet. PMON will eventually snipe the session, marking it dead in v$session.

Reference this oracle Document for more information.

Once the oracle session is changed to SNIPED status, we can kill that session without any problem. How ever this be done manually, but watching for these SNIPED sessions every time can be irritating, we can automate the job of killing SNIPED session as below.


-- This is an optional table. Create this only if you want to Audit the killed session.

CREATE
  TABLE "AUDIT_KILL_SNIPED_SESSIONS"
  (
    "SID"        NUMBER,
    "SERIAL#"    NUMBER,
    "TIME_STAMP" TIMESTAMP (6) DEFAULT SYSTIMESTAMP,
    "USERNAME"   VARCHAR2(50 BYTE)
  )TABLESPACE "USERS" ;


Note :     Inorder to create below procedure you will need DBA role & "ALTER SYSTEM" grant. If you are creating this procedure in non DBA user, you will need grant select on V$SESSION & "ALTER SYSTEM" grant


-- Procedure to kill sessions that are in sniped state

create or replace Procedure KILL_SNIPED_SESSIONS as
cursor SEL_SID is select SID,SERIAL#,USERNAME from v$session where status='SNIPED';
SEL_REC SEL_SID%ROWTYPE;
V_SQL varchar2(100);
V_SQL1 varchar2(100);

Begin
OPEN SEL_SID;
LOOP
FETCH SEL_SID INTO SEL_REC;
EXIT WHEN SEL_SID%NOTFOUND;

V_SQL :='ALTER SYSTEM KILL SESSION '''||SEL_REC.SID||','||SEL_REC.SERIAL#||''' IMMEDIATE';
-- DBMS_OUTPUT.PUT_LINE(V_SQL);
execute immediate V_SQL;
--- LETS AUDIT THE KILLED SESSIONS DATA HERE
-- COMMENT LINES BELOW THIS TO REMOVE AUDITING


V_SQL1:= 'insert INTO AUDIT_KILL_SNIPED_SESSIONS (SID,SERIAL#,USERNAME) VALUES ('''||SEL_REC.SID||''','''||SEL_REC.SERIAL#||''','''||SEL_REC.USERNAME||''')';
-- DBMS_OUTPUT.PUT_LINE(V_SQL1);
COMMIT;
execute immediate V_SQL1;

-- COMMENT UNTILL THIS LINE TO REMOVE AUDITING

END LOOP;
CLOSE SEL_SID;

END;


-- YOU CAN ALSO SETUP A JOB TO RUN EVERY 30 MINS OR HOUR TO EXECUTE THIS PROCEDURE

BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
            job_name => '"EXEC_KILL_SNIPED_SESSIONS"',
            job_type => 'STORED_PROCEDURE',
            job_action => 'KILL_SNIPED_SESSIONS',
            number_of_arguments => 0,
            start_date => TO_TIMESTAMP_TZ('2016-09-29 13:07:38.837143000 AMERICA/CHICAGO','YYYY-MM-DD HH24:MI:SS.FF TZR'),
            repeat_interval => 'FREQ=HOURLY',
            end_date => NULL,
            enabled => FALSE,
            auto_drop => FALSE,
            comments => 'Job to run KILL_SNIPED_SESSIONS procedure that kills SNIPED SESSIONOS ');

       
    DBMS_SCHEDULER.SET_ATTRIBUTE(
             name => '"EXEC_KILL_SNIPED_SESSIONS"',
             attribute => 'logging_level', value => DBMS_SCHEDULER.LOGGING_OFF);
     
 
   
    DBMS_SCHEDULER.enable(
             name => '"EXEC_KILL_SNIPED_SESSIONS"');
END;


References :

http://arvindasdba.blogspot.com/2016/09/alter-system-kill-session.html

Thursday, July 21, 2016

Using special characters in ORACLE DB passwords


Using special characters in ORACLE DB passwords

 
Using special characters in ORACLE DB passwords. Most times we restrict our selves from using complicated special characters as we think that we can't use them in passwords, but in oracle DB world we are allowed to use most special characters as passwords. See this simple example to see how to use special char's in passwords and login.




To log into DB using cmdline we need to use single quote ''. else oracle some times doesn't recognize the password. See below example :

I created a user with password using special characters.

SQL> alter user C##atest identified by "atest113..";

User C##ATEST altered.

[oracle@Linux03 admin]$ sqlplus C##atest/atest113..

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jul 20 16:39:56 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

ERROR:
ORA-01017: invalid username/password; logon denied


Solution to this is to use single quote:

[oracle@Linux03 admin]$ sqlplus C##atest/"atest113$$"

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jul 20 16:41:44 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

ERROR:
ORA-01017: invalid username/password; logon denied


Enter user-name: ^C

press ctrl+c to escape from this line


[oracle@Linux03 admin]$ sqlplus C##atest/'atest113$$&&'

SQL*Plus: Release 12.1.0.2.0 Production on Wed Jul 20 16:43:20 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Last Successful login time: Wed Jul 20 2016 16:42:54 -05:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> show user
USER is "C##ATEST"

SQL> exit
Disconnected from Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
[oracle@Linux03 admin]$ sqlplus C##atest/atest113$$&&

Wednesday, July 20, 2016

configure complex password (password verify function) in oracle database


 configure password verify function in oracle database


We can enable the oracle provided "password verify function" to enforce strong password restrictions for our DB users. This function with other profile parameters can create a strong security for the database.To enable the oracle password verification function you need to execute the utlpwdmg.sql file from ORACLE_HOME/rdbms/admin as sysdba.


[oracle@Linux03 home]$ cd /u01/app/oracle/product/12.1.0.2/db_1/rdbms/admin/
[oracle@Linux03 admin]$ ls utlpwdmg.sql

[oracle@Linux03 admin]$ sqlplus / as sysdba
SQL> @/u01/app/oracle/product/12.1.0.2/db_1/rdbms/admin/utlpwdmg.sql

SQL> @/u01/app/oracle/product/12.1.0.2/db_1/rdbms/admin/utlpwdmg.sql

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Profile altered.

Note : You can query current default profile settings using as below

select * from DBA_PROFILES where profile='DEFAULT';

Starting from 12c this file (utlpwdmg.sql) creates four functions under user SYS. Here we have an option to select one from four functions.

ORA12C_STRONG_VERIFY_FUNCTION
ORA12C_VERIFY_FUNCTION
VERIFY_FUNCTION
VERIFY_FUNCTION_11G

This function makes the minimum complexity checks like the minimum length of the password, password not same as the
username, etc. The user may enhance this function according to your need.

You can change the password verify function by using below sql :

ALTER PROFILE "DEFAULT" LIMIT PASSWORD_VERIFY_FUNCTION ORA12C_VERIFY_FUNCTION

IT SETS UP FOLOWING PARAMETERS IN DEFAULT PROFILE:

ALTER PROFILE DEFAULT LIMIT
PASSWORD_LIFE_TIME 180
PASSWORD_GRACE_TIME 7
PASSWORD_REUSE_TIME UNLIMITED
PASSWORD_REUSE_MAX  UNLIMITED
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_LOCK_TIME 1

-- This script alters the default parameters for Password Management. This means that all the users on the system have Password Management enabled and set to the following values unless another profile is created with parameter values set to different value or UNLIMITED  is created and assigned to the user.

LETS TEST THE PASSWORD FUNCTION BY CREATING A NEW USER.

SQL> create user C##atest identified by atest11;

Error starting at line : 2 in command -
create user C##atest identified by atest11
Error report -
SQL Error: ORA-28003: password verification for the specified password failed
ORA-20001: Password length less than 8
28003. 00000 -  "password verification for the specified password failed"
*Cause:    The new password did not meet the necessary complexity
           specifications and the password_verify_function failed
*Action:   Enter a different password. Contact the DBA to know the rules for
           choosing the new password

          
While using length of 8 chars I was able to create user.

SQL> create user C##atest identified by atest113;

User C##ATEST created.


Follow this link on how to disable Password verify function  : 

http://arvindasdba.blogspot.com/2013/06/disable-password-verify-function-in.html

Thursday, July 7, 2016

Enable Database Auditing in oracle


ENABLE AUDITING IN ORACLE DATABASE


Enabling Auditing in Oracle Database

Auditing in Oracle Database helps track and monitor database activities, which is essential for security and compliance. By default, auditing is disabled, but you can enable it and configure its settings based on your requirements.

1. Understanding Auditing Parameters

To begin with, check the current auditing configuration using SQL*Plus:

sql

    SQL> SHOW PARAMETER AUDIT

Expected Output:


NAME TYPE VALUE
------------------------------------ ----------- ------------------------------ audit_file_dest string C:\ORACLE\PRODUCT\10.2.0\ADMIN \DB10G\ADUMP audit_sys_operations boolean FALSE audit_trail string NONE

2. Auditing Parameters and Their Values

The AUDIT_TRAIL parameter controls the type of auditing and can be set to one of the following values:

  • NONE: Auditing is disabled.
  • db: Auditing is enabled, with records stored in the database audit trail (SYS.AUD$).
  • db,extended: As db, but includes SQL_BIND and SQL_TEXT columns in the audit records.
  • xml: Auditing is enabled, with records stored as XML files in the operating system.
  • xml,extended: As xml, but includes SQL_BIND and SQL_TEXT columns.
  • OS: Auditing is enabled, with records directed to the operating system’s audit trail.

3. Enabling Auditing in the Database

To enable auditing and store audit records in the database audit trail, follow these steps:

  1. Set the AUDIT_TRAIL Parameter:

    Execute the following command to set the parameter:

    sql

    This command updates the AUDIT_TRAIL parameter in the server parameter file (SPFILE).

            SQL> ALTER SYSTEM SET audit_trail=db SCOPE=SPFILE;

  1. Restart the Database:

    For the changes to take effect, restart the database:

    sql:
    SQL> SHUTDOWN
    Database closed. Database dismounted. ORACLE instance shut down. SQL> STARTUP ORACLE instance started. Total System Global Area 289406976 bytes Fixed Size 1248600 bytes Variable Size 71303848 bytes Database Buffers 213909504 bytes Redo Buffers 2945024 bytes Database mounted. Database opened.

    Note: The auditing changes will only take effect after restarting the database.

4. Verifying Auditing Configuration

After the restart, confirm that the auditing settings are applied:

sql

    SQL> SHOW PARAMETER AUDIT

Expected Output:


NAME TYPE VALUE
------------------------------------ ----------- ------------------------------ audit_file_dest string C:\ORACLE\PRODUCT\10.2.0\ADMIN \DB10G\ADUMP audit_sys_operations boolean FALSE audit_trail string DB

5. Additional Considerations

  • Auditing Specific Actions: To audit specific actions (e.g., DDL commands, logins), use the AUDIT command in SQL*Plus.

  • Review Audit Records: Query the SYS.AUD$ table to review audit records.

    sql:
    SELECT * FROM SYS.AUD$;
  • Managing Audit Data: Regularly manage and archive audit data to prevent excessive growth of audit tables.

By enabling and configuring auditing, you can enhance security and ensure that your database activities are properly monitored and recorded.


Note: Enabling and Disabling the auditing in the database will only take effect after a db restart.

Wednesday, June 29, 2016

select grants on tables to users or roles


select grants on tables to users or roles



SELECT
  OWNER,
  GRANTEE,
  GRANTOR,
  TABLE_NAME,
  PRIVILEGE
FROM
  DBA_TAB_PRIVS
WHERE
  table_name   = 'TABLENAME'
AND PRIVILEGE IN ('DELETE','INSERT','SELECT','UPDATE')
AND GRANTEE   IN ('ROLE1','ROLE2')
ORDER BY
  1,2;



select grants on table to a user thru role or direct priv



select Grantee,'Granted Through Role' as Grant_Type, role, table_name
from role_tab_privs rtp, dba_role_privs drp
where rtp.role = drp.granted_role
and table_name = 'TABLENAME'
union
select Grantee,'Direct Grant' as Grant_type, null as role, table_name
from dba_tab_privs
where table_name = 'TABLENAME' ;

Tuesday, June 28, 2016

Online table redefination

Table and Dependent Objects Creation:

Drop Existing Objects:

Before creating new objects, ensure no conflicts with existing ones:

sql

DROP PROCEDURE get_description;
DROP VIEW redef_tab_v; DROP SEQUENCE redef_tab_seq; DROP TABLE redef_tab PURGE;

Create Table:

Define the table redef_tab with a primary key:

sql

CREATE TABLE redef_tab (
id NUMBER, description VARCHAR2(50), CONSTRAINT redef_tab_pk PRIMARY KEY (id) );

Create View:

Create a view that selects all columns from redef_tab:

sql

CREATE VIEW redef_tab_v AS
SELECT * FROM redef_tab;

Create Sequence:

Define a sequence to generate unique IDs:

sql

CREATE SEQUENCE redef_tab_seq;

Create Procedure:

Create a procedure to retrieve the description based on an ID:

sql

CREATE OR REPLACE PROCEDURE get_description (
p_id IN redef_tab.id%TYPE, p_description OUT redef_tab.description%TYPE) AS BEGIN SELECT description INTO p_description FROM redef_tab WHERE id = p_id; END; /

Create Trigger:

Create a trigger to automatically assign a new ID from the sequence before inserting it into redef_tab:

sql

CREATE OR REPLACE TRIGGER redef_tab_bir
BEFORE INSERT ON redef_tab FOR EACH ROW WHEN (new.id IS NULL) BEGIN :new.id := redef_tab_seq.NEXTVAL; END; /

Verify Object Creation:

Check the status of the created objects:

sql

COLUMN object_name FORMAT A20
SELECT object_name, object_type, status FROM user_objects ORDER BY object_name;

Expected Output:



OBJECT_NAME OBJECT_TYPE STATUS
-------------------- ------------------- ------- GET_DESCRIPTION PROCEDURE VALID REDEF_TAB TABLE VALID REDEF_TAB_BIR TRIGGER VALID REDEF_TAB_PK INDEX VALID REDEF_TAB_SEQ SEQUENCE VALID REDEF_TAB_V VIEW VALID

2. Online Table Redefinition:

Check Table Redefinition Feasibility:

Verify if the table redef_tab can be redefined:

sql

EXEC DBMS_REDEFINITION.can_redef_table('ATOORPU', 'REDEF_TAB');

Create Interim Table:

Create a new table redef_tab2 with the same structure as redef_tab, but initially empty:

sql

CREATE TABLE redef_tab2 AS
SELECT * FROM redef_tab WHERE 1=2;

Start Redefinition:

Begin the online redefinition process:

sql

EXEC DBMS_REDEFINITION.start_redef_table('ATOORPU', 'REDEF_TAB', 'REDEF_TAB2');

Synchronize Interim Table (Optional):

Synchronize redef_tab2 with any interim data:

sql

EXEC DBMS_REDEFINITION.sync_interim_table('ATOORPU', 'REDEF_TAB', 'REDEF_TAB2');

Add New Primary Key Constraint:

Add the primary key constraint to redef_tab2:

sql

ALTER TABLE redef_tab2 ADD (CONSTRAINT redef_tab2_pk PRIMARY KEY (id));

Complete Redefinition:

Finish the redefinition process:

sql

EXEC DBMS_REDEFINITION.finish_redef_table('ATOORPU', 'REDEF_TAB', 'REDEF_TAB2');

Drop Original Table:

Drop the original table, which has been renamed to REDEF_TAB2:

sql

DROP TABLE redef_tab2;

3. Verify the Updated Schema:

Check the status of the updated objects:

sql

COLUMN object_name FORMAT A20 SELECT object_name, object_type, status FROM user_objects ORDER BY object_name;

Expected Output:


OBJECT_NAME OBJECT_TYPE STATUS -------------------- ------------------- ------- GET_DESCRIPTION PROCEDURE VALID REDEF_TAB TABLE VALID REDEF_TAB2_PK INDEX VALID REDEF_TAB_SEQ SEQUENCE VALID REDEF_TAB_V VIEW VALID

Notes:

  • Procedure and View Validity: The GET_DESCRIPTION procedure and REDEF_TAB_V view remains valid after redefinition because they reference the table, which is still present under a new name (REDEF_TAB).
  • Trigger Loss: The REDEF_TAB_BIR trigger is dropped because it was associated with the original table, which was renamed and subsequently dropped.

This comprehensive setup and redefinition process helps manage schema changes with minimal downtime, ensuring that your database schema evolves smoothly while maintaining data integrity.

Thursday, June 16, 2016

ORA-00020: maximum number of processes exceeded



ORA-00020: maximum number of processes



This error occurs when your total numbers of sessions connecting to oracle database has exceeded the max limit set in parameter file. Simplest way to overcome this error is to reset the max sessions value to a greater value than existing.Here is how to do it
 



oracle@LINUX201:[~] $ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.4.0 Production on Mon Jun 13 10:20:26 2016

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-00020: maximum number of processes (500) exceeded




oracle@LINUX201:[~] $ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.4.0 Production on Mon Jun 13 10:23:42 2016

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-00020: maximum number of processes (500) exceeded


Enter user-name:

Disconnected from ORACLE

I wasn't able get into the oracle database to kill some database session. So I tried to kill few sessions on OS to make my way into DB.

oracle@LINUX201:[~] $ ps -ef|grep oracle
.
.
.
.
.
.
.

oracle   64373     1  0 Jun08 ?        00:00:03 oracleQPDEV (LOCAL=NO)
oracle   64540     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   64554     1  0 Jun08 ?        00:00:01 oracleQPDEV (LOCAL=NO)
oracle   64633     1  0 Jun08 ?        00:00:03 oracleQPDEV (LOCAL=NO)
oracle   64637     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
.
.
.
oracle   65186     1  0 Jun08 ?        00:00:04 oracleQPDEV (LOCAL=NO)
oracle   65190     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   65192     1  0 Jun08 ?        00:00:01 oracleQPDEV (LOCAL=NO)
oracle   65202     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   65206     1  0 Jun08 ?        00:00:02 oracleQPDEV (LOCAL=NO)
root     65407 65381  0 May16 pts/2    00:00:00 sudo -u oracle -i
oracle   65408 65407  0 May16 pts/2    00:00:00 -bash
oracle   65458 65408  0 May16 pts/2    00:00:00 sqlplus
oracle   65459 65458  0 May16 ?        00:00:00 oracleQPDEV (DESCRIPTION=(LOCAL=YES)(ADDRESS=(PROTOCOL=beq)))
oracle   65518     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   65520     1  0 Jun08 ?        00:00:02 oracleQPDEV (LOCAL=NO)
oracle   65534     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)

oracle@LINUX201:[~] $ kill -9 64785
oracle@LINUX201:[~] $ sqlplus "/as sysdba"

SQL*Plus: Release 11.2.0.4.0 Production on Mon Jun 13 10:26:25 2016

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

ERROR:
ORA-00020: maximum number of processes (500) exceeded


Enter user-name: ^C

Killing few processes on Linux :

oracle@LINUX201:[~] $ kill -9 65192 65085 64785 64777 64655 64653 64637


oracle@LINUX201:[~] $ ps -ef|grep 65192 65085 64785 64777 64655 64653 64637

.
.
.
.
oracle   50258     1  0 Jun07 ?        00:00:04 oracleQPDEV (LOCAL=NO)
oracle   50264     1  0 Jun07 ?        00:00:03 oracleQPDEV (LOCAL=NO)
oracle   50268     1  0 Jun07 ?        00:00:02 oracleQPDEV (LOCAL=NO)
.
.
.
oracle   64554     1  0 Jun08 ?        00:00:01 oracleQPDEV (LOCAL=NO)
oracle   64633     1  0 Jun08 ?        00:00:03 oracleQPDEV (LOCAL=NO)
oracle   65186     1  0 Jun08 ?        00:00:04 oracleQPDEV (LOCAL=NO)
oracle   65190     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   65202     1  0 Jun08 ?        00:00:00 oracleQPDEV (LOCAL=NO)
oracle   65206     1  0 Jun08 ?        00:00:02 oracleQPDEV (LOCAL=NO)
.
.
.

oracle@LINUX201:[~] $ sqlplus "/as sysdba"

SQL*Plus: Release 11.2.0.4.0 Production on Mon Jun 13 10:30:07 2016

Copyright (c) 1982, 2013, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> show parameter process;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
aq_tm_processes                      integer     1
cell_offload_processing              boolean     TRUE
db_writer_processes                  integer     1
gcs_server_processes                 integer     0
global_txn_processes                 integer     1
job_queue_processes                  integer     1000
log_archive_max_processes            integer     4
processes                            integer     500
processor_group_name                 string


Now reset the max processes to a greater value:

SQL> alter system set processes=1200 scope=spfile;

System altered.

SQL>  show parameter process;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
aq_tm_processes                      integer     1
cell_offload_processing              boolean     TRUE
db_writer_processes                  integer     1
gcs_server_processes                 integer     0
global_txn_processes                 integer     1
job_queue_processes                  integer     1000
log_archive_max_processes            integer     4
processes                            integer     500
processor_group_name                 string
SQL> select name,open_mode from v$database;

NAME      OPEN_MODE
--------- --------------------
QPDEV     READ WRITE

This will need a restart to take affect


SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

SQL> startup;
ORACLE instance started.

Total System Global Area 3206836224 bytes
Fixed Size                  2257520 bytes
Variable Size            1275071888 bytes
Database Buffers         1912602624 bytes
Redo Buffers               16904192 bytes
Database mounted.
Database opened.

SQL> show parameter process

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
aq_tm_processes                      integer     1
cell_offload_processing              boolean     TRUE
db_writer_processes                  integer     1
gcs_server_processes                 integer     0
global_txn_processes                 integer     1
job_queue_processes                  integer     1000
log_archive_max_processes            integer     4
processes                            integer     1200
processor_group_name                 string

SQL>

Friday, June 10, 2016

Create Temporary Tables in Oracle


Global Temporary Tables in Oracle


Temporary tables are useful in applications where a result set is to be buffered, perhaps because it is constructed by running multiple DML operations. For example, consider the following:

A Web-based airlines reservations application allows a customer to create several optional itineraries. Each itinerary is represented by a row in a temporary table. The application updates the rows to reflect changes in the itineraries. When the customer decides which itinerary she wants to use, the application moves the row for that itinerary to a persistent table.

During the session, the itinerary data is private. At the end of the session, the optional itineraries are dropped.

This statement creates a temporary table that is transaction specific:

NOTE : Indexes can be created on temporary tables. They are also temporary and the data in the index has the same session or transaction scope as the data in the underlying table.

*********************************************************************************
HERE is an example to create a global temporary table with on commit DELETE ROWS :
*********************************************************************************

sql>  CREATE GLOBAL TEMPORARY TABLE admin_work_area
        (startdate DATE,
         enddate DATE,
         class CHAR(20))
      ON COMMIT DELETE ROWS;
      
      
    
sql>  insert into ADMIN_WORK_AREA values (sysdate,sysdate+ 1,'A');

1 row inserted.


sql> select * from ADMIN_WORK_AREA;

commit;

Commit complete.

sql> select * from ADMIN_WORK_AREA;


NOTE: records in this temp table will be deleted upon commit. This is equivalent to truncating table on commit.

*********************************************************************************
HERE is an example to create a global temporary table with on commit PRESERVE ROWS :
*********************************************************************************


sql>  CREATE GLOBAL TEMPORARY TABLE admin_work_area
        (startdate DATE,
         enddate DATE,
         class CHAR(20))
      ON COMMIT PRESERVE ROWS;
      
            
sql>  insert into ADMIN_WORK_AREA values (sysdate,sysdate+ 1,'A');

1 row inserted.

1 row inserted.

sql>  select * from ADMIN_WORK_AREA;

commit;

Commit complete.

sql>  select * from ADMIN_WORK_AREA;


NOW exit the session and login back and select the table.

sql>  select * from ADMIN_WORK_AREA;

table is empty

NOTE: records (rows) in this temp table will be deleted upon session exit only, as long as you are using same session you can see these rows. 
This is equivalent to truncating table on session exit.