You are on page 1of 40

1.How do u count no of rows in a table?

A.) select count (*) from table will give the number of rows in
The table including null values.

2. Re: what is the different between unique+not null & primary key, Answer

A)In a relation, we can create only one primary key where as we can create
multiple unique+not null constrains.

Primary key uses clustered index where are unique +Not null uses non
clustered index

3.i have a table as follows


empid empname mgrid deptid
1 a 3 4
2 b 1 5
3 c 2 3
4 d 3 6
5 e 4 7

i want the output as


empname mgrname
a c
b a
c b
d c
e d

A.)select a.empname empname,b.empname mgrname from emp a,emp b


where a.mgrid=b.empid

4.If the base table structure is changed what will happen to


join index?

Answer
Join index will not affected until we change the column name
or data type of the column which we have used in join condition.

5.What is the Diff b/w Constraints and Trigeer?


Answer :1

Constraints
1.are used to limit the type of data that can go into a table.
2.it can be specified when a table is created or after the table is
created.
3.Direct validation like the column should not contain null
values then you can choose Constraints.
4.Constraints will check for exiting rows.
5.constraines provide stoned error message.

Trigger :is a fragment of code that you tell Oracle to run


before or after table is modified.

Answer:2 Direct validation like the column should not contain null
values then you can choose Constraints.

Constraints : NOT NULL,UNIQUE,PRIMARY KEY,CHECK,REFERENCE

Trigger effected only those row after which trigger applied


but constraint effected all row of table .

7.Can i possible to see Table Details ?


Ex :
Table Name Date Time User
Emp May/18/2010 12:59pm Scott

Answer

SELECT OWNER,OBJECT_NAME,To_char(CREATED,'MON/DD/YYYY'),
to_char(CREATED,'HH:MM PM') from ALL_OBJECTS WHERE
OBJECT_TYPE ='TABLE' AND OBJECT_NAME ='EMP_TEST';

8.What is a mutating table

Mutating means that some one is trying to access the table


currently being held by some other non-committing
transaction

IF you have a trigger on table emp_test. Inside that


trigger, your are trying to update/insert in the same table
emp_test.
Then mutating table error will occur.
9.What is pl/sql tables?

Answer
It is a composite datatype used in PLSQL programming.

10.Can I use Commit inside the Trigger? Suppose I use commit


what will be happen (it's complied /executed/work)?

You can not use Commit Inside Trigger. It will not get complied.
commit,rollback and savepoint cannot be used in a trigger
directly, but it can be called in a stored procedure
present in the trigger. however it is usually avoided as it
might have sideeffects in transactions.

Trigger will be compiled. while execution r error will occur.


To avoid this you can use PRAGMA autonomus_transaction

example :

create or replace trigger emp_test_trig


after update on emp_test
for each row
declare
PRAGMA autonomus_transaction;
begin

insert into dep_test values(100,:new.emp_id);


commit;
end;

11. How do you retrieve the last N records from a table?

This Will give you last 10 records from a table

SELECT EMPNAME,SALARY
FROM
(SELECT EMPNAME,
SALARY,
RANK() OVER(ORDER BY SALARY) SAL_RANK
FROM EMP)
WHERE SAL_RANK < = 10

12.List the differences between plsql - function & procedures

Answer
functions:
1.The parameters are input values and output values
2.The functions will return a value
3.The functions will be called with in sql

Procedures:
1.The parameters are input values and output values
2.The procedures will not return any value
3.The procedures will not be called with in sql

13. how to Update table Sales_summary with max(sales) data from


table sales_data. Table 1. sales_data table
Table 2. Sales_summary

1: Region sales 2: Region sales


N 500 N 0
N 800 W 0
N 600
W 899
W 458
W 900

I want the Sales_summary After Update like this


Region Sales
N 800
W 900

SQL> desc a;
Name Null? Type
------------------------------- -------- ----
A VARCHAR2(2)
B NUMBER(3)

SQL> select * from a;

A B
-- ---------
N 500
N 800
N 600
W 899
W 458
W 900

6 rows selected.

SQL> desc b;
Name Null? Type
------------------------------- -------- ----
A VARCHAR2(2)
B NUMBER(3)

SQL> select * from b;

no rows selected

SQL> insert into b (select a, max(b) from a group by a);

2 rows created.
O
SQL> select * from b;

A B
-- ---------
N 800
W 900

update Sales_summary
set Sales=(select max(Sales)from Sales_data where
Region=&region) where Region=&region;

14.suppose we have values like 1 5 7 in a colum.Now we want


numbers like(2 3 4 6) that exists between 1 5 7.How can we
do this using sql query??

A:

15.what is the difference between implicit and explicit cursor

However,queries that return more than one row you must


declare an explicit cursor or use a cursor FOR loop.
Explicit cursor is a cursor in which the cursor name is
explicitly assigned to a SELECT statement via the
CURSOR...IS statement.

An implicit cursor is used for all SQL statements Declare,


Open, Fetch, Close. An explicit cursors are used to process
multirow SELECT statements An implicit cursor is used to
process INSERT, UPDATE, DELETE and single row SELECT. .INTO
statements.

Answer
when we fire any DML operation a memory is alocated. this
memory area is called context area or cursor. data is retieved and stored
in this area

implicit cursors are automatically created by the Oracle.


when you perform any DML operation a memory has been
automatically created, and when the operation is finished
it automatically release the memory space, here every thing
is controlled by the oracle itself.

explicit cursors are the cursors, where the user defined


for which select statement the cursor is being created,
when to fetch the data, and release the memory space. on
other words the control is over the programmer.

16)Difference between DBMS and RDBMS...CODD’s rules

Answer

DBMS-Database management system.


=>In dbms no relationship concept
=>It can’t Dmplement constraints in table and no security
of data.
=>It supports Single User only
=>It treats Data as Files internally
=>It supports 3 rules of E.F.CODD out off 12 rules
=>It requires low Software and Hardware Requirements.
=>Examples: FoxPro
RDBMS-Relational management system
=>It is used to establish the relationship concept between
two database objects, i.e, tables
=>It implement constraints in table and no security of data.
=>It supports multiple users
=>It treats data as Tables internally
=>It supports minimum 6 rules of E.F.CODD
=>It requires High software and hardware requirements.
=>examples:Oracle,mysql,DB2.

