Codd

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 59

Codd’s rule

All information in a relational database is represented


Rule 1: The Information explicitly at the logical level and in exactly one way - by
values in tables.
Each and every datum (atomic value) in a relational
database is guaranteed to be logically accessible by
Rule 2: Guaranteed Access
resorting to a combination of table name, primary key
value, and column name.
Null values (distinct from the empty character string of
blank characters and distinct from any zero or other
Rule 3: Systematic Treatment
numbers) are supported in fully relational DBMS for
of Null Values
representing missing information and inapplicable
information in a systematic way.
The database description is represented at the logical
Rule 4: Dynamic Online
level in the same way as ordinary data, so that
Catalog Based on the
authorized users can apply the same relational language
Relational Model
to its interrogation as they apply to the regular data.
A relational system may support several languages and
various modes of terminal use (for example, the fill-in-
the-blanks mode). However, there must be at least one
language whose statements are expressible, per some
well-defined syntax, as character strings, d that is
comprehensive in supporting all of the following items:
 Data Definition
Rule 5: Comprehensive Data
Sublanguage  View Definition
 Data manipulation (interactive and by program)
 Integrity Constraints
 Authorization

 Transaction boundaries (begin, commit, and


rollback).
All views that are theoretically updateable are also
Rule 6: View Updating
updateable by the system.
The capability of handling a base relation or a derived
Rule 7: High-Level Insert, relation as a single operand applies not only to the
Update, and Delete retrieval of data but also to the insertion, update, and
deletion of data.
Application programs and terminal activities remain
Rule 8: Physical Data
logically unimpaired whenever any changes are made in
Independence
either storage representations or access methods.
Application programs and terminal activities remain
Rule 9: Logical Data logically unimpaired when information-preserving
Independence changes of any kind that theoretically permit
unimpairment are made to the base tables.
Integrity constraints specific to a particular relational
Rule 10: Integrity database must be definable in the relational data
Independence sublanguage and storable in the catalog, not in the
application programs.
Rule 11: Distribution
A relational DBMS has distribution dependence.
Independence
If a relational system has a low-level (single record at a
time) language, that low level cannot be used to subvert
Rule 12: Nonsubversion or bypass the integrity rules and constraints expressed in
the higher-level relational language (multiple records at a
time).

2) What is a mutating table error and how can you get around it?

This happens with triggers. It occurs because the trigger is trying to update a row it is
currently using. The usual fix involves either use of views or temporary tables so the
database is selecting from one while updating the other.

3) Describe the use of %ROWTYPE and %TYPE in PL/SQL?

%ROWTYPE allows you to associate a variable with an entire table row. The %TYPE
associates a variable with a single column type.

4) What packages (if any) has Oracle provided for use by developers?

Oracle provides the DBMS_ series of packages. There are many which developers should
be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY,
DBMS_DDL, UTL_FILE.

5). What are SQLCODE and SQLERRM and why are they important for PL/SQL
developers?

SQLCODE returns the value of the error number for the last error encountered. The
SQLERRM returns the actual error message for the last error encountered. They can be
used in exception handling to report, or, store in an error log table, the error that occurred
in the code. These are especially useful for the WHEN OTHERS exception.

6) How can you find within a PL/SQL block, if a cursor is open?

Use the %ISOPEN cursor status variable.

7) What are the types of triggers?

There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE,
AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT

8) How can variables be passed to a SQL routine?

By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1,
&2,...,&8) to pass the values after the command into the SQLPLUS session. To be
prompted for a specific variable, place the ampersanded variable in the code itself:

9)How can you call a PL/SQL procedure from SQL?

By use of the EXECUTE (short form EXEC) command.

10) What SQLPlus command is used to format output from a select?

This is best done with the COLUMN command.

11) What is a Cartesian product?

A Cartesian product is the result of an unrestricted join of two or more tables. The result
set of a three table Cartesian product will have x * y * z number of rows where x, y, z
correspond to the number of rows in each table involved in the join.

-------------------------------------------
1. To see current user name
Sql> show user;
2. Change SQL prompt name
SQL> set sqlprompt “Manimara > “
Manimara >
Manimara >
3. Switch to DOS prompt
SQL> host
4. How do I eliminate the duplicate rows ?
SQL> delete from table_name where rowid not in (select max(rowid) from table group
by duplicate_values_field_name);
or
SQL> delete from table_name ta where rowid >(select min(rowid) from table_name tb
where ta.dv=tb.dv and .....);
Example.
Table Emp
Empno Ename
101 Scott
102 Jiyo
103 Millor
104 Jiyo
105 Smith
delete from emp a where rowid < ( select max(rowid) from emp b where a.ename =
b.ename );
The output like,
Empno Ename
101 Scott
103 Millor
104 Jiyo
105 Smith
5. How do I display row number with records?
To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum,
ename from emp;
Output:
1 Scott
2 Millor
3 Jiyo
4 Smith
6. Display the records between two range
select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER
7. I know the nvl function only allows the same data type(ie. number or char or date
Nvl(comm, 0)), if commission is null then the text “Not Applicable” want to display,
instead of blank space. How do I write the query?
SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA
8. Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.
9. Explicit Cursor attributes
There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT,
cursor_name%ISOPEN
10. Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit
cursor after executing SQL statements.
: 2. All are Boolean attributes.
11. Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT
(DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
---------
3700
12. To view installed Oracle version information
SQL> select banner from v$version;
13. Display the number value in Words
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
14. Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
15. Which date function returns number value?
months_between
16. Any three PL/SQL Exceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others
17. What are PL/SQL Cursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
18. Other way to replace query result null value with a text
SQL> Set NULL ‘N/A’
to reset SQL> Set NULL ‘’
19. What are the more common pseudo-columns?
SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM
20. What is the output of SIGN function?
1 for positive value,
0 for Zero,
-1 for Negative value.
21. What is the maximum number of triggers, can apply to a single table?
12 triggers.

1. What are the different types of joins?


Inner Join
outer join (left outerjoin , right outer join)
full outer join
2. Explain normalization with examples.
First Normal Form : Avaoids relation within a relation
Second Normal Form : Fully functional depended on each key
Third Normal Form : Avoids Transitivity dependency
3. What cursor type do you use to retrieve multiple recordsets?
ref cursors'

4. State the difference between a "where" clause and a "having" clause


having comes along with group by

5. What is the difference between "procedure" and "function"?


procedure doesnot return a value thru return statement

6. How will you copy the structure of a table without copying the data?
select * from table_naem where 1 > 3

7. How to find out the database name from SQL*PLUS command prompt?
-

8. Tadeoffs with having indexes


9. Talk about "Exception Handling" in PL/SQL?
10. What is the difference between "NULL in C" and "NULL in Oracle?"
11. What is Pro*C? What is OCI?
12. Give some examples of Analytical functions.
13. What is the difference between "translate" and "replace"?
14. What is DYNAMIC SQL method 4?
15. How to remove duplicate records from a table?
16. What is the use of Analyzing the tables?
17. How to run SQL script from a Unix Shell?
18. What is a "transaction"? Why are they necessary?
19. Explain Normalization and Denormalization with examples.
20. When do you get constraint violation? What are the types of constraints?
21. How to convert RAW datatype into TEXT?
22. What is the difference between Primary Key and Aggregate Key
23. How functional dependency is related to database table design?
24. What is a "trigger"?
25. Why can a "group by" or "order by" clause be expensive to process?
26. What are "HINTS"? What is "index covering" of a query?
27. What is a VIEW? How to get script for a view?
28. What are the Large object types supported by Oracle?
29. What is SQL*Loader?
30. Difference between "VARCHAR" and "VARCHAR2" datatypes.
31. What is the difference among "dropping a table", "truncating a table" and "deleting all
records" from a table.
32. Difference between "ORACLE" and "MICROSOFT ACCESS" databases.
33. How to create a database link ?
Autonomous Transactions
Friday, March 24, 2006
By Arabinda Banerjee
What is an Autonomous Transaction?
Autonomous Transaction is a new feature in ORACLE. It allows setting up independent
transactions that can be called from within other transactions. It lets you suspend the main
transaction (without committing or rolling back), perform some DML operations, commit or roll
back those operations (without any effect on the main transaction), and then return to the main
transaction.
Being independent of the main transaction (almost like a separate session), an autonomous
transaction does not see the uncommitted changes from the main transaction. It also does not
share locks with the main transaction. As a result, it can get into a deadlock with its parent …
something the application developer should watch out for.
As expected, changes committed by an autonomous transaction are visible to other
sessions/transactions immediately, regardless of whether the main transaction is committed or
not. These changes also become visible to the main transaction when it resumes, provided its
isolation level is set to READ COMMITTED (which is the default).
Defining Autonomous Transactions
A transaction can be marked as autonomous by putting that transaction in a separate stored
procedure/function, or a packaged procedure/function, or a local procedure inside a stored
procedure, or a separate database trigger. Anonymous PL/SQL blocks and methods of SQL
object type can also be defined as autonomous transactions.
Any of these routines can be marked as autonomous simply by using the following syntax
anywhere in the declarative section of the routine (putting it at the top is recommended for better
readability):

PRAGMA AUTONOMOUS_TRANSACTION;
Here is an example of defining a stored procedure as autonomous:
CREATE PROCEDURE process_ord_line_shipment
(p_order_no number, p_line_no number) AS
PRAGMA AUTONOMOUS_TRANSACTION;
l_char_1 varchar2(100);
BEGIN
...
END;
There are two restrictions on the use of this PRAGMA: it cannot be used to mark ALL members of
a package as autonomous. Simple workaround: mark each member (proc/function) as
autonomous individually. Also, a nested PL/SQL block cannot be marked as autonomous. Again,
the workaround is not too bad: just make it a local procedure (or a separate stored procedure).
The called routine should have its own commit (or rollback). This is true even for a trigger (which
otherwise cannot have a commit or rollback statement). An attempt to exit without committing or
rolling back the changes results in an exception condition (and the pending changes are rolled
back as a result).
Advantages of Autonomous Transactions
Autonomous transactions are likely to be quickly embraced by PL/SQL developers. They would
find their use in many situations where some DML's needs to be saved regardless of whether or
main transaction commits or rolls back. Here are a few examples:
Transaction logging: A transaction needs to be logged for audit purposes even if it fails and
does not update any other data. An example of this is currently available under the
sample PL/SQL code section of the Technet website (technet.oracle.com).
Debugging (logging messages in an error-message table). The procedure to insert a
message into a debug table should be set up as an autonomous transaction so the
messages are saved even if the main transaction fails or rolls back.
Incrementing retry counters. It is very similar to the transaction-logging situation.
Apart from these technical needs, there is a significant advantage of using autonomous
transactions from the point of view of programming style and structure. Since autonomous
transactions can be committed or rolled back independent of the main transaction, it will facilitate
development of more modular programs.
Here is an example of debugging application (mentioned above) that demonstrates this very well:
Procedure debug_write(p_err_msg in varchar2,
p_proc in varchar2, …)
is
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
Begin
Insert into debug messages (err_msg, proc_name, …)
Values(p_err_msg, p_proc, …);
Commit;
Exception

end;
END;
Once set up this way, it is a modular piece of code that can be called from any
procedure/function/trigger without compromising the integrity of the calling transaction.
This is a great benefit and will surely make PL/SQL programming more fun.

PROCEDURE RETURNS RECORDSET COLLECTION

There are two ways of accessing recordset collection from procedure

1 USING PL/SQL TABLE TYPE ONLY


Each column value return as an collection seperatly.
The current version of microsoft provider for oracle
support this feature.
2 USING PL/SQL TABLE TYPE WITH RECORD
TYPE COLLECTIONS
The collection itself returning the collection of record set.
The current version of microsoft provider for oracle
doesn’t support this feature.
Execute the following file in your login :- Tables and Datas

1) USING PL/SQL TABLE TYPE ONLY

