1.what Is A Cursor For Loop ?

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

1.What is a cursor for loop ?

Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of
values from active set into fields in the record and closes.

When all the records have been processed.

eg. FOR emp_rec IN C1 LOOP

salary_total := salary_total +emp_rec sal;

END LOOP;

2. What is difference between procedure & FUNCTION?

Procedure:-
Execute as a PL/SQL
statement, No RETURN clause in
the header, Can return none, one,
or many values,Can contain a RETURN
statement
Function:-Invoke as part of an
expression,Must contain a RETURN
clause in the header,Must return a single value,Must contain at least one RETURN statement

IN case of procedure only it takes IN, OUT, INOUT parameters.

3. State the difference between implicit and explicit cursor's.

Implicit Cursor are declared and used by the oracle internally. whereas the explicit cursors
are declared and used by the user. More over implicitly cursors are no need
to declare oracle creates and process and closes automatically. The explicit cursor should be
declared and closed by the user.

4. Explain rowid, rownum? What are the pseduocolumns we have?

ROWID - Every record in a database is uniquely identified by system generated value called
Rowid’s. It Is a 18 character hexma decimal value. These Rowid's are physically existence.

ROWNUM - It is an integer number also unique for sorting Normally TOP N Analysis
Other Psudo Column are
NEXTVAL, CURRVAL Of sequence are some exampls

5.What is difference between stored procedures and applicationprocedures,stored function


andapplication function?
Stored Procedure/Function is a compiled database object, which issued for fast response
from Oracle Engine. Difference is Stored Procedure must return multiple value and
function must return single value .

6. 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.

7. Name the tables where characteristics of Package, procedure and functions are stored ?

Characteristics of DB objects are stored in data dictionary. Which can be accessed by Data
dict. views like (user/all/DBA_objects/source).

8. What is ref cursor?

Ref Cursor is cursor variable. It is a pointer to a result set. It is useful in scenarios when
result set is created in one program and the processing of the same in some other, might be
written indifferent language, e.g. firing the select is done in PL/SQL and the processing will
be done in Java.

declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
en emp.ename%type;
begin
open c_emp for select ename from emp;
loop
fetch c_emp into en;
exit when c_emp%notfound;
dbms_output.put_line(en);
end loop;
close c_emp;
end;

9. How many types of database triggers can be specified on a table ? What are they?

Baically there only 1 type of trigger which can be fired on the table. .i.e., DML TRIGGER.

There are 14 types of DML TRIGGER


But we can fire only 12 types of triggers, because remaining 2 types of triggers fire on View.

1. Before insert on ROW LEVEL TRIGGER 2. 1. AFTER insert on ROW LEVEL TRIGGER

3. Before insert on STATEMENT LEVEL TRIGGER 4. After insert on STATEMENT LEVEL


TRIGGER
5. Before update on ROW LEVEL TRIGGER 6. After update on ROW LEVEL TRIGGER

7. Before update on STATEMENT LEVEL TRIGGER. 8. After update on STATEMENT LEVEL


TRIGGER.

9. Before Delete on STATEMENT LEVEL TRIGGER. 10 After Delete on STATEMENT LEVEL


TRIGGER.

11. Before Delete on ROW LEVEL TRIGGER. 12 After Delete on ROW LEVEL TRIGGER

10. How to disable multiple triggers of a tableat at a time?

ALTER TABLE<TABLE NAME> DISABLE ALL TRIGGER

ALTER TABLE TT_DCB DISABLE ALL TRIGGERS

12.What is the difference between view and materialized


view
A view will takes the output of the query. But a materialized view stores the output of the
query which is not possible in view.

13. When do we create bitmap indexes

14.What will be the output for the below Query Select 'High'
from dual where null = null;
The Answer will always be null, since you never can equate a NULL to another NULL. if the
query was "Select 'High' from dual where null IS null;" The answer would have been "High"

15. What is different between union and minus?


Union combines the two table records, its eliminates the duplicate records.

SELECT * FROM A
MINUS
SELECT * FROM B

while minus shows only those rows which are not duplicated of table first in query.

SELECT * FROM A
UNION
SELECT * FROM B
How to calculate the second highest salary of he
16.
employee ?