Answer :2

DBMS-Database management system.


1> consider as file says field,attributes,record and file.
2> table relationship mentained by programmaticaly.
3> high network trafic.
4> distributed datable not supported.
5> no security
RDBMS-Relational management system
1> says column, row and table.
2>table relationship mentained at the time of table creations.
3>low network trafic.
4>distributed database supported.
5>login level security.

17.Difference between IN and EXISTS

IN: Inner query executes first and drives the outer query.

EXISTS: Outer query executes first and compares tge rows


retrived with the inner query.

Consider table tab1 has 1000 rows and table tab2 has 1000
rows.

IN: select t1.empid from tab1 t1 where t1.code in (select


t2.code from tab2 t2) -- All rows in t1 will read with t2
and the effect is 1000 X 1000 rows.

EXISTS: select t1.empid from tab1 t1 where exists (select 1


from tab2 t2 where t1.code=t2.code) -- Max of 1 row will be
read for each row of t1 and thus reduces the processing

overhead.
Thumb rule:
1) If the majority of the filtering are in the sub query
then use IN.
1) If the majority of the filtering are in the outer query
then use EXISTS.

18.I have 2 Databases. How can create a table in particular


database? How can i know the list of tables presented each
database?( in oracle 10g)

Answer
suppose you have two databases: db1 and db2
you have to select one of them
as
sql>use db1;
then use
sql>select * from tab;
it will show you the listing required.!
Answer :2

Suppose your 2 databases are name as PROD1 and PROD2

1) How can create a table in particular database?


=> First you have to connect to the database where you want
to create table with given login and password.
and then if you have create permission than you can use
following sql
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )

19)suppose we have a table in which 200 rows. i want to find


101 row ? what the query....
and how we find 4th and 5th highest salary and 1 to 10
highest salary?

Answer
Let Table name : Employee
Let the columns: Employee_name, Salary

To find 101st row:

select * from (select * from Employee order by


emplayee_name) where rownum = 101

To find 4th highest salary

select * from (select * from Employee order by salary desc)


where rownum = 4

To find 5th highest salary

select * from (select * from Employee order by salary desc)


where rownum = 4

To find 1 to 10 highest salary

select * from (select * from Employee order by salary desc)


where rownum < 11

20. How would you go about increasing the buffer cache hit
ratio?

A. If Buffer cache hit ratio is less then 85%.


0. Explain the difference between a hot backup and a cold
backup and the benefits associated with each

A.Hot backup is online backup(means we can take backup when


database is up and running.ie Alter database begin backup
mode;
Cold backup is offline backup(means taking backup when
database is shutdown gracefully.ie at O/S level using copy
command.)

1. You have just had to restore from backup and do not have
any control files. How would you go about bringing up this
database?

A. Create controlfile dynamicaly.

2. How do you switch from an init.ora file to a spfile?

A. create spfile from pfile;


startup force;

3. Explain the difference between a data block, an extent


and a segment.

A. oracle stores data interms of data blocks


group of data blocks is known as extent.
group of extents make a segment.

4. Give two examples of how you might determine the


structure of the table DEPT.

5. Where would you look for errors from the database engine?

6. Compare and contrast TRUNCATE and DELETE for a table.

A. Truncate=delete+ commit(as it is a DDL command)


Delete= as it is a DML command we can rollback the
transaction

7. Give the reasoning behind using an index.

A. reason behind using index is to increase query


performance.
8. Give the two types of tables involved in producing a star
schema and the type of data they hold.

9. What type of index should you use on a fact table?

10. Give two examples of referential integrity constraints.

11. A table is classified as a parent table and you want to


drop and re-create it. How would you do this without
affecting the children tables?

12. Explain the difference between ARCHIVELOG mode and


NOARCHIVELOG mode and the benefits and disadvantages to
each.?

13. What command would you use to create a backup control


file?

14. Give the stages of instance startup to a usable state


where normal users may access it.

15. What column differentiates the V$ views to the GV$ views


and how?

16. How would you go about generating an EXPLAIN plan?

Answer

21)What are the new features in Oracle 10g. Compared to Oracle 9i?

Answer

# Flashback Enhancements -Flashback Version Query, Flashback


Transaction Query, LOB Handling with Flashback, Setting up
for Flashback, Flashback Table, Flashback Drop Table and
Recycle Bin management.

# Backup and Recovery Enhancements: - Flash Recovery Area,


Flashback Database (setup, flashback logs and use), Restore
Points, Simplified Recovery through RESETLOGS, Compressed
Backups, Change Tracking, Incrementally Updated Image
Copies, SWITCH DATABASE, New V$ Views, Encrypted Backups,
DROP DATABASE, CATALOG, Oracle Secure Backup and more.

# Automatic Storage Management:- An introduction to Oracle's


new integrated file system and volume manager. Examples
illustrate the basic use of ASM, including creating disk
groups, fail groups, and using ASMCMD.

# Job Scheduler - Use the new DBMS_SCHEDULER package to


schedule jobs, including OS scripts. Examples illustrate
creating and scheduling jobs in both a Linux and a Windows
environment.

# SQL Enhancements - Regular expressions, DML error logging,


case-insensitive sort and search, MERGE enhancements, MODEL
queries, XQUERY and much more.

# PL/SQL Enhancements -The new optimizing compiler, compiler


warning messages, debugging improvements, native compilation
enhancements, UTL_MAIL and more.

# Performance and Tuning Features - Automatic SGA


Management, Automatic Workload Repository (AWR), Advisors
(ADDM, SQL Tuning Advisor, etc), Active Session History
data, new performance statistics (e.g. metrics and database
time), Thresholds and Server-Generated Alerts, CBO
Enhancements and much more.

# Security and Auditing Enhancements - Changes to the


