Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, May 21, 2014

RESULT_CACHE hint on Oracle 11G

Result Cache is a new feature in Oracle 11g.  It caches the results of queries and puts it into shared pool. If you are executing the same query without changes then it uses the result of shared pool. 

http://docs.oracle.com/cd/E16655_01/server.121/e15857/tune_result_cache.htm#TGDBA648


Friday, February 14, 2014

How to get the table or index syntax from sql

We can use the DBMS_METADATA.GET_DDL which will retrieve the complete syntax of the table / index

Here is the example.

 SELECT DBMS_METADATA.GET_DDL('TABLE','TEST_PRA','APPS') ddl FROM dual;

Tuesday, January 7, 2014

What is difference between AD_BUGS and AD_APPLID_PATCHES ?

AD_BUGS holds information about the various Oracle Applications bugs whose fixes have been applied (ie. patched) in the Oracle Applications installation. 

AD_APPLIED_PATCHES holds information about the "distinct" Oracle Applications patches that have been applied. If 2 patches happen to have the same name but are different in content (eg. "merged" patches), then they are considered distinct and this table will therefore hold 2 records.

Tuesday, October 29, 2013

How to find the long running sqls

select sid,
       opname,
       target,
       sofar,
       totalwork,
       units,
       (totalwork-sofar)/time_remaining bps,
       time_remaining,
       sofar/totalwork*100 fertig
from   v$session_longops
where  time_remaining > 0

Monday, October 7, 2013

How to find the sid from concurrent request id

The below sql retrieve the sid information for the running concurrent program.

SELECT a.request_id, d.sid, d.serial# ,d.osuser,d.process , c.SPID ,d.inst_id
FROM apps.fnd_concurrent_requests a,
apps.fnd_concurrent_processes b,
gv$process c,
gv$session d
WHERE a.controlling_manager = b.concurrent_process_id
AND c.pid = b.oracle_process_id
AND b.session_id=d.audsid
AND a.request_id =&req_id
AND a.phase_code = 'R';

Also you can use the below sql to find out which sql is running for the above concurrent request id.

select a.sid, a.serial#, b.sql_text
   from v$session a, v$sqlarea b
    where a.sql_address=b.address
     and a.sid = &sid

Saturday, September 7, 2013

How to find which patch applied on database related to oracle bugs

select * from ad_bugs where bug_number ='12945067' order by bug_number

Tuesday, September 3, 2013

how to find the number of users connected to Oracle Apps in the past 1 day using SQL

select count(distinct user_id) "users" from icx_sessions where last_connect > sysdate - 1 and user_id != '-1'

BITAND function in sql

Purpose
The BITAND function treats its inputs and its output as vectors of bits; the output is the bitwise AND of the inputs.
The types of expr1 and expr2 are NUMBER, and the result is of type NUMBER. If either argument to BITAND is NULL, the result is NULL.
The arguments must be in the range -(2(n-1)) .. ((2(n-1))-1). If an argument is out of this range, the result is undefined.
The result is computed in several steps. First, each argument A is replaced with the value SIGN(A)*FLOOR(ABS(A)). This conversion has the effect of truncating each argument towards zero. Next, each argument A (which must now be an integer value) is converted to an n-bit two's complement binary integer value. The two bit values are combined using a bitwise AND operation. Finally, the resulting n-bit two's complement value is converted back to NUMBER.
Notes on the BITAND Function
  • The current implementation of BITAND defines n = 128.
  • PL/SQL supports an overload of BITAND for which the types of the inputs and of the result are all BINARY_INTEGER and for which n = 32.
Examples
The following example performs an AND operation on the numbers 6 (binary 1,1,0) and 3 (binary 0,1,1):
SELECT BITAND(6,3) FROM DUAL;

BITAND(6,3)
-----------
          2
This is the same as the following example, which shows the binary values of 6 and 3. The BITAND function operates only on the significant digits of the binary values:
SELECT BITAND(
   BIN_TO_NUM(1,1,0),
   BIN_TO_NUM(0,1,1)) "Binary"
FROM DUAL;
 
    Binary
----------
         2

Tuesday, July 9, 2013

Restrictions on DISTINCT and UNIQUE Queries

DISTINCT , UNIQUE