STEP DESCRIPTION

CREATE OR REPLACE PACKAGE PK_RETURN_RS


AS

TYPE TBL_ENO IS TABLE OF EMP.ENO%TYPE INDEX BY


BINARY_INTEGER;
Create package TYPE TBL_ENAME IS TABLE OF EMP.ENAME%TYPE INDEX
BY BINARY_INTEGER;
TYPE TBL_SAL IS TABLE OF EMP.SAL%TYPE INDEX BY
BINARY_INTEGER;
PROCEDURE GET_EMP_DETAILS(I_DNO IN DEPT.DNO%TYPE,
O_ENO OUT TBL_ENO, O_ENAME OUT TBL_ENAME,
O_SAL OUT TBL_SAL);

END PK_RETURN_RS;
/

CREATE OR REPLACE PACKAGE BODY PK_RETURN_RS


IS
PROCEDURE (I_DNO IN DEPT.DNO%TYPE,
O_ENO OUT TBL_ENO,O_ENAME OUT TBL_ENAME ,
O_SAL OUT TBL_SAL)
IS
Create Package CURSOR C1 IS SELECT ENO,ENAME,SAL FROM EMP
Body WHERE DNO=I_DNO;
CNT NUMBER DEFAULT 1;

BEGIN
FOR I IN C1
LOOP
O_ENO(CNT):=I.ENO;
O_ENAME(CNT):=I.ENAME;
O_SAL(CNT):=I.SAL;
CNT:=CNT+1;
END LOOP;
END GET_EMP_DETAILS;
END PK_RETURN_RS;
/

DECLARE
V_ENO PK_RETURN_RS.tbl_ENO;
V_ENAME PK_RETURN_RS.tbl_ENAME;
V_SAL PK_RETURN_RS.tbl_SAL;
V_DNO DEPT.DNO%TYPE := &DEPTNO;
BEGIN
Example of PK_RETURN_RS.GET_EMP_DETAILS(V_DNO,
calling Package V_ENO, V_ENAME,V_SAL);
using PL/SQL FOR K IN 1 .. V_ENO.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE(V_ENO(K));
DBMS_OUTPUT.PUT_LINE(V_ENAME(K));
DBMS_OUTPUT.PUT_LINE(V_SAL(K));
END LOOP;
END;
/

Private Sub Command1_Click()


Dim cnntest As New ADODB.Connection
Dim rstest As New ADODB.Recordset
Example of Dim Departnumber
calling Package
using VB With cnntest
.ConnectionString = Provider=MSDAORA.1;
Password=test;User ID=test;Data Source=test;
Persist Security Info=True"
.Open
End With
Departnumber = 10
strSQL = "{call PK_RETURN_RS.GET_EMP_DETAILS
(" & Departnumber & ",{resultset 10000,
O_ENO, O_ENAME,O_SAL})}"

SET rstest=CNNTEST.EXECUTE(STRSQL)
rstest.Open
Print "ENO :- " & rstest(0)
Print "ENAME :- " & rstest(1)
print "SAL :- " & rstest(2)
End Sub

2) USING PL/SQL TABLE TYPE WITH PLSQL RECORD TYPE

STEP DESCRIPTION

CREATE OR REPLACE PACKAGE PK_RETURN_RS


AS
TYPE REC_EMP IS RECORD(V_ENO EMP.ENO%TYPE,
V_ENAME EMP.ENAME%TYPE, V_SAL EMP.SAL%TYPE);
TYPE TBL_EMP IS TABLE OF REC_EMP INDEX BY
BINARY_INTEGER;
Create package PROCEDURE GET_EMP_DETAILS(I_DNO IN
NUMBER,DET_EMP OUT TBL_EMP);
END PK_RETURN_RS;
/

CREATE OR REPLACE PACKAGE BODY PK_RETURN_RS


IS
PROCEDURE GET_EMP_DETAILS(I_DNO IN NUMBER,
DET_EMP OUT TBL_EMP)
IS
CURSOR C1 IS SELECT ENO,ENAME,SAL FROM EMP
Create Package WHERE DNO=I_DNO;
Body CNT NUMBER DEFAULT 1;
BEGIN
FOR I IN C1
LOOP
DET_EMP(CNT).V_ENO:=I.ENO;
DET_EMP(CNT).V_ENAME:=I.ENAME;
DET_EMP(CNT).V_SAL:=I.SAL;
CNT:=CNT+1;
END LOOP;
END GET_EMP_DETAILS;
END PK_RETURN_RS;
/

DECLARE
Example of REC1 PK_RETURN_RS.TBL_EMP;
calling Package V_DNO NUMBER := &DNO;
BEGIN
using PL/SQL PK_RETURN_RS.GET_EMP_DETAILS(V_DNO,REC1);
FOR K IN 1 .. REC1.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE(REC1(K).V_ENO);
DBMS_OUTPUT.PUT_LINE(REC1(K).V_ENAME);
DBMS_OUTPUT.PUT_LINE(REC1(K).V_SAL);
END LOOP;
END;
/

Calling in VB There is no supported ole provider for accessing the TableType


containing Record type collections.

PACKAGE RETURN REF CURSOR


INTRODUCTION

This document gives a clear understanding of how to return recordsets through a


package and how to access the same from the Sql Prompt or from any Pl/Sql
block.

CREATION OF THE PACKAGE

Create the following package that returns a recordset for the input Sql. CREATE
OR REPLACE PACKAGE GL_PK_RETURN_CURSOR AS TYPE REF_CUR
IS REF CURSOR; PROCEDURE GL_PR_RETURN_CURSOR( IN_SQL
VARCHAR2, OUT_REF_CUR OUT REF_CUR); END
GL_PK_RETURN_CURSOR ; /

CREATE OR REPLACE PACKAGE BODY GL_PK_RETURN_CURSOR AS


PROCEDURE GL_PR_RETURN_CURSOR ( IN_SQL VARCHAR2,
OUT_REF_CUR OUT REF_CUR ) IS BEGIN OPEN OUT_REF_CUR FOR
IN_SQL; END GL_PR_RETURN_CURSOR ; END
GL_PK_RETURN_CURSOR ; /

In this package, a Ref Cursor type is defined and the package procedure returns
this type defined in the package as an OUT parameter. The Ref Cursor type that
is returned can be used in any Pl/Sql block or in the Sql Prompt and the records
stored in it can be retrieved, in much the same way as records are fetched from
any other cursor variable.

SAMPLE CALLS TO THE PACKAGE TO RETURN A CURSOR

Pre-Requisite:

Create the following table. create table EMP ( EMPNO NUMBER(4) not null, ENAME
VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL
NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2) );

From the Sql Prompt:

From the Sql Prompt, follow the 4 steps below to retrieve employee records through the
package.
1. SET SERVEROUTPUT ON
2. VAR X REFCURSOR
3. EXEC GL_PK_RETURN_CURSOR.GL_PR_RETURN_CURSOR('SELECT * FROM
EMP',:X);
4. PRINT X

From a Pl/Sql Block:

The following sample Pl/Sql Block can be used to retrieve the employee records through
the package.
DECLARE
V_SQLSTR VARCHAR2(4000);
V_EMP_CUR GL_PK_RETURN_CURSOR.REF_CUR;
V_EMP_ROW EMP%ROWTYPE;
BEGIN
V_SQLSTR:='SELECT * FROM EMP';
GL_PK_RETURN_CURSOR.GL_PR_RETURN_CURSOR(V_SQLSTR,V_EMP_CUR)
;
LOOP
FETCH V_EMP_CUR INTO V_EMP_ROW;
EXIT WHEN V_EMP_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Emp No : ' || V_EMP_ROW.EMPNO || ' | Emp Name : ' ||
V_EMP_ROW.ENAME || ' | Emp Sal : ' || V_EMP_ROW.SAL);
END LOOP;
END;
/

what is p-code and sourcecode ?


P-code is Pre-complied code stored in Public cache memory of System Global Area after
the Oracle instance is started, whereas sourcecode is a simple code of sp, package,
trigger, functions etc which are stored in Oracle system defined data dictionary. Every
session of oracle access the p-code which have the Execute permission on that objects.
Source code stored in user_objects data dictinary for user defined Store proc, Trigger,
Package, Function. DBA_object stores all the db objects in sp. DB. ALL_objects stores
all the db objects in sp. schema
What steps should a programmer should follow for better tunning of the PL/SQL
blocks?
Difference between procedure and function?
What is the use of ref cursor return type?
The main difference between procedure and function,function should return a
value.procedure need not
Ref cursor return type can be used when it's required that a procedure / function need to
return set of records.
How to return more than one value from a function?
What are the types of triggers?
What are the features of oracle 9i
we can return only one value at a time. if we want more then one value we directly assign
that value to the variable(ii)
Types of triggers(*) row level trigger(*) statement level trigger(*) Before Trigger(*)
After Trigger
we return one more than one value by using ref cursors.
The following are some of the new features of oracle 9i....
1. Flash Back Query
2. Function based indexes
3. Materialized view enhancement etc....
Is there any limitation on no. of triggers that ca...
12 triggers max
what is crosstab
to create a result set where the rows need to be columns, or vice versa. You need to
"pivot" rows into columns, or vice versa. this is where you need to look at a pivot (or
crosstab) query.
create table src_table
(col1 varchar2(10)
,col2 varchar2(10)
,col3 varchar2(10)
,col4 varchar2(10)
,col5 varchar2(10)
);
insert into src_table values ('A', 'B', 'C', null, null);
insert into src_table values (null, 'B', 'C', null, null);
insert into src_table values (null, 'B', null, null, null);