CONNECT Role, FGAC Review, FGAC / VPD Enhancements, FGA
Review, Fine Grained Auditing Enhancements, Encryption
Enhancements, DBMS_CRYPTO Package (R1) and Transparent Data
Encryption (R2).

# Tablespace, Table and Segment Management - SYSAUX


tablespace, BIGFILE and SMALLFILE tablespaces,
database-level default tablespace, database-level default
temp tablespace, temp tablespace groups, multi-platform
transportable tablespace, renaming tablespaces, predicting
object growth, online table redefinition enhancements and
online segment shrink.

# Utilities (Data Pump) - An example-based introduction to


Data Pump, the next generation export / import utility. Also
covered: External Table and Logminer enhancements.

# SQL*Plus Enhancements - New predefined variables, SPOOL


command enhancements, AUTOTRACE enhancements and more.

# Miscellaneous Enhancements - Guaranteed UNDO retention,


ROLLBACK monitoring, Easy Connect (EZCONNECT) connections,
database high watermark recording, database feature usage
tracking and new and deprecated initialization parameters.
22 .refers to the disk mirroring

Answer
creating a copy of the disk at some separate place and keep
on updating corresponding to the original disk is called
disk mirroring or disk shadowing.

23.What are the different types of joins and explain them


briefly.?

Answer
equi join ,
non-equi join,
self join,
outer join,
cross join.

There are 2 main type of joins :

Equijoin : Join N number of tables for equality =.

Non-Equijoin : Join N number of tables for other than


equality such as <>,<,>,IN,BETWEEN etc.

Technically there are total 3 different types of joins:

Cross Join: When join condition is missing then all rows from one table
gets joined with all rows from other table..

Inner Join: If a row has a NULL value in any one of the


columna of join conditin then that row will not fetched.

Outer Join: Even if the NULL values are present in any


columns of join condition that record will get fetched.
There are again 3 types of outer joins: Left, Right, Full.

Self Join : A table is joined with self.

Joins in Oracle 10g:


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

A join is a query that combines rows from two or more


Tables, views, or materialized views ("snapshots"). Oracle
Performs a join whenever multiple tables appear in the
Query’s FROM clause. The query's select list can select any
Columns from any of these tables. If any two of these
tables have a column name in common, you must qualify all
references to these columns throughout the query with table
names to avoid ambiguity.

Join Conditions
---------------
Most join queries contain WHERE clause conditions that
compare two columns, each from a different table. Such a
condition is called a join condition. To execute a join,
Oracle combines pairs of rows, each containing one row from
each table, for which the join condition evaluates to TRUE.
The columns in the join conditions need not also appear in
the select list.

To execute a join of three or more tables, Oracle first


joins two of the tables based on the join conditions
comparing their columns and then joins the result to
another table based on join conditions containing columns
of the joined tables and the new table. Oracle continues
this process until all tables are joined into the result.
The optimizer determines the order in which Oracle joins
tables based on the join conditions, indexes on the tables,
and, in the case of the cost-based optimization approach,
statistics for the tables.

In addition to join conditions, the WHERE clause of a join


query can also contain other conditions that refer to
columns of only one table. These conditions can further
restrict the rows returned by the join query.

Equijoin / Inner Join


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

An equijoin is a join with a join condition containing an


equality operator. An equijoin combines rows that have
equivalent values for the specified columns.

Cartesian Product
-----------------
If two tables in a join query have no join condition,
Oracle returns their Cartesian product. Oracle combines
each row of one table with each row of the other. A
Cartesian product always generates many rows and is rarely
useful. For example, the Cartesian product of two tables,
each with 100 rows, has 10,000 rows. Always include a join
condition unless you specifically need a Cartesian product.
If a query joins three or more tables and you do not
specify a join condition for a specific pair, the optimizer
may choose a join order that avoids producing an
intermediate Cartesian product.
Outer Join
----------

An outer join extends the result of a simple join. An outer


join returns all rows that satisfy the join condition and
those rows from one table for which no rows from the other
satisfy the join condition. Such rows are not returned by a
simple join. To write a query that performs an outer join
of tables A and B and returns all rows from A, apply the
outer join operator (+) to all columns of B in the join
condition. For all rows in A that have no matching rows in
B, Oracle returns NULL for any select list expressions
containing columns of B.

Outet join has Two types :


--------------------------
1. Left Outer Join
2. Right Outer Join

Self Join
---------

A self join is a join of a table to itself. This table


appears twice in the FROM clause and is followed by table
aliases that qualify column names in the join condition. To
perform a self join, Oracle combines and returns rows of
the table that satisfy the join condition.

24.define primary key & secondary key?

Answer
primary key is a key which always accept unique value.

secondary key is a key which when you are making primary key
for more than one column as primary key for retrieving of
reords.

eg.
create table tnam
(ano number,
bno number,
bname char(12),
primary key(ano,bno))

In this bno is secondary key.


25.what is autonomous transaction?

Answer

Autonomous transactions are started by a parent, or main,


transaction but operate
independently of the parent for transaction control. If a
commit or rollback is used
in the autonomous or main transaction, or if a failure
occurs for any reason, it does
not impact the other transaction.
Our favorite use of this feature is for logging application
events. If the need is to
log activity, regardless of the outcome, but the logging
success or failure should not
impact the application, autonomous transactions are the
perfect solution.
To create an autonomous transaction, use a pragma called
AUTONOMOUS_TRANSACTION. The pragma is placed in the
declaration section of the block.

26.How can I insert data into a table with 3 columns using


FORALL?

Answer
you can use 3 different collections for it...

suppose the table is emp have the following columns


1. empname varchar
2. empid number
3. sal number

declare
type name_typ is table of emp.empname%type;
type id_typ is table of emp.empid%type;
type sal_typ is table of emp.sal%type;
name_tab name_typ;
id_tab id_typ;
sal_tab sal_typ;
begin
name_tab := name_typ('ramit','rohan');
id_tab := id_typ(10,20);
sal_tab := sal_typ(21000,22000);
for all i in name_tab.first .. name_tab.last