Specify DISTINCT or UNIQUE if you want the database to return only one copy of each set of duplicate rows selected. These two keywords are synonymous. Duplicate rows are those with matching values for each expression in the select list.
Restrictions on DISTINCT and UNIQUE Queries These types of queries are subject to the following restrictions:
  • When you specify DISTINCT or UNIQUE, the total number of bytes in all select list expressions is limited to the size of a data block minus some overhead. This size is specified by the initialization parameter DB_BLOCK_SIZE.
  • You cannot specify DISTINCT if the select_list contains LOB columns.

Thursday, June 13, 2013

IGNORE_ROW_ON_DUPKEY_INDEX Hint for INSERT Statement 11g new sql feature

With INSERT INTO TARGET...SELECT...FROM SOURCE, a unique key for some to-be-inserted rows may collide with existing rows. The IGNORE_ROW_ON_DUPKEY_INDEX allows the collisions to be silently ignored and the non-colliding rows to be inserted. A PL/SQL program could achieve the same effect by first selecting the source rows and by then inserting them one-by-one into the target in a block that has a null handler for the DUP_VAL_ON_INDEX exception. However, the PL/SQL approach would take effort to program and is much slower than the single SQL statement that this hint allows. This hint improves performance and ease-of-programming when implementing an online application upgrade script using edition-based redefinition.

Sunday, June 2, 2013

PURGE new SQL feature in Oracle 11g

Purpose
Use the PURGE statement to remove a table or index from your recycle bin and release all of the space associated with the object, or to remove the entire recycle bin, or to remove part of all of a dropped tablespace from the recycle bin.

To see the contents of your recycle bin, query the USER_RECYCLEBIN data dictionary review. You can use the RECYCLEBIN synonym instead. The following two statements return the same rows:

SELECT * FROM RECYCLEBIN;
SELECT * FROM USER_RECYCLEBIN;

Caution:
You cannot roll back a PURGE statement, nor can you recover an object after it is purged.

Prerequisites
The database object must reside in your own schema or you must have the DROP ANY ... system privilege for the type of object to be purged, or you must have the SYSDBA system privilege.

Semantics
TABLE or INDEX
Specify the name of the table or index in the recycle bin that you want to purge. You can specify either the original user-specified name or the system-generated name Oracle Database assigned to the object when it was dropped.
  • If you specify the user-specified name, and if the recycle bin contains more than one object of that name, then the database purges the object that has been in the recycle bin the longest.
  • System-generated recycle bin object names are unique. Therefore, if you specify the system-generated name, then the database purges that specified object.
When the database purges a table, all table partitions, LOBs and LOB partitions, indexes, and other dependent objects of that table are also purged.

RECYCLEBIN
Use this clause to purge the current user's recycle bin. Oracle Database will remove all objects from the user's recycle bin and release all space associated with objects in the recycle bin.

DBA_RECYCLEBIN
This clause is valid only if you have SYSDBA system privilege. It lets you remove all objects from the system-wide recycle bin, and is equivalent to purging the recycle bin of every user. This operation is useful, for example, before backward migration.

TABLESPACE tablespace
Use this clause to purge all the objects residing in the specified tablespace from the recycle bin.
USER user Use this clause to reclaim space in a tablespace for a specified user. This operation is useful when a particular user is running low on disk quota for the specified tablespace.
Examples
Remove a File From Your Recycle Bin: Example The following statement removes the table test from the recycle bin. If more than one version of test resides in the recycle bin, then Oracle Database removes the version that has been there the longest:

PURGE TABLE test;

To determine system-generated name of the table you want removed from your recycle bin, issue a SELECT statement on your recycle bin. Using that object name, you can remove the table by issuing a statement similar to 
the following statement. (The system-generated name will differ from the one shown in the example.)

PURGE TABLE RB$$33750$TABLE$0;

Remove the Contents of Your Recycle Bin: Example To remove the entire contents of your recycle bin, issue the following statement:

PURGE RECYCLEBIN;

Thursday, May 23, 2013

dbms_utility.format_error_stack in Oracle 10g

In Oracle database 10g, Oracle added format_error_backtrace which can and should be called from exception handler. It displays the call stack at the point where exception was raised.
 
Let's see what happen when exception handled using dbms_utility.format_error_stack procedure P3.

scott@10gR2> select * from v$version;

BANNER
----------------------------------------------------------------
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
CORE    10.2.0.4.0      Production
TNS for Solaris: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production

scott@10gR2> create or replace procedure p3 as
  2  begin
  3     p2;
  4  exception
  5             when others then
  6             dbms_output.put_line (' calling format error stack from P3 ');
  7             dbms_output.put_line (dbms_utility.FORMAT_ERROR_BACKTRACE);
  8  end;
  9  /