SELECT MAX(sal)FROM EMP WHERE sal NOT IN (SELECT


MAX(sal) FROM emp

17.How many rows will return from dual table?


only one row one column

18. Select top 3 sal from each dept?


Select distinct top 3 (sal) from emp order by sal desc

19. What is Difference between Having and Where clause?


Having clause is used for filtering grouped data and where clause is used for filtering rows.

20.What is the difference between delete, drop and


truncate?
DELETE: when u r using delete command in oracle the data will be deleted in the table. after
that if u r using rollback the data in the table will be retrieved.

TRUNCATE: in the case of truncate when u r using truncate what ever data in the table it will
be deleted. after that if u r giving rollback also the data will not be retrived. but the
structure of the table is available.

DROP: in the case of DROP if u r using drop the rollback command is not working and
structure and data in the table also deleted. nothing willbe available about that table.
DELETE: delete * from emp;
TRUNCATE: truncate table emp;
drop table emp;

What is the difference between the Primary and Foreign


21.
key?
Primary Key: This is a constraint which is always unique & not null.

Foreign Key: This is a constraint which is just opposite to Primary key. It can be not null &
can accept duplicate value as well.
Foreign key points to same table's primary key or another table's primary key to make a
relationship.

22. How to create table with in the procedure or function?

Create procedure test as


Begin
EXECUTE IMMEDIATE
'CREATE TABLE emp(empno VARCHAR(10),JOB VARCHAR(10),SAL
NUMBER(10))';
end;

23. What is HASH join?

24.How to get employee name from employee table which is


the fiveth highest salary of the table
Select Salary From Employee a Where 5=( Select Count(Distinct Salary) From Employee b
Where a. Salary <= b.Salary )

25. What does “select count(*) from tab” result?


Will display the count of the Tables on the Schema.

26. I have two table one Emp and other is dpt. Emp table has a field
,dept id,name ,sal and dpt table has a field dept id,dept name. Now I
want to find out the emplyee list whose sal is between 2000-3000
from dept x.

Select Name
From Emp e inner join Dpt d
on d.dptid=e.dptid Where sal>=2000 And sal<=3000
And dptname='x'

27. can we use out parameter in a function? Give an example.

create or replace function p_tst (v_p out varchar2)


return varchar as v_g varchar2(50);
begin
select ENAME2 into v_p from emp where empno='11';
return v_p;
end;

28. How to get the 3rd column?


Column Names of a table are stored in the data dictionary
table user_tab_columns along with column_id. By referring
Column_id we can display the column name as:

select column_name from user_tab_columns where table_name


= 'EMP' and column_id = 3;

29. How to copy a table in another table with datas?

If new table is not yet created,


create table new_table as select * from old_table;

if new table is already created,

insert into new table select * from old_table


provided the structure of the new table is same as old
table.

30. How do you count the duplicate records in a table?

Select count (0) from tab1 a


Where a.rowid > any (select b.rowid from tab1 b where
a.col1 =b.col1);

31. what is autonomous transaction?


Autonomous transactions are started by a parent, or main,
Transaction but operates 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.

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


know which will execute first?

33. Briefly explain the difference between first, second, third and
fourth normal forms?

FIrst Normal form : Attribute should be atomic.

Second Normal Form : Non-Key attribute should be fully functionally dependent on key
Attribute.

Third normal Form : There is no transitivity dependency between attribute. Suppose 'y' is
dependent on 'x' i.e. x->y and 'z' is dependent on 'y' i.e. y->z this is transitivity dependency
So we can split table on to two tables os that result will be x->z.

Forth Normal Form : A determinant is any attribute (simple or composite) on which some
other attribute is fully functionally dependent.

35. 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

36. What are various constraints used in SQL?


There are basically 5 types of constraints that are used in creating and managing
tables in SQL

1) Not Null: This doesn't accept null values.. in other words when u declare a
column as not null then its mandatory to enter a value for that column without
leaving it blank

eg: create table emp(empno int not null)

The above example will create a table emp with field empno with not null constraint

2) Unique: This uniquely identifies every row in the table... it restricts the entry of
duplicate values in the table