insert into emp values(name_tab(i),id_tab(i),sal_tab(i));


end;
27.What is the different between Stored Procedure and Procedure?

Answer

In Layman tounge -
---------------
Whenever any named block in PL/SQL is created using CREATE
OR REPLACE clause, and as we compile it will get stored in
database, henceforth other code snippets can call/use this
block which ulimately resides in database after creation
i.e. "stored in database". And thus will move along
database if ever we move the database.

In oracle way -
---------------

A stored procedure is created and stored in the database as


a schema object. Once created and compiled, it is a named
object that can be run without recompiling. Additionally,
dependency information is stored in the data dictionary to
guarantee the validity of each stored procedure.

Answer

Two are same.Once the procedure is created and compiled ,it


is stored in database permanently.That's why it is called as
stored procedure.

Answer

Yes, Store Procedure/Procedure are one and the same.We have


to Create Procedure and Compile it in Data base,once
compiled it will be stored and we can use the same when
ever required in various other Procedures.

Procedure Usually used to perform set of actions based on


conditions.
28)How to write a procedure for displying the data in a TREE
or (PARENT and CHILD ) relationship?
for ex: A is the main project id, for this project B,C,D are sub
tasks(sub project id's) for B the sub tasks are e,f,g and for c is
h ,i ,j and for d is k,l,m now i need to display the o/p in a TREE fashion

Answer
You can use Select..ConnectBY.. PRIOR clause in Oracle to
generate the data in tree structure. Google for the apt
syntax and usage.

select lpad('',level*4)||projectid,subtask from xyz


start with projectid ='&a' connect by prior projectid=subproid

29.how to saw triggers output in pl/sql database?

Answer

Running block of code or the querry having opposite


condition placed in the trigger.When the condition gets
false then the trigger gets called avoiding particular
action such as Update,Delete,Insert depending on the
trigger type.The trigger output is in form of Error massage
used in trigger itself.

30.What is the difference between CHAR and VARCHAR2? If


VARCHAR2 serves the uses of CHAR why CHAR is still used and
not been discarded yet?

Answer
in char it allocates the memory space as static where as in
varchar2 it allocates the memory space as dynamic

OR

char is a space mapping function where as in varchar2 it is


not mapping the space it occupies the exact size of the
string

Have more diff between char and varchar2


char size only 2000 bytes in sql, default size is 1 byte.
it will occupying the trailing spaces. so much of memory wasted.

varchar2 size 4000 bytes in sql and no default size.


it will not occupying the trailing spaces.
Another difference is accessing a variable declared as char
is faster than, accessing a varchar2.

Char is the datatype that occupies complete space declared


whether used or not. ie:- If any field is declared as char
(10) then this field for all records will occupy complete
10 bytes whether the value stored in it is 1 byte or 10
byte.

Whereas Varchar2, as the first 3 characters explains Var-


Variable, will occupy only the bytes for the value entered
in the field.

1. Char is fundamental data type. VARCHAR2 is derived one.


2. Char allocates static memory space while VARCHAR2
allocates dynamic memory.
3. Char is required to maintain compatibility with other
tools (Reporting, DWH, Data related).
4. Char is faster than VARCHAR2 (for large text).

Answer

Technically CHAR has better performance than VARCHAR2.


For CHAR(10) database already knows the length of value in
each record and therefore displays the entire string up till
10 characters. In case of VARCHAR2 the end of string has to
be reached('\0'-NULL) before the database stops displaying
the characters ahead. Each character is compared to NULL
character before it can be determined that end of string has
arrived. Comparing each string character with NULL character
consumes some CPU cycles and hence VARCHAR2 is slower in
performance as compared to CHAR.

31. When the mutating error will comes? and how it will be
resolved?

when we try to dml operation on orginal table in trigger.


then the trigger was excuted but while perfoming any action
on original table it will show mutating..

to overcome the above problem we need to create a autonamous


trasaction trigger

Mutating error in Trigger:-


When programmer create trigger and give table name abc and
in body if programmer is using same table abc for
selecting,updating,deleting,inserting then mutation occur.

EX.:-
create or replace trigger xyz
after
update
on abc
for each row
referencing :OLD as OLD :NEW as NEW
begin
select max(salary) from abc;

update abc
set location_id=:NEW.location_id
where dept_id=105;

end;
------------------------------------------------------------
In the above example you are updating same table which is
under transaction so mutation problem occur here.

Solution on this is

You can use Temporary table or Materialize view which can


solve above problem

32. Can we use SQL%ISOPEN in implicit cursors? Does this


attribute works properly in Implicit Curosors?

Implicit cursors: SQL%ISOPEN always returns FALSE,


indicating that the implicit cursor has been closed.

I hope below example gives you very fair idea.

SQL> BEGIN
2 UPDATE employee
3 SET salary = salary *2
4 WHERE id = '01';
5
6 IF not SQL%ISOPEN THEN
7 DBMS_OUTPUT.PUT_LINE('closed');
8 END IF;
9 END;
10 /
closed

PL/SQL procedure successfully completed

33. what is Complex index. how to create it?


Do you mean Composite Index?

Composite index is the index created on multiple columns of


a table. A maximum of 16 columns can be used as a composite
index. It can be created at table level only. Unique,
Primary Key and Foreign Key can be composite keys.

Ex:
Create table emp
(eno number,
ename varchar(5),
dob date,
sal number,
dno number,
Primary Key(eno, ename) -- Composite Index
);

34. how to select alphabets in a one column , for this the


table name is PA_TASKS and column name is TASK_NUMBER, In
TASK_NUMBER the data like this
1.1.3NN,1.1.4NN,1.5.1NN,1.3.2NE,1.5NN,1NN,1.2NE,1CE , For
this i need to disply output as NN,NN,NN,NE,NN,NN,NE,CE,
Its some urgent requirement ,thanks in advance

A>you can use this select statement:-

select trim(translate(TASK_NUMBER,'.0123456789',' ')) from


PA_TASKS;
For example:-
select trim(translate('1.1.3NN','.0123456789',' ')) from
dual;

it will give NN as output

if value format same like this then you can use substr
function also for it like this:-

select substr(TASK_NUMBER,-2) from PA_TASKS ;For example:-

select substr('1.1.3NN',-2) from dual;

it will give NN as answer.

35. how to connect oracle in UNIX prompt?


This is not a big job
$ su orcale10g
$sql plus
username/password-scott/tiger

If not connected just mail me on my mail id


omkarp.joshi@yahoo.co.uk

You have to set the following:

ORACLE_HOME
ORACLE_SID
PATH

$sqlplus
$scott/tiger

36. Hello All, Could any well write a query for the following
scenario?

Account(table name)
No Name Amount
1 ABCD 2000.00
2 DEFG -2000.00
3 GHIJ 3000.50
4 JKLM 4000.00
5 MNOP 6000.00

O/p Should be in this format


No Name Credit Debit
1 ABCD 2000.00 0
2 DEFG 0 -2000.00
3 GHIJ 3000.50 0
4 JKLM 0 -4000.00
5 MNOP 6000.00 o

could any one give appropriate query for this

select no, name,


case amount/abs(amount) when 1 then amount else 0 end credit,
case amount/abs(amount) when -1 then amount else 0 end Debit
from account
select sno,name,decode(sign(amount),1,0,amount)debit,decode
(sign(amount),-1,0,amount)credit from account
/

Select no,name, 0 Debit, amount Credit


from temp
where amount >0
union
Select no,name, amount Debit, 0 Credit
from temp
where amount < 0

37. what is oracle sql,pl/sql with interfaces

sql * plus, iSQL * Plus

38. why use cursors?

Cursor is used to process multiple rows using pl/sql.

Cursors allow row-by-row processing of the result sets.


Retrieve more than one rows from table or database to use
Cursors

Cursor : It's a private SQL worksheet area where we can


execute SQL commands and processing information.
The purpose of the Cursor is, PL/SQL execution block will
process only one records means it will return only one
records. If we want to retrieve or process more number of
records we use the "Cursors".
These are of two types.
1. Implicit Cursor 2. Explicit cursors.

38. how to delete duplicate rows from a specified table(only single table)
how do you know which join is need to be used?

delete <table_name> where rowid not in (select min(rowid)


from <table_name> group by <dup_rec_col>)

max(rowid) can also be used provided you have to retain the


latest value other wise min(rowid) is fine.

delete from emp p where rowid<(select max(rowid) from emp s where


p.ename=s.ename)

39. why should required for Indexed by table in pl/sql?

A. For good performance Index is required.


Consider the case of a very large table (20,000,000 rows)
to which new records are added daily (usually about 1,000
of them). Every night, you need to report these additions
on an audit trail. Rather than scan the whole table looking
for changes, you will want to use an index over the
TRANSACTION_DATE column. But the index would need to be
huge. This is a case in which your index is over the entire
table, although you are actually interested only in the
1,000 or so records that were added today. The actual index
is physically many times larger than it needs to be, and it
uses many more disk I/Os to traverse the binary tree to the
leaf data.

40. why should required nested tables, Object types, partition


tables and varying arrays. what is the difference between
these are all. give me example with explanation?

V-Array is an Ordered set of elements. It’s having Maximum


size and you can't delete individual elements. V-Arrays are
dense.

Nested Table is an un-orderes set of elements. It doesn't


have maximum size and you can delete individual elements
from Nested Tables . Nested Table can be Parse.

41. With out using count() function. How to the find total
number of rows in a table?

select max(rownum) from table-name;

Here rownum is a keyword which can gives unique number for individual rows

select sum(1) from table-name

42. Please let me know if UNION ALL and Natural Join does the
same operation and are same?

no,union all and natural join is not same. for example tave
two tame emp and dept

emp table

empid ename salary


1 a 1000
2 b 2000

dept table
deptid deptno
1 10
2 20
if i join this two tables

(empid = deptid)

empid ename salary deptno


1 a 1000 10
2 b 2000 20

if i union a11 this two tables


empid ename salary deptno
1 a 1000 null
2 b 2000 null
1 null null 10
2 null null 20

so join and unionall is not same

union all: Joins the 2 selected results based on different


conditions.

Example:
select a.emp_id, b.dept_id from
emp a, dept b
where a.dept_id=b.dept_id
and a.sal < 3000
union all
select a.emp_id, b.dept_id from
emp a, dept b
where a.dept_id=b.dept_id
and a.sal > 6000

Natural Join: Establish the condition between 2 or more


tables.

Example: select a.emp_id, b.dept_id from


emp a, dept b
where a.dept_id=b.dept_id

43. can use the following like overloading concept in a single


package:

procedure p1(a varchar),


procedure p1(a varchar2),
procedure p1(a char)

Yes. you can create package where overloading will be


identified by using type of arguments.

Following code will work fine,


--WORK's FINE

create or replace package PK_TEST AS

procedure p1(a IN varchar);


procedure p1(a IN varchar2);
procedure p1(a IN char);

end PK_TEST;
But, following code will not work as p1( v1 IN varchar) and
p1(v3 IN varchar) has the same type of arguments.

--NOT WORK
create or replace package PK_TEST AS

procedure p1(v1 IN varchar);


procedure p1(v2 IN varchar2);
procedure p1(v3 IN varchar);

end PK_TEST;

I created a test package and executed.

create or replace package test is


procedure p1(v1 in Varchar);
Procedure p2(v2 in varchar2);
procedure p3(v3 in char);
end;
/

create or replace package body test is


procedure p1(v1 in Varchar) is

begin
dbms_output.put_line(' The input data for v1 is: '||v1);
end;

Procedure p2(v2 in varchar2) is

begin
dbms_output.put_line(' The input data for v2 is: '||v2);
end;

procedure p3(v3 in char) is


begin
dbms_output.put_line(' The input data for v3 is: '||v3);
end;

end;
/

I called each procedure in sql by setting the serveroutput


on:

begin
test.P3('Testing Procedure P3');
end;

I got the below output:


The input data for v1 is: Testing Procedure P1
The input data for v2 is: Testing Procedure P2
The input data for v3 is: Testing Procedure P3

44. how can we find the select statement is indexed or not?

To check the statement is indexed or not via AUTO Trace -Â


Trace only command

Check for "EXPLAIN PLAN".

SELECT * FROM ALL_INDEXES


WHERE OWNER = 'MYUSERNAME' AND TABLE_NAME ='MYTABNAME' AND INDEX_NAME =
'MY_IND_NAME'

45. how to debugs a procedure or package using


dbms_output.put_line in plsql?

dbms_output.put_line can be used in Packages, Procedures or


triggers to display message or variable values which can be
used as debugging tool

46. i want to display 1 to 10 numbers using one select statement.

1.select level from dual connect by level<=10

2. select rownum from user objects where rownum <= 10

47. i have one table with accounts and amounts as colums.


accounts with columns c and d. and amounts with
values 1000,2000,3000 for c and 4000,5000,8000 for d.
i need to find the sum of these accounts c and d individually
and find the differences between their sum using one select
statement.

question simply ask for the total of both the columns and
their difference, all in one 'select' statement.

select sum(c)"Sum of C",sum(d)"Sum Of


D",abs(sum(c)-sum(d))"Difference" from accountA

48. I have doubt that any one tell ref cursor comes in sql
pl/sql? pls clarify?

Ref cursor comes in PL/SQL.


You can return a ref cursor in a function.
A ref cursor is useful while returning more values.

It will use in PL/SQL. Reusability of Cursor is nothing


but "REF CURSOR”. These are of 2 types.
1.Weak Ref cursor 2. Strong ref Cursor.
49. If I have a table T with 4 rows & 2 columns A & B. A has
values 1,2,3,4. and B has 10,20,30,40. Write an Update SQL
query which can Swap the values of A & B for all records.
(Do not use a sub-query)

UPDATE T
SET A = B, ENVDOR_NUMBERB = A

UPDATE T
SET A = B,B=A;

select A as "B",B AS "A" from T;

update T
set A:=A+B,
B:=A-B,
A:=A-B;

50. In a package if we have 10 procedures or functions,How to


know which will execute first?

1.Inner\Sub Group statements are Executed


2.Procedures\Functions having normal fetching stmt is
executed first

51. how to create a database in oracle?

1.Align the Table space for the Database


2.Create db with name and then user privileges for creating
the Table

52. write a query for finding the length of the sting?

select length('abc') from dual;

out put:3

select length(<columname>) from <table>;

53. I have one Excel file with 1,50,000 Records. Now I need to
load that whole file into Oracle Database with same columns
in Excel sheet .
I need PLSQL Procedure or used by SQL PLUS

1.I NEED PL/SQL PROCEDURE

we can't use sqlplus,why because we can't upload the data


in single statement,So we need pl/sql procedure
or else dump the data using with sql loader
by using command prompt in SQL LOADER

2.Probably, u have to save the file in ur hard disk(namely in


ur D drive) first eg. sourav.txt
Then open pl/sql developer and open a command window. And
then type in: @ D:\sourav.txt
All the rows will be updated.. finally "commit" it

3.If you are using SQL Developer one option is there for
importing data from excel/CSV or any other files.
first u need to create table which contains all columns in
excel. then right click on that table it will give option
for import excel data to the table

54. What is a REF CURSOR? Compare strong and week ref cursor types.

Ref cursor is a cursor variable which acts as a pointer to


the sql memory area.
Ref cursor can be associated with multiple sql statements
where as a cursor can be associated with only one sql
statement.
Refcursor is dynamic where as cursor is static.

Ref cursors are of two types:


1)strong ref cursor: which retuns value.
2)week ref cursor: which doesn't return value.