Procedure created.


And now when I run the procedure P3, I will see the following output.


scott@10gR2> exec p3;
raising error at p1
 calling format error stack from P3
ORA-06512: at "scott.P1", line 4
ORA-06512: at "scott.P2", line 3
ORA-06512: at "scott.P3", line 3

PL/SQL procedure successfully completed.


The information that had previously been available only through an unhandled exception is now retrievable from within the PL/SQL code.

Saturday, May 18, 2013

Forced Replacement of Types in 11g release 2


If you have used types, you must have realized how powerful they can be. You can define your own data type that can be a composite of various other data types, or they can be records to group related pieces of data together, even to match a complete table row. Here is an example of a type called TY_TRANS that defines the elements of a transaction:
create or replace type ty_trans
as object
(
    trans_id    number(2),
    trans_amt   number(10)
)
/

Next, you can a type to hold sales information. Since every sale will have a transaction, you can define a column of type ty_trans, shown below:
create or replace type ty_sales
as object
(
    sales_id    number(2),
    trans_rec   ty_trans
)
/

Once you define the structures this way, TY_SALES becomes a dependent of TY_TRANS. You can confirm that by querying USER_DEPENDENCIES view:
SQL> select referenced_name, dependency_type
  2  from user_dependencies
  3  where name = 'TY_SALES'
  4  /

REFERENCED_NAME       DEPE
---------------------           ----
STANDARD              HARD
TY_TRANS              HARD

This shows that TY_SALES has a “hard” dependency on the type TY_TRANS.

Now, let’s look at a real world possibility. What if you made a mistake in defining the types and defined an attribute with a wrong precision or just want to change the precision keeping with the business needs? Well, not a problem – you simply use the CREATE OR REPLACE statement to recreate that type:
create or replace type ty_sales
as object
(
    sales_id    number(3),
    trans_rec   ty_trans
)
/

Here you recreated the type with the one of the attributes as number(3) instead of number(2), as it was previously. While this operation was successful for this type, what if you had to do the same for ty_trans?
SQL> create or replace type ty_trans
  2  as object
  3  (
  4      trans_id    number (4),
  5      trans_amt   number
  6  )
  7  /
create or replace type ty_trans
*
ERROR at line 1:
ORA-02303: cannot drop or replace a type with type or table dependents

The error message says it all – you can’t alter this type since it has a dependent, as we saw earlier from the user_dependencies view. It’s sort of a parent-child relationship between the types. If there is at least one child, you can’t drop the parent. So, what are your options for changing the “parent” type definition?

Until Oracle Database 11g Release 2, the only option for modifying that type is the MODIFY ATTRIBUTE clause of ALTER TYPE statement, which is an expensive and potentially error prone proposition. In Release 2, there is a very convenient FORCE clause to replace the type forcibly. Using this, we can alter the type TY_TRANS as:
create or replace type ty_trans
force
as object
(
    trans_id    number (4),
    trans_amt   number
)
/

This will execute successfully and the type will be created, due to the FORCE clause shown in bold above. This makes it very convenient when you deploy applications – you don’t have to worry about which specific attributes have changed; rather, a full replace type takes care of the type definition, changed or not.

Friday, May 10, 2013

SKIP LOCKED clause in Oracle 11g


Oracle 11g introduced SKIP LOCKED clause to query the records from the table which are not locked in any other active session of the database. This looks quite similar to exclusive mode of locking. The SQL statement in Example code (15) queries the unlocked records from EMP table
Example :
SELECT * FROM EMP FOR UPDATE SKIP LOCKED

Read Only Tables In Oracle 11g

 In Oracle 11g, a table can be set READ ONLY mode to restrict write operations on the table. A table can be altered to toggle over READ ONLY and READ WRITE modes.


Example 1:
SQL> ALTER TABLE EMP READ ONLY;
Example 2: 
SQL> ALTER TABLE EMP READ WRITE;

Tuesday, April 9, 2013

Read only tables in Oracle 11g

Oracle 11g database categorizes tables based on their transactional behavior; they can be READ ONLY or READ WRITE. A READ ONLY table remains passive against all DML operations, selective DDL operations, and flashback activities. The permissible actions on a READ ONLY table includes selection, indexing, enforce constraints, rename, and dropping.

With the addition of this category, Oracle added another obvious category as READ WRITE. A table, which is open for all transactional activities, falls under this category. The category can be toggled over at any point of time in the session using ALTER TABLE command.