-- unordered
select ilv1.col_val
from
(
select
decode(ilv_dual.rnum, 1, src_table.col1
, 2, src_table.col2
, 3, src_table.col3
, 4, src_table.col4
, 5, src_table.col5
) col_val
from
src_table,
(select level rnum
from dual
connect by level <= 5
) ilv_dual
) ilv1
where ilv1.col_val is not null

-- ordered
select ilv1.col_val
from
(
select
src_table.rowid rid,
decode(ilv_dual.rnum, 1, src_table.col1
, 2, src_table.col2
, 3, src_table.col3
, 4, src_table.col4
, 5, src_table.col5
) col_val
from
src_table,
(select level rnum
from dual
connect by level <= 5
) ilv_dual
) ilv1
where ilv1.col_val is not null
order by ilv1.rid
/
What is the difference between all_ and user_ tabl...
An ALL_ view displays all the information accessible to the current user, including
information from the current user's schema as well as information from objects in other
schemas, if the current user has access to those objects by way of grants of privileges or
roles.
While A USER_ view displays all the information from the schema of the current user. No
special privileges are required to query these views.
Based on what conditions can we decide whether to use a table or a view or a
materialized view ?
Security reasons we can use view2. If there is a more transaction in a base table we better
chose materialised view for performance 3. Depend upon the situation where we need to
refresh the data in specific time interval.
Tables we used for entity information physically in our DB.
View is a virtual representation of table data, for security and hiding the table column
infor. we used normally view. we uses for Report & MIS purposes for showing the data
from more than two table.
Materalized view is used for remote data access and suitable for transaction related data
storage in distributed environment. It stores the data phyisically comparision to normal
view. It can refreshes the remote data auto. and forcefully/manually.
--if the refresh mode is Force
dbms_mview.refresh('Ashok_mview')
What are ref cursors ?
They are similar to a normal curson but they can have different select stmts at run time.
What is the difference between a reference cursor and normal cursor ?

REF cursors are different than your typical, standard cursors. With standard cursors, you
know the cursor's query ahead of time. With REF cursors, you do not have to know the
query ahead of time. With REF Cursors, you can build the cursor on the fly
Normal Cursor is a Static Cursor.
Refernce Cursor is used to create dynamic cursor.
There are two types of Ref Cursors:
1. Weak cursor and 2.Strong cursor
Type ref_name is Ref cursor [return type]
[return type] means %Rowtype
if Return type is mentioned then it is Strong cursor else weak cursor
The Reference cursor does not support For update clause.
Describe in brief some of the featurs of oracle9i....
LogMiner is a powerful audit tool for Oracle databases, allowing administrators to easily
locate changes in the database, enabling sophisticated data analyses, and providing undo
capabilities to rollback logical data corruptions or user errors.
Can e truncate some of the rows from the table instead of truncating the full table.
No , it is not possible. Truncate is a DDL Command and we can not where clause in
Truncate.
can i write plsql block inside expection
Yes you can write PL/SQL block inside exception section. Suppose you want to insert the
exception detail into your error log table, that time you can write insert into statement in
exception part. To handle the exception which may be raised in your exception part, you
can write the PL/SQL code in exception part.
What is PL/SQL table?

SNO MARK
------- ------------------
1 59
2 40
3 ‘A’
4 60
Write a single query to I) Sorted Marks II)First mark III) replace the mark ‘A’ with
0(zero)?

Pl/Sql table is a type of datatype in procedural language Extension.It has two


columns.One for the index,say Binary index And another column for the datas,which
might further extend to any number of rows (not columns)in future.
I)sort marksSelect * form TABLE order by MARK;II)First Markhighest mark or first
mark in table.Highest: Select Max(Mark) from TABLE;First: Select Mark from TABLE
where rownum = 1III)replace mark 'A' with 0(zero)update TABLE set MARK = 0 where
MARK = 'A';
Can any one explain Perforance Tuning in PL/SQL
The different aspects of tuning PL/SQL are
Analyzing program performance.
Tuning access to compiled code.
Tuning access to your data.
Tuning your algorithms.
Major tools are
MONITOR SQL_TRACE and TKPROF EXPLAIN PLAN ORADBX ANALYZE
UTLBSTAT (begin) and UTLESTAT (end) Enterprise Manager/Performance Pack
What happens when a package is initialized ?
when a package is initialised that is called for the first time the entire package is loaded
into SGA and any variable declared in the package is initialises.
What are the restrictions on Functions ?
(1).Only in parameters are allowed.No inout & out parameters are allowed.
(2).A DML statement containing a function cannot perform another DML operation on
the same table.
We can use IN and IN OUT parameters with function, in Oracle 9i ver. 9.2. See below,
create or replace function f1 (num in out number) return number
as
begin
dbms_output.put_line ('Inside f1 num='||num);
num:=100;
return 10;
end;
/
declare
n1 number := 1;
begin
dbms_output.put_line('return val='||f1(n1));
dbms_output.put_line('out param='||n1);
end;
/
What type of binding is PL/SQL?
The assigning of values to PL/SQL variables in SQL statements is called binding.
PL/SQL binding operations fall into three categories:
 in-bind
 out-bind
 define
A DML statement can transfer all the elements of a collection in a single operation, a
process known as bulk binding. If the collection has 20 elements, bulk binding lets you
perform the equivalent of 20 SELECT, INSERT, UPDATE, or DELETE statements using
a single operation. This technique improves performance by minimizing the number of
context switches between the PL/SQL and SQL engines. With bulk binds, entire
collections, not just individual elements, are passed back and forth.
Why Functions are used in oracle ?
Can Functions Return more than 1 values?
Why Procedures are used in oracle ?
What are the Disadvantages of packages?
What are the Global Variables in Packages?
1) A function will return a value, adding to that , it is possible to use a function in SQL
statements, whereas procedures cannot be used.2)No, functions cannot retrun more than
one value, instead one can get this done in other way round by using OUT parameters for
a function.3)To perform validations and transactions on database tables.4)Memory usage
is more.5)The variable defined inside Package Specification are treated as Global
variables, which can be referred externally
What is bulk binding please explain me in brief ?
Bulk Binds (BULK COLLECT , FORALL ) are a PL/SQL technique where, instead of
multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to
retrieve from, or store data in, at table, all of the operations are carried out at once, in
bulk.
This avoids the context-switching you get when the PL/SQL engine has to pass over to
the SQL engine, then back to the PL/SQL engine, and so on, when you individually
access rows one at a time. To do bulk binds with Insert, Update and Delete statements,
you enclose the SQL statement within a PL/SQL FORALL statement.
To do bulk binds with Select statements, you include the Bulk Collect INTO a collection
clause in the SELECT Statement instead of using Simply into .
Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and
10g PL/SQL that can really make a different to you PL/SQL performance
Bulk Binding is used for avoiding the context switching between the sql engine and pl/sql
engine. If we use simple For loop in pl/sql block it will do context switching between
sql and pl/sql engine for each row processing that degrades the performance of pl/sql
bloack.
So that for avoiding the context switching betn two engine we user FORALL keyword by
using the collection pl/sql tables for DML. forall is pl/sql keyword.
It will provides good result and performance increase.
Can we use commit or rollback command in the exception part of PL/SQL block?
Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored
procedure/function. The code in this part of the program gets executed like those in the
body without any restriction. You can include any business functionality whenever a
condition in main block(body of a proc/func) fails and requires a follow-thru process to
terminate the execution gracefully!
Yes we can use commit/rollback in exception part. Example:
DECALRE
BEGIN
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO err_log(
err_code, code_desc)
VALUES(‘1403’, ‘No data found’)
COMMIT;
RAISE;
END
What is the output of the following pl/sql block ?
declare
v_empno emp.empno%type;
begin
select empno into v_empno from emp where empno = 10;
exception
when others then
dbms_output.put_line ( 'no data found');
when no_data_found then
dbms_output.put_line ( 'ther is no data found ');
end;
when others then
*
ERROR at line 6:
ORA-06550: line 6, column 2:
PLS-00370: OTHERS handler must be last among the exception handlers of a block
ORA-06550: line 0, column 0:
PL/SQL: Compilation unit analysis terminated
always when others exception should be the last exception handling in sequence.
Talk about "Exception Handling" in PL/SQL?
Exception handing allow developer to raise and handle the error . Each SQL block have
it's own exception block. when a error occur than excution immediatly terminates . And
control pass to exeption section.
There are 2 types of Exception Handlers:ORACLE defined(Named Exception Handler
and Numbered Exception Handler) and User Defined Exceptions.
Named Exceptions : examples- LOGIN_DENIED,TOO_MANY_ROWS etc.
Numbered Exceptions: There are about 20 K numbered exceptions, one can overwrite
these numbered exception such that instead of showing a number for the raised exception,
user specifed EXCEPTION_NAME will be shown.
User Defined: These are the exceptions defined and raised by user code. This includes
Business Rule validations like (Amount < 0) etc.
What is Data Concarency and Consistency?
Data Concarency => Means that many users can access data at the same time.
Data Consistency => Means that each user sees a consistent view of the data, including
visible changes made by the user's own transactions and transactions of other users.
Concurrency
How well can multiple sessions access the same data simultaneously
Consistency
How consistent is the view of the data between and within multiple sessions,
transactions or statements
Is it possible to use Transaction control Statements such a ROLLBACK or
COMMIT in Database Trigger ? Why ?
It is not possible. As triggers are defined for each table, if you use COMMIT of
ROLLBACK in a trigger, it affects logical transaction processing.
Generally In triggers you can't use TCL commands.
But you can use TCL commands in Autonomous Triggers.
You can declare a trigger as Autonomous by providing PRAGMA
AUTONOMOUS_TRANSACTION in the beginning of the trigger.
At a same time you have to end your trigger with commit/rollback.
You can use these type of triggers to maintain log details of a table.
What is Overloading of procedures ?
The Same procedure name is repeated with parameters of different datatypes and
parameters in different positions, varying number of parameters is called overloading of
procedures.
e.g. DBMS_OUTPUT put_line
What are % TYPE and % ROWTYPE ? What are the advantages of using these
over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or
columns selected in the cursor.
The advantages are : I. Need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable
changes accordingly.
Advantage is, if one change the type or size of the column in the table, it will be reflected
in our program unit without making any change.
What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type
);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
What is PL/SQL table ?
Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the
same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one
column and a primary key
Pl/SQL tables are the row, column structure as of the table but cannot perform any select
query on the pl/sql tables because the data isfrom fetched only by the indexes like
--- store empno, ename from emp table thru cursor to pl/sql tables.
declare
type ty_plsql is record ( empno number, ename varchar2(50));
ty_plsql1 ty_plsql;
cursor c is select empno,ename from emp;
begin
for i in c loop
ty_plsql(i).empno := i.empno;
ty_plsql(i).ename := i.ename;
end loop;
end;
PL/SQL table is a one-dimensional, unbounded, sparse collection of homogenous
elements, indexed by integers
One-dimensional
A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional
array.
Unbounded or Unconstrained
There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table
grows dynamically as you add more rows to the table. The PL/SQL table is, in this way,
very different from an array.
Related to this definition, no rows for PL/SQL tables are allocated for this structure when
it is defined.
Sparse
In a PL/SQL table, a row exists in the table only when a value is assigned to that row.
Rows do not have to be defined sequentially. Instead you can assign a value to any row in
the table. So row 15 could have a value of `Fox' and row 15446 a value of `Red', with no
other rows defined in between.
Homogeneous elements
Because a PL/SQL table can have only a single column, all rows in a PL/SQL table
contain values of the same datatype. It is, therefore, homogeneous.
With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is
still, however, homogeneous. Each row simply contains the same set of columns.
Indexed by integers
PL/SQL tables currently support a single indexing mode: by BINARY_INTEGER. This
number acts as the "primary key" of the PL/SQL table. The range of a
BINARY_INTEGER is from -231-1 to 231-1, so you have an awful lot of rows with
which to work
Keep the following restrictions in mind when you work with PL/SQL tables:
 There is no concept of transaction integrity with PL/SQL tables. You cannot