eg : Create table emp(ename varchar2(20) empno int unique)

In the example when u try to enter a empno which is already existing it will not
accept

3) Primary Key: it is also known as not null key... this uniquely identifies each row
in the table. observe this example

create table emp ( empno int not null unique)

Here we created a table emp with a field empno as not null and unique. Instead of
using both not null and unique constraints simply declare the field as "PRIMARY
KEY" wch satisfies both constraint conditions

create table emp(empno int primary key)

Therefore a primary key is not null and a unique key

4) Foreign key/Referencial Intergrity: This establishes a relationship between


the parent table and child table.. this is very helpful in retreiving the data from
more than 1 tables by providing a link between them.
5) Check Constraint: This defines a condition that each row must satisfy

eg: create table emp(


empno int primary key
ename varchar(10)
deptno number(10)
salary number(10)
constraint emp_min_sal check (salary>0));

6) What are different Oracle database objects?

Different oracle database object

• procedure
• function
• package
• trigger
• index
• cluster
• sequence
• view
• table

7) What is difference between SQL and SQL*PLUS?


SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting
tool. Its a command line tool that allows user to type SQL commands to be executed directly
against an Oracle database. SQL is a language used to query the relational database (DML,
DCL, DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL
commands and PL/SQL.

8) Which datatype is used for storing graphics and images?


BLOB is generally used to store pictures. It stands for Binary Large Object. The maximum
storage limit is 4GB. There is also one limitation using BLOB you can have only one column of
type BLOB.

9) How will you delete duplicating rows from a base table?


DELETE FROM table_name a WHERE rowid > (SELECT min (rowid) FROM table_name b WHERE
a.column_name=b.column_name)

10) There is a % sign in one field of a column. What will be


the query to find it?
SQL> select * from name where name like ' ' escape '';

NAME
--------------------
Girija Sankar

11) When do you use WHERE clause and when do you use
HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and it is
written after GROUP BY clause. The WHERE clause is used when you want to specify a
condition for columns, single row functions except group functions and it is written before
GROUP BY clause if it is used.

12) 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);

For Eg:-

Enter value for n: 2

SAL

---------

3700

13) How do you find the number of rows in a Table ?

Following query will help to find out number of rows in a table

Select count (*) from <table_name>;

14) 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.

15) What is a cursor?


Oracle uses work area to execute SQL statements and store processing information PL/SQL
construct called a cursor lets you name a work area and access its stored information A cursor
is a mechanism used to fetch more than one row in a Pl/SQl block.
16) What are cursor attributes?
%ROWCOUNTreturns number of the rows which are fetched/updated/deleted

%NOTFOUNDreturns true if the cursor does not fetch any row

%FOUNDreturns true if the cursor fetched any row

%ISOPENreturns true if the cursor is open

17) Difference between procedure and function. ?

One more diff is that function must return a value while procedure may or may not return a
value.

18) What are different modes of parameters used in


functions and procedures?
IN: lets you pass values to the subprogram being called
OUT: lets you return values to the caller of subprogram
INOUT: lets you to pass values to the subprogram and return values to the caller of the
subprogram.

19) Can a function take OUT parameters? If not why?

yes fuction can take out variable but the good programing practice is to not use the out
parameter since function must return only one value to the calling envoirnment.

20) 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.

21) How to get 1,4,7,10.....rows from a table?


22) what is the differences between Oracle8i and 9i?

1)User defined datatypes are applicable only for oracle 9i but not oracle 8i.

2)datatype for character large object is LONG for oracle 8i but it is LOBS for oracle9i.

23) What are the datatypes a available in PL/SQL ?

Scalar Types

BINARY_INTEGER
DEC
DECIMAL
DOUBLE PRECISION
FLOAT
INT
INTEGER
NATURAL
NATURALN
NUMBER
NUMERIC
PLS_INTEGER
POSITIVE
POSITIVEN
REAL
SIGNTYPE
SMALLINT
CHAR
CHARACTER
LONG
LONG RAW
NCHAR
NVARCHAR2
RAW
ROWID
STRING
UROWID
VARCHAR
VARCHAR2