A table would be created in conventional manner but it can be altered to READ ONLY mode.

Example

ALTER TABLE [TABLE NAME] [READ ONLY | READ WRITE]

Example

SQL> ALTER TABLE EMPLOYEES READ ONLY;
Table altered.

The below ALTER TABLE statement switches back the table mode to READ WRITE.


SQL> ALTER TABLE EMPLOYEES READ WRITE;
Table altered.
READ ONLY tables are extremely useful in tightening the security at user level. Earlier, the same objective was achieved by a statement level DML trigger or a check constraint in ‘disable validate’ state. But READ ONLY table provides a simple and reliable technique to impose DML restriction on a table.

Thursday, April 4, 2013

How do I calculate the table space size in oracle


SELECT   /* + RULE */
         df.tablespace_name "Tablespace",
         df.bytes / (1024 * 1024 * 1024) "Size(GB)",
         SUM (fs.bytes) / (1024 * 1024 * 1024) "Free(GB)",
         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
             WHERE tablespace_name LIKE 'ONTD%'
          GROUP BY tablespace_name) df
   WHERE fs.tablespace_name(+) = df.tablespace_name
GROUP BY df.tablespace_name, df.bytes
ORDER BY 3 DESC

Monday, March 11, 2013

Query to find locked objects in Oracle


SELECT   c.owner, c.object_name, c.object_type, b.sid, b.serial#, b.status,
         b.osuser, b.machine, b.program, b.module, b.action
    FROM v$locked_object a, v$session b, dba_objects c
   WHERE b.sid = a.session_id AND a.object_id = c.object_id
ORDER BY module

Tuesday, February 19, 2013

Oracle 10g new features for developers

10g Limit less LOB
  Since first introduced the Oracle LOB type has been limited to 4GB (enough for most uses)
• Oracle 10g allows LOB data to be limited only by tablespace page size
• Current limit: – 8–128 terabytes
• Supported environments:
– PL/SQL using DBMS_LOB
– Java using JDBC
– C/C++ using OCI

10g R2 DML Error Logging