commit information to a PL/SQL table or roll back changes from the table.
 You cannot SELECT from PL/SQL tables. There is no way to perform set-at-a-
time processing to retrieve data from a PL/SQL table. This is a programmatic
construct in a programmatic language. Instead you can use PL/SQL loops to move
through the contents of a PL/SQL table, one row at a time.
 You cannot issue DML statements (INSERTs, UPDATEs, and DELETEs) against
PL/SQL tables (though PL/SQL Release 2.3 does offer a DELETE operator).
What is a cursor ? Why Cursor is required ?
Cursor is a named private SQL area from where information can be accessed. Cursors are
required to process rows individually for queries returning multiple rows.
cursor retrive data from a table. it can be done in two level
1 %type it retrive data from a particular row
2 %rowtype it retrive data from a full table
Cursor is a handler or pointer to Oracle Context Area.Context area is a memory space
used for processing of sql statements.
Cursor is a named private SQL area also called as context area from where information
can be accessed. Cursors are required to process rows individually for queries returning
multiple rows. there are three types of cursors
1. Static Cursor
* Implicit Cursor
* Explicit Cursor
2. Dynamic Cursor
3. Reference Cursor
Explain the two type of Cursors ?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.
implicit cursor: implicit cursor is a type of cursor which is automatically maintained by
the Oracle server itself.implicit cursor returns only one row.
Explicit Cursor: Explicit Cursor is defined by the Proframmer,and it has for
phases:declare,open,fetch and close.explicit Cursor returns more than one row.
What will happen after commit statement ?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;-----
commit;
end loop;
end;
The cursor having query as SELECT .... FOR UPDATE gets closed after
COMMIT/ROLLBACK.
The cursor having query as SELECT.... does not get closed even after
COMMIT/ROLLBACK.
The cursor having query will get closed, because once the for update clause is fired it
locks all the rows which is been modified and once it encounters a commit/rollback it
automatically comes out of that session, and will be processing a fresh loop altogether.
The changes will be permanently written to hard disk. No undo(rollback) is possible.
Explain the usage of WHERE CURRENT OF clause in cursors ?
WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest
row fetched from a cursor.
Database Triggers
PL/SQL provides the WHERE CURRENT OF clause for both UPDATE and DELETE
statements inside a cursor in order to allow you to easily make changes to the most
recently fetched row of data.
The general format for the WHERE CURRENT OF clause is as follows:
UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name;DELETE
FROM table_name WHERE CURRENT OF cursor_name;Notice that the WHERE
CURRENT OF clause references the cursor and not the record into which the next
fetched row is deposited.
The most important advantage to using WHERE CURRENT OF where you need to
change the row fetched last is that you do not have to code in two (or more) places the
criteria used to uniquely identify a row in a table. Without WHERE CURRENT OF, you
would need to repeat the WHERE clause of your cursor in the WHERE clause of the
associated UPDATEs and DELETEs. As a result, if the table structure changes in a way
that affects the construction of the primary key, you have to make sure that each SQL
statement is upgraded to support this change. If you use WHERE CURRENT OF, on the
other hand, you only have to modify the WHERE clause of the SELECT statement.
This might seem like a relatively minor issue, but it is one of many areas in your code
where you can leverage subtle features in PL/SQL to minimize code redundancies.
Utilization of WHERE CURRENT OF, %TYPE, and %ROWTYPE declaration
attributes, cursor FOR loops, local modularization, and other PL/SQL language
constructs can have a big impact on reducing the pain you may experience when you
maintain your Oracle-based applications.
Let's see how this clause would improve the previous example. In the jobs cursor FOR
loop above, I want to UPDATE the record that was currently FETCHed by the cursor. I
do this in the UPDATE statement by repeating the same WHERE used in the cursor
because (task, year) makes up the primary key of this table:
WHERE task = job_rec.task AND year = TO_CHAR (SYSDATE, 'YYYY');This is a
less than ideal situation, as explained above: I have coded the same logic in two places,
and this code must be kept synchronized. It would be so much more convenient and
natural to be able to code the equivalent of the following statements:
Delete the record I just fetched.
or:
Update these columns in that row I just fetched.
A perfect fit for WHERE CURRENT OF! The next version of my winterization program
below uses this clause. I have also switched to a simple loop from FOR loop because I
want to exit conditionally from the loop:
DECLARE CURSOR fall_jobs_cur IS SELECT ... same as before ... ; job_rec
fall_jobs_cur%ROWTYPE;BEGIN OPEN fall_jobs_cur; LOOP FETCH
fall_jobs_cur INTO job_rec; IF fall_jobs_cur%NOTFOUND THEN EXIT;
ELSIF job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN UPDATE
winterize SET responsible = 'STEVEN' WHERE CURRENT OF fall_jobs_cur;
COMMIT; EXIT; END IF; END LOOP; CLOSE fall_jobs_cur;END;
What is a database trigger ? Name some usages of database trigger ?
Database trigger is stored PL/SQL program unit associated with a specific database table.
Usages are Audit data modifications, Log events transparently, Enforce complex business
rules Derive column values automatically, Implement complex security authorizations.
Maintain replicate tables.
A database trigger is a stored procedure that is invoked automatically when a predefined
event occurs.
Database triggers enable DBA's (Data Base Administrators) to create additional
relationships between separate databases.
For example, the modification of a record in one database could trigger the modification
of a record in a second database.
How many types of database triggers can be specified on a table ? What are they ?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the
statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
There are five types of database triggers
Row Level Trigger
Statement Level Trigger
Instead of Trigger
Schema Trigger
Database Trigger
Out of these five types of triggers Only two are used for the table purpose, i.e. two row
level trigger and statement level triggers are used for insert, update or/and delete
operation on table
What are two virtual tables available during database trigger execution ?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values
only available.
For triggers related to DELETE only OLD.column_name values only available.
What happens if a procedure that updates a column of table X is called in a
database trigger of the same table ?
Mutation of table occurs.
To avoid the mutation table error ,the procedure should be declared as an
AUTONOMOUS TRANSACTION.
By this the procedure will be treated as an separate identity.
What is Pragma EXECPTION_INIT ? Explain the usage ?
The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an
oracle error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
Pragma exception_init Allow you to handle the Oracle predefined message by you'r own
message. means you can instruct compiler toassociatethe specific message to oracle
predefined message at compile time.This way you Improve the Readbility of your
program,and handle it accoding to your own way.
It should be declare at the DECLARE section.
example
declare
salary number;
FOUND_NOTHING exception;
Pragma exception_init(FOUND_NOTHING ,100);
begin
select sal in to salaryfrom emp where ename ='ANURAG';
dbms_output.put_line(salary);
exception
WHEN FOUND_NOTHING THEN
dbms_output.put_line(SQLERRM);
end;
What are the return values of functions SQLCODE and SQLERRM ?
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.
Pl / Sql Provides Error Information via two Built-in functions, SQLCODE &
SQLERRM.
SQLCODE Returns the Current Error Code.
Returns 1.
SQLERRM Returns the Current Error Message Text.
Returns " User Defined Exception "
Name the tables where characteristics of Package, procedure and functions are
stored ?
User_objects, User_Source and User_error.
What are two parts of package ?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and local to
the schema.
Package Body contains actual procedures and local declaration of the procedures and
cursor declarations.
What is Raise_application_error ?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to
issue an user_defined error messages from stored sub-program or database trigger.
Where the Pre_defined_exceptions are stored ?
In the standard package.
Procedures, Functions & Packages ;
What are advantages fo Stored Procedures
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.
If the large table contains thousands of records and the application is accessing 35%
of the table w
FULL TABLE for more than 15% row access.
How do you increase the performance of %LIKE operator
The wildcard char % can be placed in one of three ways:

%searchwordhere%
searchwordhere%
%searchwordhere

The searchwordhere% is the fastest because it can use an index if one is specified on that
column. The other two %searchwordhere%, and %searchwordhere would never use the
index even if one is specified and thus result in slow table scans.
In which situation whether peak time or off peak time you will execute the
ANALYZE TABLE command. Why
You have to run the analyze command during off peak time only because it actually
performs full table scan.
How to do the scheduled task/jobs in Unix platform