For the strong ref cursor the returning columns with


datatype and length need to be known at compile time.

For the weak ref cursor the structure does not need to be
known at compile time.

TYPE WEAK_REF_CURSOR IS REF CURSOR;

TYPE STRONG_ REF_CURSOR IS REF CURSOR RETURN


TABLE_NAME%ROWTYPE;

55. What is oracle ? why we should go for oracle database


instead of different databases available in the industry?

IT WILL SATISFY 11 OUT OF 12 CODDS LAW / RDBMS FULLY


SATISFIED

Basically Oracle refers company name. Oracle used to store


and receive the data in the database in a structured manner
using RDMS concept.

oracle name took from oracle company. thats right. i heard


that we store unlimed of date permanently. we can retrive
data when ever we want. it has safe secure than other
datbase. but only one dis adv is that we have write long
statement and difficult in code. not easy to write like sql
server. and much more is there . important one only i refered.

for eg: ms-access we cannot store large data in it. it has


limited space also not that much secure as oracle as.

Oracle stands for "Oak Ridge Automated Computing language Engine"

56. How One can easily select all even, odd, or Nth rows from a
table using SQL queries?

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

For nth number,


Example we r considering number n=10
select * from emp where (rowid,0) in (select rowid,
mod(rownum,10) from emp)