Insert, Update, Delete, and Merge add ERROR logging allowing you to capture DML errors and log
them
INSERT … /* or UPDATE, DELETE, MERGE */
LOG ERRORS
[ INTO [schema.] table ]
[ (simple_expression) ]
[ REJECT LIMIT { integer | UNLIMITED }
– Default error table defined by DBMS_ERRLOG package: ERR$_ followed by first 25 characters of DML target table
– Simple expression is value to be used as statement tag (may be result of SQL function call)
– Reject limit default is zero

Creating the Error Log Table


Oracle provides a PL/SQL packaged procedure to create the logging table (for each table to be logged)
execute DBMS_ERRLOG.CREATE_ERROR_LOG('myemp', 'myemplog');
– myemp Table DML is being applied to
– myemplog Logging table for rejected rows
• Creates a database table containing:
– ORA_ERR_NUMBER$ Error number
– ORA_ERR_MESG$ Error message
– ORA_ERR_ROWID$ Rowid of impacted rows
– ORA_ERR_OPTYP$ Operation type (I,U,D,M)
– ORA_ERR_TAG$ Text from LOG_ERRORS
– All column values (good & bad) as varchar2(4000)

Error Log Output


insert into emp select * from myempbig
log errors into myemplog ('Log test3')
reject limit unlimited;
0 rows created.
ORA_ERR_NUMBER$ 12899
ORA_ERR_MESG$ ORA-12899: value too large for column
"JOHN"."EMP"."JOB" (actual: 13, maximum: 9)
ORA_ERR_ROWID$
ORA_ERR_OPTYP$ I
ORA_ERR_TAG$ Log test3
EMPNO 6543
ENAME STEPHENSON
JOB WEB DEVELOPER
MGR 7369
HIREDATE 03-SEP-06
SAL 3000
COMM
DEPTNO 40

10g SQL*Plus Misc


SET SERVEROUTPUT ON now works immediately within PL/SQL block where executed
• DBMS_OUTPUT.PUT_LINE text line maximum increased from 255 to 32767 bytes
• Recycle Bin keeps deleted database objects until Purged
• DESCRIBE automatically attempts to validate invalid objects before display
• White space now allowed in file names
• Substitution variables allowed in SET PROMPT
• Three pre-defined SQL*Plus variables added:
– _DATE Current date or a user defined fixed string.
– _PRIVILEGE Privilege level of connection
(AS SYSDBA, AS SYSOPER or blank)
– _USER Currently connected userid
• APPEND, CREATE, REPLACE extensions to SPOOL

SET SERVEROUTPUT ON

It is common for PL/SQL developers to use the DBMS_OUTPUT.PUT_LINE procedure to write to the console during testing and debugging
• To enable output from DBMS_OUTPUT.PUT_LINE you must enable SERVEROUTPUT
• In Oracle 10g this command has been enhanced to include a default of UNLIMITED buffer size eliminating the need to specify a buffer size
• You may also specify “WORD_WRAPPED” to cause DBMS_OUTPUT.PUT_LINE output to be wrapped at clear word breaks
set serveroutput on size 1000000 –- size limited
set serveroutput on unlimited -- size unlimited
set serveroutput on -- size unlimited (default)

10g Using Recyclebin


Careful! Dropping tables no longer really drops them… This might be a problem for applications with
lots of “temp”-type tables

drop table myTable;

show recyclebin
ORIGINAL    RECYCLEBIN NAME     TYPE  DROP TIME
myTable RB$$41506$TABLE$0   TABLE 2004-04-01:22:11:13

flashback table myTable to before drop;

drop table myTable purge;

purge recyclebin;

10g Regular Expressions


Oracle now has three functions that allow the use of POSIX-compliant regular expressions 
in SQL

– REGEXP_LIKE Allows pattern matching
– REGEXP_INSTR Search for string matching pattern and return position

– REGEXP_REPLACE Find string matching pattern and replace it
– REGEXP_SUBSTR Search for string matching pattern and return substring



Regular Expression Examples




select employee_id,phone_number
from hr.employees
where REGEXP_LIKE(phone_number,
'[[:digit:]]{3}[[:punct:]][[:digit:]]{2}[[:punct:]]');

Example

select first_name, last_name
from hr.employees
where REGEXP_LIKE (first_name, '^ste(v|ph)en$');

LIKE vs REGEXP_LIKE


Here are two statement that generate exactly the same output and nearly the same execution plan

select prod_id , substr(prod_name,1,20) prod_name , substr(prod_desc,1,30) prod_desc
from sh.products
where prod_name like ('E%') 
or prod_name like ('P%')
order by prod_id;

select prod_id, substr(prod_name,1,20) prod_name, substr(prod_desc,1,30) prod_desc
from sh.products
where regexp_like (prod_name,'^E|^P')
order by prod_id;









Monday, February 11, 2013

To find the which sql is executing by the concurrent program in a schema

Run the below query first to get the SID and the program details.


SELECT   q.concurrent_queue_name qname, f.user_name, a.request_id "Req Id",
         DECODE (a.parent_request_id, -1, NULL, a.parent_request_id) "Parent",
         a.concurrent_program_id "Prg Id", a.phase_code, a.status_code,
         vs.inst_id, vs.sid, vs.serial# "Serial#", vp.spid,
         b.os_process_id apprsid,
           (  NVL (a.actual_completion_date, SYSDATE)
            - a.actual_start_date
           )
         * 1440
               "Time",
            c.concurrent_program_name
         || ' - '
         || c2.user_concurrent_program_name "Program"
    FROM applsys.fnd_concurrent_requests a,
         applsys.fnd_concurrent_processes b,
         applsys.fnd_concurrent_queues q,
         applsys.fnd_concurrent_programs_tl c2,
         applsys.fnd_concurrent_programs c,
         applsys.fnd_user f,
         gv$session vs,
         gv$process vp
   WHERE a.controlling_manager = b.concurrent_process_id
     AND a.concurrent_program_id = c.concurrent_program_id
     AND a.program_application_id = c.application_id
     AND c2.concurrent_program_id = c.concurrent_program_id
     AND f.user_name = :user_name
     AND c2.application_id = c.application_id
     AND a.phase_code IN ('I', 'P', 'R', 'T')
     AND a.status_code IN ('R')
     AND a.requested_by = f.user_id
     AND b.queue_application_id = q.application_id
     AND b.concurrent_queue_id = q.concurrent_queue_id
     AND vp.spid = a.oracle_process_id
     AND vs.paddr(+) = vp.addr
     AND vs.inst_id(+) = vp.inst_id
ORDER BY 12;


Take the SID of the concurrent program and give the SID to the below program

select sql_text,HASH_VALUE from gv$sqltext t,gv$session s
where t.ADDRESS = s.SQL_ADDRESS
and t.HASH_VALUE = s.SQL_HASH_VALUE
and s.sid = &sid
order by PIECE ;