cron job feature in unix.


Explain psudo column Label with an example
Pseduo columns are columns which have special meaning. Though we do not define in
create table but we can access those columns in our queries like
ROWNUM,
ROWID,
NEXTVAL,
CURRVAL,
What is the difference between single quote (') an...
single quote is used to write a character string or character in sql query.
but,double quotes are used to print the name in sql screen.
for eg:-
select sysdate "current date" from dual;
current date
-----------------
24-mar-06.
in single quote oracle takes the character as a keyword.
how to delete set of records at a time where all t...
yes you can delete the duplicate records with the help of a sql query as follows
delete from table_name where rowid not in(select max(rowid) from table_name group by
field_name)
in this way only rowid with distinct values will remain and the rest will be removed.I
hope it will help you out.
what is the difference between ROWNUM and ROWID
the ROWNUM is a number(like serial no) which is dynamically changes.but the ROWID
does not change.Because it is having the unique address,which is generated by the oracle
rownum is a pseudo column. It numbers the records in a result set. The first record that
meets the where criteria in a select statement is given rownum=1, and every subsequent
record meeting that same criteria increases rownum.
A rowid is a pseudo column, that uniquely identifies a row within a table, but not within a
database. It is possible for two rows of two different tables stored in the same cluster to
have the same rowid.
How to get first 5 Records then next 5 records til...
Use ROWNUM to get the rows, one set after the other as mentioned in the question
We can get the first 5 records by the following sql:(Let the table is emp)
select * from emp where rownum<6
Then we can get the next 5 records by the following sql:
select * from emp where rownum<6 MINUS select * from emp where rownum<11
and so on...
It should be:Select * from emp where rownum<6;thenSelect * from emp where
rownum<11 MINUS select * from emp where rownum <6;and so on
is there any way we can change the column name in ...
We can change the column name of the table
that is available in oracle 9i.
alter table tablename rename column column1 to column2;
To find the two minimum salaries among table
select min(sal) from emp union select min(sal) from (select sal from emp where
sal>(select min(sal) from emp));
Following SQL returns nth ranked salary from emp table
select * from (select rownum rn,sal from (select distinct sal From emp order by sal desc))
where rn = 13
by changing the = sign to < will return the top n ranked salaries from emp
select * from (select rownum rn,sal from (select distinct sal From emp order by sal desc))
where rn < 13
select sal from (select * from <table_name> order by sal asc) where rownum < 3
This Query returns duplicate value.
select sal from (select * from <table_name> order by sal asc) where rownum < 3
This Query retuns only the second minimum salary
Select min(salary) from <Table Name> where Salary>(Select min(salary) from <Table
Name>)
Whereas the following Query returns the distinct first two minmum salary in a table
Select min(salary) from <Table Name> union
Select min(salary) from <Table Name> where salary>(Select min(salary) from <Table
Name>)
select sal from (select distinct sal from emp order by sal asc) where rownum < 3;
SELECT TOP 2 sal FROM emp ORDER BY sal ASC
How many codd's rules are supporting by the oracle?.Plz clarify this.
twelve rules has introduced by Fcodd,but oracle support 11 rules.
The 12 codd rule which oracle does not satisfy is
Codd rule says view should be updatable , but views in oracle
are updatable but with constraints i.e two tables are joined to form a view
11 rules is supported out of 12.
the only oracle datbase that support maximum rules.
oracle supports 11 codd rules out of 12
view updatation is not support always
view updation is suuported as some extent
what is the differences between Oracle8i and 9i?
I would like to add some more differences b/w 8i and 9i
1. Column rename is not possible in 8i
2. We dont have CUBE and ROLLUP functions in 8i
3. We dont have merge statement in 8i
4. We dont have the datatype timestamp with local timezone in 8i
5. From DBA Side - We cannot dynamically set the size of sga in 8i without shutting
down the instance
and lots more
difference are -
sql level - cube , rollup, case expression , insert all , merge,list partition
dba level - dynamically u can add parameter in pfile /spfile without restarting the
database
example alter system set db_block_buffer=value scope=/path/spfile
new parameter db_block_buffer instead of db_buffer_cache in oracle 8i
UNDO table space management,
while creating user in 9i automatically considered in temp tablespace
while adding datafile in temp tablespace
u have to add alter tablepace temp add "tempfile " instead of datafile
table next extent is auto management , pctfree and pctused we can use along with table
creation .
stat pack is the new performnce monitaring tool .
u can moniter inedx using alter index indexname monitering usage
or new table user_objects for index.
how to get the prime number rows from table ie like1,3,5,7,11

select * from table_name where (rowid,1) in ( select rowid,mod(rownum,2) from


table_name )
select empno, ename, rn
from (select e.*, row_number() over (order by empno asc) rn
from emp )
where mod(rn, 2)=1;
how to get 1,4,7,10.....rows from a table
select * from yet where (rowid,1) in (select rowid, mod(rownum,3)from yet);
Assume Test table with following values
COL1
----------
1
2
5
6
1
8
4
12
Using inline views,
select a.rr,a.col1
from (select rownum rr,mod(rownum,3) rn,col1 from test) a
where a.rn=1
output
RR COL1
---------- ----------
11
46
74
where we use nested tables in our real time
nested table is the example of reusable of objects we can create one object type and we
can use that object_type and create many tables on that object_type
maxvalue.sql Select the Nth Highest value from a table
select level, max('col_name') from my_table where level = '&n' connect by prior
('col_name') >
'col_name')
group by level;
Example:
Given a table called emp with the following columns:
-- id number
-- name varchar2(20)
-- sal number
--
-- For the second highest salary:
-- select level, max(sal) from emp
-- where level=2
-- connect by prior sal > sal
-- group by level
Nth Max value in a table

For Exaple A Table ABC

Salay
------
10
20
30
40

I Need the Nth Max Salary of the Table ABC.


SELECT *
FROM TableName E1
WHERE (N =
(SELECT COUNT(DISTINCT (E2.sal))
FROM TableName E2
WHERE E2.sal >= E1.sal))
this is one of the ways to find out the Nth highest salary :select * from(select salary,rank()
over(order by salary desc) as r from (select distinct salary from employees)) where
r=&Ntry out this...
What are various constraints used in SQL?
There are five classes of constraints:

NOT NULL. Specifies that a column does not accept nulls.


PRIMARY KEY. Specifies the column or columns whose values uniquely identify a row
in a table. Primary key columns are automatically NOT NULL.
UNIQUE. Specifies that a column has all unique values.
CHECK. Limits the domain of acceptable values for a column.

FOREIGN KEY. Aka a DRI constraint (Declarative Relational Integrity). Identifies


relationships between tables. A foreign key in a table points to a candidate key (usu. a
primary key) in another table. A table can have up to 253 FOREIGN KEY contraints
Differentiate between TRUNCATE and DELETE

TRUNCATE DELETE

It is a DDL statement It is a DML statement

It is a one way trip,cannot ROLLBACK One can Rollback

Doesn't have selective features (where clause) Has

Doesn't fire database triggers Does

It requires disabling of referential constraints. Does not require

Display the number value in Words?


SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
Here the 'j' used as a format in to_date function return the number in julian year.Whereas
the 'jsp' used in to_char made the julian year spelled out.
i.e. j-julian year and sp-spelling so jsp.
Suppose there are two fields in table(Employee) say Name and Salary and there are
in total 100 records in table. Now my query gives the name of an employee whose
salary is 10th among 100 salaries. this query should be solve in SQL not in PL/SQL
ans: the command will be:

select name,salary from employee where rowid=( select Max(rowid) from employee
where rownum<=10);