57. what are the differences among these table level lock
modes - IN SHARE MODE, IN SHARE UPDATE MODE, IN EXCLUSIVE
MODE ?

in share mode :
this mode is for read only on entire table.
we can not make changes to table.
any user can have a lock in share mode at same time.

in share update mode :


this mode is used to lock the selected rows for update.
this mode acquires lock on selected rows only,not entire table.
other user can have lock on other rows on the same table but
not on the rows you have locked.

in exclusive mode :
this acquires lock on entire table.
another user can not have any lock on that table.

58. what eliminate duplicate without using rownum and not

Use Group clause and having count < 2

Mr. Kondla is almost right, but forgotten to use keyword


DISTINCT. It should be like

-> create table T2 as select DISTINT(*) from T1;


-> drop table T1;
-> rename T2 to T1;

59. how to create user in sql and how to set password for that?

create user <username> IDENTIFIED BY password;

60. How can we overcome recursive triggers in SQL?

using semaphore

61. what is the difference between the query and corelated query?

1.corelated query is refered by each an every value by sub query.


2.normal query is referd by sub query one bulk amount to get a
main query

A query is nothing but if we want to evaluate one thing we


will write query. like
select * from emp; --->> query

A Query is evaluated once for each and every row from the
parent statement is called correlated Query.