DATE
INTERVAL DAY TO SECOND
INTERVAL YEAR TO MONTH
TIMESTAMP
TIMESTAMP WITH LOCAL TIME ZONE
TIMESTAMP WITH TIME ZONE

BOOLEAN
Composite Types
RECORD
TABLE
VARRAY

LOB Types
BFILE
BLOB
CLOB
NCLOB

Reference Types
REF CURSOR
REF object_type

24) View - Base Tables?

View does not occupy memory but Oracle keeps view code in its dictionary (you can check in
user views for example)
If you delete the base table the view becomes INVALID.
In order to make it valid again you have to ether build the deleted table again or create
another view with the same name and structure as deleted table or create synonym with the
same name as deleted table which will point to the table with the same structure.

25) HAVING vs WHERE Clause ?

1) HAVING clause can only be used to filter out the aggegate functions whereas WHERE clause
cannot filter out the aggegate functions.
2) HAVING clause can be used with GROUP BY function where as WHERE clause cannot be used
with group by function.

26) What is a deadlock?

Deadlock is a process it occurs when two users are trying to modify the same data at the same
time then problem occurs with this process then oracle automatically locks one user so that
other user can process the data.

27) Dispaly employee records who gets more salary than the average salary in
their department?

select * from emp a


(select avg(sal) aa deptno from emp group by deptno)x
where a.DEPTNO=x.deptno and a.sal>x.aa

28) What is Cartesian product in the SQL?

Cartesian Products: 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.• A Cartesian product is formed when:– A join condition is
omitted– A join condition is invalid– All rows in the first table are joined to all
rows in the second table

29) Is it possible to update Views? If yes, How, If Not, Why?


A view from a single table can be updated where as a view from multiple tables can not be
updated.

30)About dbms_output.put_line( ) package


what is the maximum size of the message that we can give in
dbms_output.putline();

255 bytes was the size limits of earlier version of oracle..ie prior to 10 g ..in 10g 32767
byte is the limit..

31) Return statement and OUT Parameters


Function must have return statement by which it returns one value.

Though we can use out parameter in function(function not getting called from select
statement or DML) it is not good programming practice to write OUT and IN OUT in function.
In case we wanted to return values using OUT parameters always use procedures.

In case we wanted to return more than one value from function use of ref cursor is preferred
solution not OUT parameters.

32) What is a stored procedure ?


Stored procedure is a sub program and stored in memory for repated execution

33) What is an Exception ? What are types of Exception ?

Exception is nothing but Error. In PL/SQL block we handle these errors in Exception block.
There are two types of exceptions: 1> System define exception and 2> User define exception.
System define exception predefine exceptions like 'ZERO_DEVIDE' NO_DATA_FOUND etc.User
define exceptions is defined by the user and raise in the excution block and then call into the
exception block.

34) 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.

35) Give the structure of the function ?


FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
37) Difference between Stored Procedure and Trigger?
Triggers get invoked automatically when the event specified in it gets fulfilled, it can't return
any value. So user have no control over it's invocation. Whereas stored procedure can be
called as per application requirement and can get output parameters.

38) What the difference between UNION and UNIONALL?


Union will remove the duplicate rows from the result set while Union all does'nt
union wont allow the duplicates, where as union all allows the duplicates.
While we use union the result will be sorted in the asc order of the first col of the select
statement by default. Where as no sorting in union all by default

39) Difference between VARCHAR and VARCHAR2?


Varchar means fixed length character data(size) ie., min size-1 and max-2000

Varchar2 means variable length character data ie., min-1 to max-4000

40) What is the use of indexes?Explain about it?


Index is a schema object that can speed up the retrieval of data by using a pointer.Index
provides direct and fast access to rows by using indexed path to locate data quickly.
Index creates automatically and we can also create.
syntax:
create index index_name to table_name(column _name)
Clustered Index:- A Clustered index is a special type of index that reorders the way records in
the table are physically stored. Therefore table may have only one clustered index.Non-
Clustered Index:- A Non-Clustered index is a special type of index in which the logical order of
the index does not match the physical stored order of the rows in the disk. The leaf nodes of a
non-clustered index do not consists of the data pages. Instead the leaf node contains index rows.

41) PL/SQL Block output ?

You might also like