SELECT DISTINCT (a.sal) FROM EMP A WHERE 10 = (SELECT COUNT


(DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Did u mean 10th Max salary among the 100 employees, then your query should be
Select min(sal) from (Select sal from (select sal from emp order by sal desc) where
rownum <= &n)
select ename,salary from (select sal from employee order by sal desc) where rownu=&n;
select ename,sal from (select ename,sal from (select ename,sal from emp order by sal
desc) where rownum < 11 order by sal asc) where rownum = 1
The minus query hits the table more times so a bit of performance concern
How to eliminate duplicate rows from a table leaving one from the duplicates?
DELETE (or SELECT *) FROM TABLE1 TABLE1_ALIAS1
WHERE EXISTS (SELECT 1 FROM TABLE1 TABLE1_ALIAS2
WHERE TABLE1_ALIAS1.FIELD1 = TABLE1_ALIAS2.FIELD1
AND TABLE1_ALIAS1.ROWID < TABLE1_ALIAS2.ROWID)
ORDER BY FIELD1;
delete from table where (duplicate value field,rowid) not in (select duplicate value
field,max(rowid) from table group by duplicate_value_field)

DELETE FROM table_name A WHERE ROWID > ( SELECT min(rowid) FROM


table_name B WHERE A.key_values = B.key_values);
or

one can create a table2 from the existing table1 by selecting distinct values and dropping
the table1.

What are various joins used while writing SUBQUERIES?


Self join-Its a join foreign key of a table references the same table. Outer Join--Its a join
condition used where One can query all the rows of one of the tables in the join condition
even though they don't satisfy the join condition.
Equi-join--Its a join condition that retrieves rows from one or more tables in which one or
more columns in one table are equal to one or more columns in the second table.
Correlated sub query is one of the best example to be used in the sub queries to join the
tables. We may be having equi, non-equi, outer joins, however when we talk about joins
in the sub queries,correlated is best suited example.
Can data be inserted/deleted/updated from CLOB,BLOB,NCLOB columns.If not
why?
Yes it possible to insert/update/delete data for CLOB, BLOB, NCLOB columns. Now
how to do it.

1. Suppose if you are using JAVA applications to modify the database columns, then you
have to open streaming connections to write data for these columns where the streaming
connections can be ASCII as well as Binary connections. See the java docs for that.
2. From SQL plus it not possible to write as max value that can be written is 4000 chars.
3. From PL/SQL you have to use the dbms_lob.writeappend packages for inserting data.

The User Defined TYPE can contain these datatypes CLOB,BLOB,NCLOB be part of
user defined records or datatype by record i mean
type rec_blob is record( l_str clob);

Difference Between Hash Join & Merge Join

Merge Join :

Oracle performs a join between two sets of row data using the merge
join algorithm. The inputs are two separate sets of row data. Output is
the results of the join. Oracle reads rows from both inputs in an
alternating fashion and merges together matching rows in order to
generate output. The two inputs are sorted on join column.

Hash Join :

Oracle performs a join between two sets of row data using hash join
algorithm. Input and Output same as Merge Join. Oracle reads all rows
from the second input and builds a hash structure (like has table in
java), before reading each row from the first input one at a time. For
each row from the first input, the hash structure is probed and matching
rows generate output.
Difference between Optimizer=ALL_ROWS and Optimizer=CHOOSE
Choose - Choose either Rule based or Cost based depend on the
availability of statistics. If statistics is available on the table it uses
CBO and if not it uses RBO.

ALL_ROWS - Choose based optimization, statistics is needed. U could


pass as hint in ur query.

But in the majority of cases with optimizer_mode=choose ( and with a good


statistics ) the CBO will be able to find a good execution plan for
yoursqueries .
What is the purpose of a cluster?
Oracle does not allow a user to specifically locate tables, since that is a part of the
function of the RDBMS. However, for the purpose of increasing performance, oracle
allows a developer to create a CLUSTER. A CLUSTER provides a means for storing data
from different tables together for faster retrieval than if the table placement were left to
the RDBMS.
What is a view ?
A view may also be defined as custom-tailored (data presented to meet requirement)
presentation of data from more than one table
A view is stored inside the database as a select query.
It does not have any data of its own but it only fetches data from base tables by executing
the query written at the time of its creation
A view is stored procedure based on one or more tables, it’s a virtual table.
What is difference between UNIQUE and PRIMARY KEY constraints?
A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys. The columns that compose PK are automatically define NOT NULL,
whereas a column that compose a UNIQUE is not automatically defined to be mandatory
must also specify the column is NOT NULL.
Primay Key Unique key
----------- ------------------
There is only one there may be more than 1
Primary key for Unique Key in table
1 table
It can not contain It Can contain Null Value
Null value
Primary key creates clustered index whereas unique key creates non clustered
index.primary key won't allow NULL values whereas unique key allows NULL values.
Which is more faster - IN or EXISTS?
EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN
returns a value.
What is a OUTER JOIN?
Outer Join--Its a join condition used where you can query all the rows of one of the tables
in the join condition even though they don’t satisfy the join condition.
Which datatype is used for storing graphics and images?
LONG RAW data type is used for storing BLOB's (binary large objects).
How you will avoid your query from using indexes?
SELECT * FROM emp
Where emp_no+' '=12345;
i.e you have to concatenate the column name with space within codes in the where
condition.
SELECT /*+ FULL(a) */ ename, emp_no from emp
where emp_no=1234;
i.e using HINTS
Write a statement without WHERE clause. This will avoid a query from using indexes.
What is a pseudo column. Give some examples?
It is a column that is not an actual column in the table.
eg USER, UID, SYSDATE, ROWNUM, ROWID, NULL, AND LEVEL.
Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
Output:-
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
Output:-
2
4
6
ODD ROWS:-
SELECT * FROM emp WHERE ROWID IN ( SELECT
DECODE(MOD(ROWNUM,2),1,ROWID) FROM emp );
EVEN ROWS:-
SELECT * FROM emp WHERE ROWID IN ( SELECT
DECODE(MOD(ROWNUM,2),0,ROWID) FROM emp );
How do you find the numbert of rows in a Table ?
A bad answer is count them (SELECT COUNT(*) FROM table_name)
A good answer is :-
'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by
querying Oracle System Catalogues (e.g. USER_TABLES or ALL_TABLES).
The best answer is to refer to the utility which Oracle released which makes it
unnecessary to do ANALYZE TABLE for each Table individually.
What should be the return type for a cursor variable.Can we use a scalar data type
as return type?
The return type for a cursor must be a record type.It can be declared explicitly as a user-
defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR
RETURN students%ROWTYPE
Can cursor variables be stored in PL/SQL tables.If yes how. If not why?
No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL
table.
What is difference between a formal and an actual parameter?
The variables declared in the procedure and which are passed, as arguments are called
actual, the parameters in the procedure declaration. Actual parameters contain the values
that are passed to a procedure and receive results. Formal parameters are the placeholders
for the values of actual parameters
What are ORACLE PRECOMPILERS?
Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be
contained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1
AND ADA.
The Precompilers are known as Pro*C,Pro*Cobol,...
This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql is
embedded is known as the host language. The prcompiler translates the embedded SQL
and pl/sql ststements into calls to the precompiler runtime library.The output must be
compiled and linked with this library to creater an executable.
What is OCI. What are its uses?
Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No
precompiler is required,PL/SQL blocks are executed like other DML statements. The OCI
library provides
 -functions to parse SQL statemets
 -bind input variables
 -bind output variables
 -execute statements
 -fetch the results
What is an UTL_FILE.What are different procedures and functions associated with
it?
UTL_FILE is a package that adds the ability to read and write to operating system files.
Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output
data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT,
FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN,
ISOPEN.
What is the maximum buffer size that can be specified using the
DBMS_OUTPUT.ENABLE function?
1,000,00
what is the difference between cursor and ref cursor?
technically, under the covers, at the most "basic level", they are the
same.

A "normal" plsql cursor is static in defintion.

Ref cursors may be dynamically opened or opened based on logic.

Declare
type rc is ref cursor;

cursor c is select * from dual;

l_cursor rc;
begin
if ( to_char(sysdate,'dd') = 30 ) then
open l_cursor for 'select * from emp';
elsif ( to_char(sysdate,'dd') = 29 ) then
open l_cursor for select * from dept;
else
open l_cursor for select * from dual;
end if;
open c;
end;
/

Given that block of code -- you see perhaps the most "salient"
difference -- no
matter how many times you run that block -- cursor C will always be
select *
from dual. The ref cursor can be anything.

Another difference is a ref cursor can be returned to a client. a plsql


"cursor
cursor" cannot be returned to a client.

Another difference is a cursor can be global -- a ref cursor cannot (you


cannot
define them OUTSIDE of a procedure / function)

Another difference is a ref cursor can be passed from subroutine to


subroutine
-- a cursor cannot be.

Another difference is that static sql (not using a ref cursor) is much
more
efficient then using ref cursors and that use of ref cursors should be
limited
to
- returning result sets to clients
- when there is NO other efficient/effective means of achieving the goal

that is, you want to use static SQL (with implicit cursors really) first
and use
a ref cursor only when you absolutely have to

Then sit back and say "anything else you wanted to know about them"
Aliases:
An alias in oracle is another name used for a column or a table inside SELECT query.
They are accessible only inside the query where they are created. Once the query
execution is over alias will perish. An alias can be a single word or can be more than one
word. If alias used is more than one word it must be enclosed in double quotes
example:
current_date or "current date"
Student_name or "Student name"
Aliases are used in places when ever there is multiple usage of longer table names.
example :
STUDENT_MASTER_RECORD can be aliased as SMR
ACCOUNT_MASTER_TABLE as AMT .

There are 2 types of aliases


i) Table alias : It is another name used to refer the table within the
query.
example :
SQL> SELECT ENAME , SAL FROM EMP E WHERE E.DEPTNO = 10;
In the above query "E" is an alias for EMP.

ii) column alias


SQL> SELECT SYSDATE "Current Date" FROM DUAL;
"Current Date" is an alias.
Working Wih Multiple Tables
To retrieve desired data from more than one table we use join.
We will have more than one table name after FROM key word in
SELECT statement. A SELECT statement on multiple tables without
a proper JOIN condition will lead to a cartesian product.(i.e.
No.Of Output rows = No.of rows in table1 X No of rows in table2....)
No of join conditions = No of tables joined - 1
Types Of Joins:
1) EQUI JOIN: The equi join is normally used to join tables with primary key foreign
key relation ships.
Example :
SQL> SELECT ENAME,JOB,DEPTNO FROM EMP;
ENAME JOB DEPTNO
---------- --------- ----------
SMITH CLERK 20
ALLEN SALESMAN 30
WARD SALESMAN 30
JONES MANAGER 20
MARTIN SALESMAN 30
BLAKE MANAGER 30
CLARK MANAGER 10
SCOTT ANALYST 20
KING PRESIDENT 10
TURNER SALESMAN 30
ADAMS CLERK 20
JAMES CLERK 30
FORD ANALYST 20
MILLER CLERK 10
-------------------------------------
SQL> SELECT DEPTNO,DNAME,LOC FROM DEPT;

DEPTNO DNAME LOC ---- ----------- -------------------


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
To display ENAME of EMP table ,DNAME of DEPT table we need to join those tables
as shown below.
SQL> SELECT E.DEPTNO , ENAME , DNAME FROM EMP E, DEPT D
WHERE E.DEPTNO=D.DEPTNO;
DEPTNO ENAME DNAME
-------- ---------- --------------
10 CLARK ACCOUNTING
10 KING ACCOUNTING
10 MILLER ACCOUNTING
20 SMITH RESEARCH
20 ADAMS RESEARCH
20 FORD RESEARCH
20 SCOTT RESEARCH
20 JONES RESEARCH
30 ALLEN SALES
30 BLAKE SALES
30 MARTIN SALES
30 JAMES SALES
30 TURNER SALES
30 WARD SALES
In the above query "E" and "D" are the alias names for the tables EMP
and DEPT respectively. As column DEPTNO is there in both the tables, table
name is used along with column name DEPTNO. This is to avoid the ambiguity
2) NON-EQUI JOIN :
A join condition where any relation operator other than "=" equal to
operator is used.

Consider the following examples Using SALGRADE and EMP tables.


SQL> SELECT * FROM SALGRADE;
GRADE LOSAL HISAL
---------- ---------- ----------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
SQL> SELECT ENAME,SAL, GRADE FROM EMP E,SALGRADE S
WHERE SAL BETWEEN LOSAL AND HISAL
ENAME SAL GRADE
---------- ---------- ----------
SMITH 800 1
JAMES 950 1
ADAMS 1100 1
WARD 1250 2
MARTIN 1250 2
MILLER 1300 2
TURNER 1500 3
ALLEN 1600 3
CLARK 2450 4
BLAKE 2850 4
JONES 2975 4
SCOTT 3000 4
FORD 3000 4
KING 5000 5
3) OUTER JOIN :
In EQUI JOIN rows that does not satisfy specified condition would not be displayed.
Example: DEPTNO 40 is not displayed in the previous example
because there are no employees in it. If we want to diplay its detail also
then we have to use OUTER JOIN.Otherwise OUTER JOIN is imilar to EQUI JOIN
except for the difference it uses outer join (+) operator. (A plus within
parenthesis) towards the side not having required data. Outer join operator will substitute
null values when there are no values available.