like
select * from emp outer where sal= ( select avg(sal) from
emp e where dept.e=dept.outer) --> corelated query

When 1st main query is executed then the result of the main
query is used in teh where clause of sub query then this
type of sub query is called as co-related sub query.

Correlated Query: If a sub query has a Reference with the


value or values of Main Query , It is called as Correlated
Sub query.

62. What is RAC in oracle?


RAC stands for REAL APPLICATION CLUSTER, it is and advance future from
Oracle 10g

Oracle RAC allows multiple computers to run the Oracle RDBMS software
simultaneously while accessing a single database, thus providing a
clustered database.

Since Oracle RAC allows multiple computers to access a single database


simultaneously, it addresses several areas of database management. These
areas include:
fault tolerance
load balancing
scalability

In a non-RAC Oracle database, a single instance


accesses a single database. Where the "database" consists
of a collection of data files, control files, and redo logs
located on disk; the "instance" comprises the collection of
Oracle-related memory and operating system processes that
run on a computer system.

In an Oracle RAC environment, two or more computers (each


with an instance) concurrently access a single database.
This allows an application or user to connect to either
computer and have access to a single coordinated set of
data.

RAC stands for Real Application Clusters. It allows


multiple nodes in a clustered system to mount and open a
single database that resides on shared disk storage. Should
a single system fail (node), the database service will
still be available on the remaining nodes.

A non-RAC database is only available on a single system. If


that system fails, the database service will be down
(single point of failure).

RAC is Cluster software available from Oracle. This is


available 10g onwards.

In this Cluster environment we can have multiple instances


running with a single database. Users are connected to
different instances. Availability and load balancing is the
main purpose behind Oracle RAC.

VD (Voting Disk) and OCR (Oracle Cluster Registry) are the


components of RAC. VD is similar to control file and OCR has
all the registered services to start the cluster.
The connection of user could be established on any node but
later depending on the number of users connections
established and the number of instances(nodes) available the
load of all the established connections is balanced across
the Cluster.

The first node created in the Cluster is the Master Node and
all other nodes in the Cluster nbehaves like Slaves.

If any slave node fails to communicate with Master node,


internally the failed node is rebooted by the Master node by
writing a kill block into VD. If the Master node fails, then
any of the existing node responding first will become the
Master node and reboots the failed node.

Daemons checks for the availability of VD,nodes and OCR and


cluster is started.

We can add nodes to the existing cluster from any exiting


node which is already a part of the cluster. We can also
delete a node from the cluster by stopping all the services
of that node from the CRS inventory and home.

We can have multiplexed copies of VD and OCR. VD (Min 1 and


Max 310....OCR(Min 1, Max 2).

We can take backup of VD and OCR with the help of dd (disk


dump). For OCR we can also perform logical backup using
export utility.

Note: Use ASM (logical location for physical disk groups) for
the best performance).
Create ASM instance for each node

63. how to create object in plsql

1.create type type_name as object()

create type type_name as object


(
No NUMBER,
Name Varchar2(15),
City VARCHAR2(30,
POSTALCODE CHAR()
);

64. What is the difference between DELETE and TRUNCATE?


DELETE: DML, Manual Commit, Till not committed can be
rollback, can be applied for both row level as well as
table level, can be used in trigger, doesn't release memory.

TRUNCATE: DDL, auto commit, cann't rollback, applied table


level, cann't be used in trigger, releases memory.

-> In DELETE Command you can give the conditions in WHERE


Clause & In TRUNCATE you cannot give conditions

65. Store procedure will return a value?

Stored procedure will return the values based on the OUT parameters
stored procedure can not return a value using the return statement.
though a stored procedure can contain a return
statement but should not return a value.simply "return".
in a manner,stored procedure can return values to the
calling block through the OUT,INOUT parameter modes.

66. use of IN/ANY/ALL

IN,ANY,ALL ARE MULTIPLE OPERATORS


THESE ARE USED IN MULTIPLE ROW SUBQUERIES

IN - used to select multiple rows based on any of the key


provided

SQL - select distinct employeeid from orders where orderid


in ( select orderid from orderdetails where discount >= 10)

ANY - used in case of relational queries to compare result


with any of the key.

SQL - select custID from orders where regionID != "E" and


discount > any (select discount from orders where regionID
= "E" and discount > 3)

ALL - used in case of relational queries to compare result


with all of the keys.

SQL - select custID from orders where regionID != "E" and


discount > all (select discount from orders where regionID
= "E" and discount > 3)

-> in------------ Looks to all values returned in sub-query

-> <any---------- looks to highest value in sub-query


-> >any---------- looks to smallest value in sub-query

-> <all---------- looks to smallest value in sub-query


-> >all---------- looks to highest value in sub-query
67. What is integrity constraints?

which prevents the user from entering the duplicating into


tables or views is called integrity constraint
Ex: primary key constraint,foreign key constraint,unique
constraint,check constraint.

An integrity constraint is a declarative way to define a


business rule for a column of a table.

68. select 1,col1,col2 from table1. output?

In the above Select statement 1 is constant so it will


display with respect to the other columns information

Result for ur query:

column_heading no_col col2_2 col3_3

1 name1 3000
1 name2 2000

69. Do view contain data?

No, View is a logical table associated with a query.


It will not store any data in it.
Only the query with which the view is created is stored in
the database.

70. oracle is compiler or interpretter,can any one tell me the


answer?

hey priyadharsini u cant call oracle as a data base because


oracle is language which is used to perform some action on
data's on database...... so u can call oracle as both
compiler and interpretter

71. mail-id table contains two columns(email_id,userid)


it contains different types of mail-ids,and no of users.
here username length is differ na,(ex-
tamil@yahoo.com,joshua@hotmail.com like)
now i want to fetch the email-ids only starting from '@'
(ex-@gmail.com,@yahoo.com,@hotmail.com

1.select email_id,user_id,substr(email_id,instr
(email_id,'@'),length(email_id)) from mail_id;

2.select substr(mail_id,1,instr(mail_id,'@')-1) from test_rk_mail


just tel me is that wat u exactly want
table -Email

email_id user_id
joy@yahoo.com joySmith
waine@gmail.com WaineR
@gmail.com tr222
@yahoo.com huip

if m not wrong in understanding ur question that is u


required the 2 records with emailid as @gmail.com and
@yahoo.com
then u can use the sql statment -with like...

select * from email where email_id like '@%';


email_id user_id
@gmail.com tr222
@yahoo.com huip

72. What is Highwatermark?

High Watermark : It's an indicator or Porinter upto which


a Table or Index has ever contained
data

High-water mark is an indicator or pointer up to which


table or index has ever contain data. Let us illustrate
this statement as Suppose we create an empty table , the
high-water mark would be at the beginning of the table
segment.
After inserting data in the table segment , the HWM moves
and point the position up to which the data is in the
segment. By inserting more data in the table segment, HWM
moves further to point the position up to which the data
is in the segment.

&#61663;------- DATA-----------------&#61664;
Un-Used Blocks

Now let us delete the data and see the pointer of HWM

DATA
&#61663;-------&#61664; Empty Blocks Un-Used Blocks

Full Table
Scan
As you seen above by deleting the data , HWM does
not move. The main disadvantage of this is that oracle
always read the blocks up to high water mark in case of
full table scan . You may have ever notice that doing a
count(*) on empty table , takes time to show you 0 rows.
The reason for delay is setting of HWM at higher position.

Now the question arises in front of us , how we set the


high-water mark at lower position ?
The only way to set the HWM is to truncate a table.

Let us see how truncate set the HWM.

No data in the segment

HWM is reset now , after truncating data.

Table where lots of deletion or insertion takes place ,


probably has High HWM. If the HWM is high , it is better
to rebuild table segment for performance sake.

73. I want to know the difference between A Record Type and a Table?

table contains data


record type provides data type

table is a object where as a recordtype is a user defined datatype .


A table can store data from one table at a time
where as different variable or column declared with
sametype can stores data from multiple table

74. what is julian date in oracle

Julian date is the number of days from 01-Jan-4712 BC

75. Write one update command to update seqno field of a table on the basis
of row number?

You can update the seqno which is having the rownum=1 only.
for eg:
If you have a table dept in scott user, you can try the
following command:-

update dept
set deptno=90
where rownum=1;

the above will update the record of the table which having
the rownum=1. and if you want to update some other record
then you have to make query to make the required record as
the first record of the table.

76. What is rule base and cost base optimizer?

one is supported in 8i and another in 9i/10g


cost base optimizer display the cost attributes of query
and it is easier

Rule based optimiser will optimise the query based on the


rules.

Cost based optimiser will optimise the query based on the


statistics available for the table.

77. How can analyze query after generating explain plan ?

After generating explain plan the out put of the query


stored in plan_table.from this table if you finding any
table access (full) in output, the query having performance
problem.

according you can create the index or primary key or unique


in proper table.

78.Can anybody please explain me the flow of the below query.

This query is for finding the Nth highest salary..

SELECT DISTINCT (a.sal)


FROM EMP A
WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B
WHERE a.sal<=b.sal);

If N = 2 then second highest salary will be the o/p.


If N = 3 then third highest salary will be the o/p.
and so on..

Detailed answer available on following weblinks


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

1) How does this query work?

<http://www.sqlteam.com/article/find-nth-maximum-value-in-
sql-server>
2) How this query works?

<http://www.dbapool.com/forumthread/topic_4361.html>

The Query above gives the nth highest distinct salary.

For explanation let a table emp with sal column like below
sal
1200
1300
1500
1200
1250
1700
1250
2000

See DISTINCT word is there in the query


So, you have to find the distinct sal first.
sal
1200
1300
1500
1250
1700
2000
Now see the condition a.sal<= b.sal

This condition compares a.sal and b.sal. The COUNT counts


how many times the a.sal is less than or equal to b.sal,
and gives this value as the output of sub query.
(N.B. comparing to same value means EQUAL SO count is 1).
This count is the value of N.

So after comparision the value of N for different salaries


are like
sal N
1200 6
1300 4
1500 3
1250 5
1700 2
2000 1

Now on querying when you give a value of N the


corresponding value of salary is selected.
Like if you are giving N=2 , then 1700 is displayed.

79.How to find secnd higest salary from table?


select max(sal) from emp
where sal not in (select max(sal) from emp )

select max(sal) from emp where sal < (select max(sal) from emp

80. scope of exception handling in plsql?

Scope of exception in plsql is handled by Exception Block..


this is depends on the code you had written.
suppose u have created one more plsql block inside a plssql
block, if the inner block is not handled any exception then
the outer block will handle the exception by defining the
situation/even like "when others then / when value_error
then... etc "

Note.. when u r using "when Others then" all the exceptions


will handle by this exception.. Even there is no error the
plsql will return 0 for this exception that is executed by
default in a plsql block. So. be carefull while writting
this kind of exception ("When others then")

Raising an error in PL/SQL execution block is nothing


but "Execption". These are of 2 types.
1.Predefined Exception 2. User defined Exception

81. What is the usage of NVL?

NVL function is used to replace the null value by another


value

The syntax for the NVL function is:


NVL( value_in, replace_with )

replace_with is the value that is returned if value_in has


a null value.

82. What is pragma exception and how, when, where us Rank Answer Posted By?

1.Pragma Exception is a pre-compiled exception which is particularly used


to raise the user defined exceptions along with the ORACLE error code.

PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);

2.pragma is compiler directive and pragma exception_init is


used to associate user deifined name to error number(within
range of 20000-20999).

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;
Q.select to_char(4.40453E+15) from dual;

To converting to exponational to number.

You might also like