SQL> SELECT E.DEPTNO,ENAME,DNAME FROM EMP E , DEPT D


2 WHERE E.DEPTNO (+) = D.DEPTNO;
DEPTNO ENAME DNAME
---------- ---------- --------------
10 CLARK ACCOUNTING
10 KING ACCOUNTING
10 MILLER ACCOUNTING
20 SMITH RESEARCH
20 ADAMS RESEARCH
20 FORD RESEARCH
20 SCOTT RESEARCH
20 JONES RESEARCH
30 ALLEN SALES
30 BLAKE SALES
30 MARTIN SALES
30 JAMES SALES
30 TURNER SALES
30 WARD SALES
OPERATIONS
SQL>SELECT D.DEPTNO,ENAME,DNAME FROM EMP E , DEPT D
WHERE E.DEPTNO (+) = D.DEPTNO
DEPTNO ENAME DNAME
---------- ---------- --------------
10 CLARK ACCOUNTING
10 KING ACCOUNTING
10 MILLER ACCOUNTING
20 SMITH RESEARCH
20 ADAMS RESEARCH
20 FORD RESEARCH
20 SCOTT RESEARCH
20 JONES RESEARCH
30 ALLEN SALES
30 BLAKE SALES
30 MARTIN SALES
30 JAMES SALES
30 TURNER SALES
30 WARD SALES
40 OPERATIONS

SQL> SELECT D.DEPTNO , NVL(ENAME, ' No employee') , DNAME


FROM EMP E,DEPT D
WHERE D.DEPTNO= E.DEPTNO(+);
DEPTNO NVL(ENAME,'N DNAME
------- ------------ --------------
10 CLARK ACCOUNTING
10 KING ACCOUNTING
10 MILLER ACCOUNTING
20 SMITH RESEARCH
20 ADAMS RESEARCH
20 FORD RESEARCH
20 SCOTT RESEARCH
20 JONES RESEARCH
30 ALLEN SALES
30 BLAKE SALES
30 MARTIN SALES
30 JAMES SALES
30 TURNER SALES
30 WARD SALES
40 No employee OPERATIONS
4) SELF JOIN:
When we join a table to itself it is called self join.To join a
table itself means that each row of the table is combined with itself
and with every other row of the table. The self join can be seen as join
of two copies of the same table.
SQL> SELECT E.ENAME,M.ENAME FROM EMP E,EMP
WHERE E.MGR=M.EMPNO;
ENAME ENAME
---------- ----------
SCOTT JONES
FORD JONES
ALLEN BLAKE
WARD BLAKE
JAMES BLAKE
TURNER BLAKE
MARTIN BLAKE
MILLER CLARK
ADAMS SCOTT
JONES KING
CLARK KING
BLAKE KING
SMITH FORD
Above query uses EMP table to display names of the employees and their managers
SQL> SELECT E.ENAME,NVL(M.ENAME,'He is managed by none') FROM EMP
E,EMP M
WHERE E.MGR=M.EMPNO(+)
ENAME NVL(M.ENAME,'HEISMANA
---------- ---------------------
FORD JONES
SCOTT JONES
JAMES BLAKE
TURNER BLAKE
MARTIN BLAKE
WARD BLAKE
ALLEN BLAKE
MILLER CLARK
ADAMS SCOTT
CLARK KING
BLAKE KING
JONES KING
SMITH FORD
KING He is managed by none

SUBQUERY :
A query within another quey. A select statement whose output is substituted in the
condition of another select statement .(A query is a statement written for returning
specific data). The subquery is executed only once. A subquery is enclosed in parenthesis
Conside the following queries.
1) SELECT DEPTNO FROM EMP WHERE ENAME = 'SMITH';
2) SELECT ENAME FROM EMP WHERE DEPTNO= 20
These two queries can be combined as follows.
SQL> SELECT ENAME FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM EMP
WHERE ENAME = 'SMITH');
The SELECT statement inside parenthesis is called subquery and the one which
uses the values returned by it as main query.

SQL> SELECT ENAME FROM EMP


WHERE JOB=( SELECT JOB FROM EMP
WHERE ENAME = 'SCOTT');
ENAME
----------
SCOTT
FORD

CORRELATED QUERY:
In a correlated subquery the table used in outer query refers to the table used in the inner
query. The correlated subquery is executed repeatedly once
for each row of the main query table.
Query to diplay name of highest salary taker.
SQL> SELECT EMPNO, ENAME FROM EMP A
WHERE 1 > ( SELECT COUNT(*) FROM EMP B
WHERE A.SAL < B.SAL)
EMPNO ENAME
-------- ----------
7839 KING

Query to diplay name of lowest salary taker.


SQL> SELECT EMPNO, ENAME,SAL FROM EMP A
WHERE 1 > ( SELECT COUNT(*) FROM EMP B
WHERE A.SAL > B.SAL)
EMPNO ENAME SAL
---------- ---------- ----------
7369 SMITH 800

SET OPERATORS
They combine results from two or more queries into one result.Data type
of all selected colums must be of same type.
UNION: It returns
rows of first query plus rows of second query but avoids duplicates.
(UNION ALL will give duplicates also).
To display designations in department 10 and 20
SQL> SELECT JOB FROM EMP WHERE DEPTNO=10
UNION
SELECT JOB FROM EMP WHERE DEPTNO=20;
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
To display designations in department 10,20 and 30
SQL> SELECT JOB FROM EMP WHERE DEPTNO=10
UNION
SELECT JOB FROM EMP WHERE DEPTNO=20
UNION
SELECT JOB FROM EMP WHERE DEPTNO=30;
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
Similar output can be produced by writing
SQL> SELECT DISTINCT JOB FROM EMP;
JOB
---------
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
INTERSECT: It returns rows that are common to all queries.

To diplay the designations that are common in DEPTNO 10 and 20 write.


SQL> SELECT JOB FROM EMP WHERE DEPTNO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20;
JOB
---------
CLERK
MANAGER
MINUS : It returns rows unique to the first query.
To diplay designations unique in DEPTNO 10 we can write.
SQL> SELECT JOB FROM EMP WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20;
JOB
---------
PRESIDENT
SQL> SELECT JOB FROM EMP WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=30;
JOB
---------
PRESIDENT

Indexes

This chapter describes how to use indexes in a data warehousing environment and
discusses the following types of index:

 Bitmap Indexes
 B-tree Indexes
 Local Indexes Versus Global Indexes
See Also:

Oracle9i Database Concepts for general information regarding


indexing
Bitmap Indexes

Bitmap indexes are widely used in data warehousing environments. The environments
typically have large amounts of data and ad hoc queries, but a low level of concurrent
DML transactions. For such applications, bitmap indexing provides:

 Reduced response time for large classes of ad hoc queries


 Reduced storage requirements compared to other indexing techniques
 Dramatic performance gains even on hardware with a relatively small number of
CPUs or a small amount of memory
 Efficient maintenance during parallel DML and loads

Fully indexing a large table with a traditional B-tree index can be prohibitively expensive
in terms of space because the indexes can be several times larger than the data in the
table. Bitmap indexes are typically only a fraction of the size of the indexed data in the
table.

Note:

Bitmap indexes are available only if you have purchased the Oracle9i
Enterprise Edition. See Oracle9i Database New Features for more
information about the features available in Oracle9i and the Oracle9i
Enterprise Edition.

An index provides pointers to the rows in a table that contain a given key value. A regular
index stores a list of rowids for each key corresponding to the rows with that key value.
In a bitmap index, a bitmap for each key value replaces a list of rowids.

Each bit in the bitmap corresponds to a possible rowid, and if the bit is set, it means that
the row with the corresponding rowid contains the key value. A mapping function
converts the bit position to an actual rowid, so that the bitmap index provides the same
functionality as a regular index. If the number of different key values is small, bitmap
indexes save space.

Bitmap indexes are most effective for queries that contain multiple conditions in the
WHERE clause. Rows that satisfy some, but not all, conditions are filtered out before the
table itself is accessed. This improves response time, often dramatically.
Benefits for Data Warehousing Applications

Bitmap indexes are primarily intended for data warehousing applications where users
query the data rather than update it. They are not suitable for OLTP applications with
large numbers of concurrent transactions modifying the data.

Parallel query and parallel DML work with bitmap indexes as they do with traditional
indexes. Bitmap indexing also supports parallel create indexes and concatenated indexes.

See Also:

Chapter 17, "Schema Modeling Techniques" for further information


about using bitmap indexes in data warehousing environments

Cardinality

The advantages of using bitmap indexes are greatest for columns in which the ratio of the
number of distinct values to the number of rows in the table is under 1%. We refer to this
ratio as the degree of cardinality. A gender column, which has only two distinct values
(male and female), is ideal for a bitmap index. However, data warehouse administrators
also build bitmap indexes on columns with higher cardinalities.

For example, on a table with one million rows, a column with 10,000 distinct values is a
candidate for a bitmap index. A bitmap index on this column can outperform a B-tree
index, particularly when this column is often queried in conjunction with other indexed
columns. In fact, in a typical data warehouse environments, a bitmap index can be
considered for any non-unique column.

B-tree indexes are most effective for high-cardinality data: that is, for data with many
possible values, such as customer_name or phone_number. In a data warehouse, B-tree
indexes should be used only for unique columns or other columns with very high
cardinalities (that is, columns that are almost unique). The majority of indexes in a data
warehouse should be bitmap indexes.

In ad hoc queries and similar situations, bitmap indexes can dramatically improve query
performance. AND and OR conditions in the WHERE clause of a query can be resolved
quickly by performing the corresponding Boolean operations directly on the bitmaps
before converting the resulting bitmap to rowids. If the resulting number of rows is small,
the query can be answered quickly without resorting to a full table scan.

Example 6-1 Bitmap Index

The following shows a portion of a company's customers table.

SELECT cust_id, cust_gender, cust_marital_status, cust_income_level


FROM customers;
CUST_ID C CUST_MARITAL_STATUS CUST_INCOME_LEVEL
---------- - -------------------- ---------------------
...
70 F D: 70,000 - 89,999
80 F married H: 150,000 - 169,999
90 M single H: 150,000 - 169,999
100 F I: 170,000 - 189,999
110 F married C: 50,000 - 69,999
120 M single F: 110,000 - 129,999
130 M J: 190,000 - 249,999
140 M married G: 130,000 - 149,999
...

Because cust_gender, cust_marital_status, and cust_income_level are all low-


cardinality columns (there are only three possible values for marital status and region,
two possible values for gender, and 12 for income level), bitmap indexes are ideal for
these columns. Do not create a bitmap index on cust_id because this is a unique column.
Instead, a unique B-tree index on this column provides the most efficient representation
and retrieval.

Table 6-1 illustrates the bitmap index for the cust_gender column in this example. It
consists of two separate bitmaps, one for gender.

Table 6-1 Sample Bitmap Index


gender='M' gender='F'

cust_id 70 0 1

cust_id 80 0 1

cust_id 90 1 0

cust_id 100 0 1

cust_id 110 0 1

cust_id 120 1 0

cust_id 130 1 0

cust_id 140 1 0
Each entry (or bit) in the bitmap corresponds to a single row of the customers table. The
value of each bit depends upon the values of the corresponding row in the table. For
instance, the bitmap cust_gender='F' contains a one as its first bit because the region is
east in the first row of the customers table. The bitmap cust_gender='F' has a zero
for its third bit because the gender of the third row is not F.

An analyst investigating demographic trends of the company's customers might ask,


"How many of our married customers have an income level of G or H?" This corresponds
to the following SQL query:

SELECT COUNT(*) FROM customers


WHERE cust_marital_status = 'married'
AND cust_income_level IN ('H: 150,000 - 169,999', 'G: 130,000 -
149,999');

Bitmap indexes can efficiently process this query by merely counting the number of ones
in the bitmap illustrated in Figure 6-1. The result set will be found by using bitmap or
merge operations without the necessity of a conversion to rowids. To identify additional
specific customer attributes that satisfy the criteria, use the resulting bitmap to access the
table after a bitmap to rowid conversion.

Figure 6-1 Executing a Query Using Bitmap Indexes

Text description of the illustration dwhsg093.gif

Bitmap Indexes and Nulls

Unlike most other types of indexes, bitmap indexes include rows that have NULL values.
Indexing of nulls can be useful for some types of SQL statements, such as queries with
the aggregate function COUNT.

Example 6-2 Bitmap Index


SELECT COUNT(*) FROM customers WHERE cust_marital_status IS NULL;
This query uses a bitmap index on cust_marital_status. Note that this query would
not be able to use a B-tree index.

SELECT COUNT(*) FROM employees;

Any bitmap index can be used for this query because all table rows are indexed, including
those that have NULL data. If nulls were not indexed, the optimizer would be able to use
indexes only on columns with NOT NULL constraints.

Bitmap Indexes on Partitioned Tables

You can create bitmap indexes on partitioned tables but they must be local to the
partitioned table--they cannot be global indexes. (Global bitmap indexes are supported
only on nonpartitioned tables). Bitmap indexes on partitioned tables must be local
indexes.

See Also:

"Index Partitioning"
Bitmap Join Indexes

In addition to a bitmap index on a single table, you can create a bitmap join index, which
is a bitmap index for the join of two or more tables. A bitmap join index is a space
efficient way of reducing the volume of data that must be joined by performing
restrictions in advance. For each value in a column of a table, a bitmap join index stores
the rowids of corresponding rows in one or more other tables. In a data warehousing
environment, the join condition is an equi-inner join between the primary key column or
columns of the dimension tables and the foreign key column or columns in the fact table.

Bitmap join indexes are much more efficient in storage than materialized join views, an
alternative for materializing joins in advance. This is because the materialized join views
do not compress the rowids of the fact tables.

Example 6-3 Bitmap Join Index: Example 1

Using the example in "Bitmap Index", create a bitmap join index with the following
sales table:

SELECT time_id, cust_id, amount FROM sales;

TIME_ID CUST_ID AMOUNT


--------- ---------- ----------
01-JAN-98 29700 2291
01-JAN-98 3380 114
01-JAN-98 67830 553
01-JAN-98 179330 0
01-JAN-98 127520 195
01-JAN-98 33030 280
...

CREATE BITMAP INDEX sales_cust_gender_bjix


ON sales(customers.cust_gender)
FROM sales, customers
WHERE sales.cust_id = customers.cust_id
LOCAL;

The following query shows how to use this bitmap join index and illustrates its bitmap
pattern:

SELECT sales.time_id, customers.cust_gender, sales.amount


FROM sales, customers
WHERE sales.cust_id = customers.cust_id;

TIME_ID C AMOUNT
--------- - ----------
01-JAN-98 M 2291
01-JAN-98 F 114
01-JAN-98 M 553
01-JAN-98 M 0
01-JAN-98 M 195
01-JAN-98 M 280
01-JAN-98 M 32
...

Table 6-2 illustrates the bitmap join index in this example:

Table 6-2 Sample Bitmap Join Index


cust_gender='M' cust_gender='F'

sales record 1 1 0

sales record 2 0 1

sales record 3 1 0

sales record 4 1 0

sales record 5 1 0

sales record 6 1 0

sales record 7 1 0
You can create other bitmap join indexes using more than one column or more than one
table, as shown in these examples.

Example 6-4 Bitmap Join Index: Example 2

You can create a bitmap join index on more than one column, as in the following
example, which uses customers(gender, marital_status):

CREATE BITMAP INDEX sales_cust_gender_ms_bjix


ON sales(customers.cust_gender, customers.cust_marital_status)
FROM sales, customers
WHERE sales.cust_id = customers.cust_id
LOCAL NOLOGGING;

Example 6-5 Bitmap Join Index: Example 3

You can create a bitmap join index on more than one table, as in the following, which
uses customers(gender) and products(category):

CREATE BITMAP INDEX sales_c_gender_p_cat_bjix


ON sales(customers.cust_gender, products.prod_category)
FROM sales, customers, products
WHERE sales.cust_id = customers.cust_id
AND sales.prod_id = products.prod_id
LOCAL NOLOGGING;

Example 6-6 Bitmap Join Index: Example 4

You can create a bitmap join index on more than one table, in which the indexed column
is joined to the indexed table by using another table. For example, we can build an index
on countries.country_name, even though the countries table is not joined directly to
the sales table. Instead, the countries table is joined to the customers table, which is
joined to the sales table. This type of schema is commonly called a snowflake schema.

CREATE BITMAP INDEX sales_c_gender_p_cat_bjix


ON sales(customers.cust_gender, products.prod_category)
FROM sales, customers, products
WHERE sales.cust_id = customers.cust_id
AND sales.prod_id = products.prod_id
LOCAL NOLOGGING;

Bitmap Join Index Restrictions

Join results must be stored, therefore, bitmap join indexes have the following restrictions:

 Parallel DML is currently only supported on the fact table. Parallel DML on one
of the participating dimension tables will mark the index as unusable.
 Only one table can be updated concurrently by different transactions when using
the bitmap join index.
 No table can appear twice in the join.
 You cannot create a bitmap join index on an index-organized table or a temporary
table.
 The columns in the index must all be columns of the dimension tables.
 The dimension table join columns must be either primary key columns or have
unique constraints.
 If a dimension table has composite primary key, each column in the primary key
must be part of the join.

See Also:

Oracle9i SQL Reference for further details


B-tree Indexes

A B-tree index is organized like an upside-down tree. The bottom level of the index holds
the actual data values and pointers to the corresponding rows, much as the index in a
book has a page number associated with each index entry.

See Also:

Oracle9i Database Concepts for an explanation of B-tree structures

In general, use B-tree indexes when you know that your typical query refers to the
indexed column and retrieves a few rows. In these queries, it is faster to find the rows by
looking at the index. However, using the book index analogy, if you plan to look at every
single topic in a book, you might not want to look in the index for the topic and then look
up the page. It might be faster to read through every chapter in the book. Similarly, if you
are retrieving most of the rows in a table, it might not make sense to look up the index to
find the table rows. Instead, you might want to read or scan the table.

B-tree indexes are most commonly used in a data warehouse to index unique or near-
unique keys. In many cases, it may not be necessary to index these columns in a data
warehouse, because unique constraints can be maintained without an index, and because
typical data warehouse queries may not work better with such indexes. Bitmap indexes
should be more common than B-tree indexes in most data warehouse environments.

Local Indexes Versus Global Indexes

B-tree indexes on partitioned tables can be global or local. With Oracle8i and earlier
releases, Oracle recommended that global indexes not be used in data warehouse
environments because a partition DDL statement (for example, ALTER TABLE ... DROP
PARTITION) would invalidate the entire index, and rebuilding the index is expensive. In
Oracle9i, global indexes can be maintained without Oracle marking them as unusable
after DDL. This enhancement makes global indexes more effective for data warehouse
environments.
However, local indexes will be more common than global indexes. Global indexes should
be used when there is a specific requirement which cannot be met by local indexes (for
example, a unique index on a non-partitioning key, or a performance requirement).

Bitmap indexes on partitioned tables are always local.

1) A table AA contains two columns c1 and c2. column c1 contains 3 records and column
c2 contains

3 records.

write a update query so that c1 must contain c2 values and c2 must c1 values .
[SWAPPING]

just write a normal update statement..that will do the job..

update table set column_a = column_b, column_b = column_a

2) Can u have commit inside a trigger

- no..we cant, for that we have to use autonomous transaction

3) A table has 4 index. If a query , select * from table uses the index. When it is used.

-- didnt understand the question

4) can u lock a table from inside a PL/SQL Block.

- yes..we can..will get back to on this.

5) Explain about DeNormalisation first and then Normalisation


denorm.. - is reverse of normalisation, is done to avoid multiple joins thats needed to
fetch data.

6) what is the query performance if a table contains more than 100 columns.

-- depends on theprimary key defined and indexes

My Answer : Yes .

7) can function return two values. - nope

My Answer: No

8) How will u measure the performance of the query.What are the tools available??

- tprop tool,"dbms explain" command.

9) U r calling a xx procedure from yy procedure . how can u have commit to certains


statements only in

xx procedure and return to yy procedure.

- should use autonomous transaction.

My Answer : I use savepoints and then commit.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy