Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oracle Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

Oracle Page 1 of 87

What are the types of SQL Statement?


Data Definition Language : CREATE, ALTER, DROP, TRUNCATE, GRANT, REVOKE, AUDIT
Data Manipulation Language : INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.
Transactional Control : COMMIT & ROLLBACK, SAVE POINT, SET TRANSACTION
Session Control : ALTER SESSION & SET ROLE
System Control : ALTER SYSTEM.

Create / Alter / Drop Tables and Constraints


Create table with primary key, foreign key, Check and Not null

CREATE TABLE OUTLET_MST (


COMP_CD VARCHAR2(2) CONSTRAINT OUT_COMP_CD_NL NOT NULL,
DIV_CD VARCHAR2(2) CONSTRAINT OUT_DIV_CD_NL NOT NULL,
OUTLET_CD VARCHAR2(4),
OUTLET_NAME VARCHAR2 (50) CONSTRAINT OUT_NAME_NL NOT NULL,
ADDR2 VARCHAR2 (50),
QTY NUMBER(4) CONSTRAINT CK_BILL_DTL_QTY CHECK(QTY>0),
CONSTRAINT OUT_CD_MST_PK PRIMARY KEY (COMP_CD, DIV_CD, OUTLET_CD),
CONSTRAINT OUT_DIV_CD_MST_FK FOREIGN KEY (COMP_CD, DIV_CD) REFERENCES DIVISION_MST(COMP_CD, DIV_CD),
CONSTRAINT OUT_REG_CD_MST_FK FOREIGN KEY (COMP_CD, REGION_CD) REFERENCES REGION_MST(COMP_CD,
REGION_CD)
)
/

Add Check Constraint

ALTER TABLE rol_bill_pay_dtl


ADD CONSTRAINT nn_bill_dtl_size CHECK(r_size IS NOT NULL);

Add Primary Key

ALTER TABLE ROL_BILL_PAY_DTL


ADD CONSTRAINTS pk_bill_pay_dtl primary key (COMP_CD, DIV_CD, FIN_CD, OUTLET_CD, BILL_NO, ITEM_CD,
R_SIZE);

Add Foreign Key

ALTER TABLE rol_bill_pay_dtl


ADD CONSTRAINT fk_bill_dtl_sman_cd foreign key (COMP_CD, DIV_CD, OUTLET_CD, SMEN_CD) references
rol_salesmen_mst (COMP_CD, DIV_CD, OUTLET_CD, SMEN_CD)

Add colum and Check Constraint


ALTER TABLE CITIES ADD COLUMN REGION VARCHAR(26)
CONSTRAINT NEW_CONSTRAINT CHECK (REGION IS NOT NULL);

Unique Constraint
ALTER TABLE SAMP.DEPARTMENT
ADD CONSTRAINT NEW_UNIQUE UNIQUE (DEPTNO);

Drop Primary key


ALTER TABLE Cities DROP CONSTRAINT Cities_PK;

Default
ALTER TABLE SAMP.EMP_ACT ADD COLUMN DEPTNO INT DEFAULT 1;
alter table dept2 modify loc default 'Ramesh'

Duplicate Rows
SELECT * FROM HR_ATT_DTL A WHERE A.ROWID>
(SELECT MIN(B.ROWID) FROM HR_ATT_DTL B
WHERE A.ATT_DATE BETWEEN '25-JUL-09' AND '21-OCT-09'
AND A.ATT_DATE=B.ATT_DATE
AND A.ATT_TIME=B.ATT_TIME
AND A.EMP_ID=B.EMP_ID
Oracle Page 2 of 87

)
ORDER BY 1

DELETE FROM HR_ATT_DTL A


WHERE A.ROWID>(
SELECT MIN(B.ROWID) FROM HR_ATT_DTL B
WHERE A.ATT_DATE BETWEEN '25-JUL-09' AND '31-JUL-09'
AND A.ATT_DATE=B.ATT_DATE AND
A.ATT_TIME=B.ATT_TIME AND A.EMP_ID=B.EMP_ID)

SELECT * FROM HR_ATT_DTL


WHERE ATT_DATE='24-JUL-09'
GROUP BY ATT_TIME, ATT_DATE, EMP_ID
HAVING COUNT(*)>1

Order of SQL statement execution


Where clause, Group By clause, Having clause, Order By clause & Select.

Limitation of Field names


Table name length - 30 char
Column name length - 30 char
Constraint name length - 30 char
Index name length - 30 char
Number of table columns - 1000
Char - (Oracle 7 – 255 bytes, 8 – 2000, 9 – 2000)
Varchar2 - (Oracle 7 – 2000 bytes, 8 – 4000, 9 – 4000)
Number - 1 to 38 (number(38))
Long - 2 GB
RAW – (Oracle 7 – 255 bytes, 8 – 2000, 9 – 2000)
Long RAW – 2 GB
BLOB (Binary Large Object) – 4GB (This Data type is used for Binary data)
CLOB (Character Large Object) – 4GB (This data type is used to store character data.)
NLOB (National Object Large Object) – 4GB (Store character data containing Unicode characters)
BFILE (Binary File): It is a pointer to external file. The files referenced by BFILE exist in the file system. The
database only maintains a pointer to the file. The size of the external file is limited only by the operating system.
ORACLE does not maintain concurrency and integrity of the data.

What is a transaction?
Transaction is logical unit between two commits and commit and rollback.

What is difference between TRUNCATE & DELETE ?


TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on
TRUNCATE
DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.
Delete does not free storage space. But, truncate does.

NVL2
NVL2( string1, value_if_NOT_null, value_if_null )

select empno, nvl2(comm,sal,deptno) from emp;


if comm is null then takes deptno
if comm is not null then takes sal

NULLIF

NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the
function returns expr1. You cannot specify the literal NULL for expr1.
Ex : select emp.*, nullif(empno, mgr) nul from emp;
Oracle Page 3 of 87

LPAD / RPAD
LPAD RPAD

SELECT LPAD('BCD',4,'A') FROM DUAL; SELECT RPAD('BCD',4,'A') FROM DUAL;


ANS : ABCD ANS : BCDA

SELECT LPAD('BCD',5,'A') FROM DUAL; SELECT RPAD('BCD',5,'A') FROM DUAL;


ANS : AABCD ANS : BCDAA

SELECT LPAD('BCD',3,'A') FROM DUAL; SELECT RPAD('BCD',3,'A') FROM DUAL;


ANS : BCD ANS : BCD

SELECT LPAD('BILL ' , 12 , 'CLINTON') FROM DUAL SELECT RPAD('BILL ' , 12 , 'CLINTON') FROM DUAL
ANS : CLINTONBILL ANS : BILL CLINTON

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


COLUMN command
column tsname format a20 heading 'Tablespace Name'
column tbs_size_mb format 999,999 heading 'Size|(MB)'

What is a join? Explain the different types of joins?


Join is a query, which retrieves related columns or rows from multiple tables.

Inner : SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers, orders
WHERE suppliers.supplier_id(+) = orders.supplier_id;

Note : here master is orders.supplier_id is master

Outer : select suppliers.supplier_id, suppliers.supplier_name, orders.order_date


from suppliers, orders
where suppliers.supplier_id = orders.supplier_id(+);

Note : here master is suppliers.supplier_id is master

Self : SELECT e1.ename||' works for '||e2.ename "Employees and their Managers"
FROM emp e1, emp e2
WHERE e1.mgr = e2.empno;

equi : SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date


FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id;

Non equi : SELECT e.ename, e.sal, s.grade


FROM emp e, salgrade s
WHERE e.sal BETWEEN s.losal and s.hisal;

Left Outer Joins & Right Outer Joins

 Assume the tables are to be joined on table1.column1 and table2.column2.


 Assume table1 contains a row with a null value in column1.
 To perform a left outer join, the WHERE clause is
 WHERE table1.column1 = table2.column2 (+);
 In a left outer join, the outer join operator is actually on the right of the equality operator.
 Next, assume table2 contains a row with a null value in column2.
 To perform a right outer join, you switch the position of the outer join operator to the left of the equality
operator and the WHERE clause becomes WHERE table1.column1 (+) = table2.column2;
 Depending on whether table1 and table2 both contain rows with null values, you get different results
depending on whether you use a left or right outer join.

ANSI joins (ansi, inner, outer, cross, natural, full, left outer)
Oracle Page 4 of 87

Inner joins:
select col_1, ... col_n from table_1 join table_2 on col_x = col_y
select col_1, ... col_n from table_1 inner join table_2 on col_x = col_y

select col_1, ... col_n from table_1 join table_2 using (col_x, col_y...)
select col_1, ... col_n from table_1 inner join table_2 using (col_x, col_y...)

select col_1, ... col_n from table_1 natural join table_2


select col_1, ... col_n from table_1 natural inner join table_2

Cross join:
select col_1, ... col_n from table_1 cross join table_2

Outer join:
select col_1, ... col_n from table_1 left join table_2 on col_x = col_y
select col_1, ... col_n from table_1 left outer join table_2 on col_x = col_y

select col_1, ... col_n from table_1 right join table_2 on col_x = col_y
select col_1, ... col_n from table_1 right outer join table_2 on col_x = col_y

select col_1, ... col_n from table_1 full join table_2 on col_x = col_y
select col_1, ... col_n from table_1 full outer join table_2 on col_x = col_y

select col_1, ... col_n from table_1 left join table_2 using(col_x, col_y...)
select col_1, ... col_n from table_1 left outer join table_2 using(col_x, col_y...)

Full join:
select col_1, ... col_n from table_1 right join table_2 using(col_x, col_y...)
select col_1, ... col_n from table_1 right outer join table_2 using(col_x, col_y...)

select col_1, ... col_n from table_1 full join table_2 using(col_x, col_y...)
select col_1, ... col_n from table_1 full outer join table_2 using(col_x, col_y...)

Natural join:
select col_1, ... col_n from table_1 natural join table_2

Inner Joins :

When we join two tables or datasets together on an equality (i.e. column or set of columns) we are performing an
inner join. The ANSI method for joining EMP and DEPT is as follows.

SELECT d.dname, d.loc, e.ename, e.job


FROM dept d
INNER JOIN
emp e
USING (deptno)
/
Or

SELECT d.dname, d.loc, e.ename, e.job


FROM dept d
INNER JOIN
emp e
ON (d.deptno = e.deptno)

The Oracle equivalent of the inner joins we have seen so far is as follows.

SELECT d.dname, d.loc, e.ename, e.job


FROM dept d, emp e
WHERE d.deptno = e.deptno;

Using Where

SELECT d.dname, d.loc, e.ename, e.job


FROM dept d
Oracle Page 5 of 87

INNER JOIN
emp e
ON (d.deptno = e.deptno)
WHERE d.loc = 'DALLAS';
Or
SELECT d.dname, d.loc, e.ename, e.job
FROM dept d, emp e
WHERE d.deptno = e.deptno
AND d.loc = 'DALLAS';

SQL> SELECT *
2 FROM dept d
3 NATURAL JOIN
4 emp e;

Output : All rows and All Columns

Natural Joins

A natural join will join two datasets on all matching column names, regardless of whether the columns are actually
related in anything other than name. For example, the EMP and DEPT tables share one common column name and a
natural join between the two tables would be correct in this scenario.

The following example converts our INNER JOIN from previous examples to a NATURAL JOIN.

SQL> SELECT d.dname, d.loc, e.ename, e.job


2 FROM dept d
3 NATURAL JOIN
4 emp e;

Note that the only identifiable benefit of NATURAL JOIN is that we do not need to specify a join predicate. Oracle
determines all matching column names and uses these to join the two tables.

Using Count in Natural Joins

SQL> SELECT COUNT(deptno)


2 FROM dept d
3 NATURAL JOIN
4 emp e;

SQL> SELECT *
2 FROM dept d
3 NATURAL JOIN
4 emp e;

Output : 0 rows

Probably the best advice to offer regarding NATURAL JOIN is to avoid it! Note that there is no equivalent Oracle
syntax.

Left Outer Joins

In traditional Oracle syntax, outer joins are indicated by (+) and this can sometimes cause issues when attempting to
outer join multiple tables or includeg expressions in join predicates. Oracle outer joins have no concept of direction,
whereas ANSI-compliant outer joins do. In the following example, we will outer join DEPT to EMP using the ANSI
LEFT OUTER JOIN. The way to interpret this is to read the tables in the FROM clause from left to right. The left-hand
table is the superset and the table on the right is the potentially deficient set.

SQL> SELECT deptno, d.dname, d.loc, e.ename, e.job


2 FROM dept d
3 LEFT OUTER JOIN
Oracle Page 6 of 87

4 emp e
5 USING (deptno);

The OUTER keyword is optional but due to the lack of (+) symbols, including it seems to be more descriptive. Note
that this example included the USING clause for our outer join predicates, but the ON clause would also work as
well. The Oracle syntax for this join is as follows.

SELECT d.deptno, d.dname, d.loc, e.ename, e.job


FROM dept d, emp e
WHERE d.deptno = e.deptno (+);

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.

Query, subquery, correlated subquery(write one example)


subquery : select * from emp where deptno in (select deptno from dept where job=’manager’);

First execute the subquery one time, based on that result the main query will be execute

Correlated subquery : select * from emp a where 4>=(select count(distinct sal) from emp b where b.sal>a.sal)

First execute the main query, based on that subquery will be execute

What are the various types of queries ?


Normal Queries
Sub Queries
Co-related queries

Nested queries : A subquery in a where clause

A SQL nested query is a SELECT query that is nested inside a SELECT, UPDATE, INSERT, or DELETE SQL query. Here is a
simple example of SQL nested query:

One approach is to develop a subquery, which involves embedding a query (SELECT-FROM-WHERE block) within the
WHERE clause of another query. This is sometimes referred to as a `` nested query''.

SELECT Model FROM Product


WHERE ManufacturerID IN (SELECT ManufacturerID FROM Manufacturer
WHERE Manufacturer = 'Dell')

SELECT A.job, A.sum_a, B.b


FROM
(select job, sum(a) sum_a from table_A) A,
(select job, b from table_B) B
WHERE A.job = B.job (+)

Compound queries : use set operations (union, union all, intersect, minus)
SELECT * FROM employees WHERE job_id = 'ST_CLERK'
UNION ALL
SELECT * FROM employees WHERE department_id = 50 AND job_id <> 'ST_CLERK';

What is the significance of the & and && operators in PL SQL ?


The & operator means that the PL SQL block requires user input for a variable. The && operator means that the
value of this variable should be the same as inputted by the user previously for this same variable.

Explain Connect by Prior?


Oracle Page 7 of 87

Retrieves rows in hierarchical order.

select lpad(' ',2*(level-1)) || to_char(empno) s


from emp
start with mgr is null
connect by prior empno=mgr

SELECT LEVEL,
LPAD(' ', 2 * LEVEL - 1) || first_name || ' ' ||
last_name AS employee
FROM employee
START WITH employee_id = 1
CONNECT BY PRIOR employee_id = manager_id;

Difference between SUBSTR and INSTR ?


INSTR (String1,String2(n,(m)),
INSTR returns the position of the mth occurrence of the string 2 in string1. The search begins from nth position of
string1.
SUBSTR (String1 n,m)
SUBSTR returns a character string of size m in string1, starting from nth postion of string1

Explain UNION, MINUS, UNION ALL, INTERSECT?


INTERSECT returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query,including all duplicates.

How to Display Odd/ Even number of records from a table?


Odd : Select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
Even : Select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp);

Other way to replace query result null value with a text?


NVL or Decode

What is ROWID?
It is 18-character long, block no, row number are the components of ROWID.

First 6 Characters – Data Object Number


Next 3 Characters – Relative file Number
Next 6 Characters – Block Number
Next 3 Characters – Row Number

What is a pseudo column? Give some examples


A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from
pseudocolumns, but you cannot insert, update, or delete their values.
USER, UID, SYSDATE, ROWNUM, ROWID, NULL, AND LEVEL.

What is the fastest way of accessing a row in a table?


Using ROWID

What is an Integrity Constraint?


It is the rules that prevent the invalid entry into the table.
Ex. Not Null, Unique Key, Primary key, Check, Foreign Key

What is Referential Integrity?


Referential integrity is the rules that govern the relationships between primary keys and foreign keys of the tables
and ensure data consistency. It ensures the value of foreign key be matched by the value of a primary key in another
table.

What is meant by entity integrity?


Entity integrity is when the primary key is in fact unique and not null.

What is self-referential integrity constraint?


If a foreign key reference a parent key of the same table is called self-referential integrity constraint.
Oracle Page 8 of 87

What are various constraints used in SQL?


NULL, NOT NULL, CHECK, DEFAULT, UNIQUE

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?
Disable the foreign key constraint to the parent, drop the table, re-create the table, enable the foreign key
constraint.

Describe the different type of Integrity Constraints supported by ORACLE ?


NOT NULL Constraint - Disallows NULLs in a table's column.
UNIQUE Constraint - Disallows duplicate values in a column or set of columns.
PRIMARY KEY Constraint - Disallows duplicate values and NULLs in a column or set of columns.
FOREIGN KEY Constrain - Require each value in a column or set of columns match a value in a related table's UNIQUE
or PRIMARY KEY.
CHECK Constraint - Disallows values that do not satisfy the logical expression of the constraint.

What is difference between UNIQUE constraint and PRIMARY KEY constraint ?


A column defined as UNIQUE can contain NULLs while a column defined as PRIMARY KEY can't contain Nulls.

What are the Referential actions supported by FOREIGN KEY integrity constraint?
UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of referenced data.
DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted.

What are the Limitations of a CHECK Constraint?


The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and
can't contain sub queries, sequence, the SYSDATE, UID, USER or USERENV SQL functions, or the pseudo columns
LEVEL or ROWNUM.

What is the maximum number of CHECK constraints that can be defined on a column ?
No Limit.

What is the usage of SAVEPOINTS?


SAVEPOINTS are used to subdivide a transaction into smaller parts. To control the Commit and Rollback operations.
Maximum of five save points are allowed.

What is ON DELETE CASCADE?


If primary key values deleted, automatically deletes the foreign key values. It is mentioned in foreign key table.
When ON DELETE CASCADE is specified ORACLE maintains referential integrity by automatically removing dependent
foreign key values if a referenced primary or unique key value is removed

CREATE TABLE R (NO NUMBER(4) , NAME VARCHAR2(20),


CONSTRAINT PK_1 PRIMARY KEY (NO));

CREATE TABLE R1 (NO NUMBER(4), M1 NUMBER(4),


CONSTRAINT FK_1 FOREIGN KEY (NO) REFERENCES R(NO) ON DELETE CASCADE);
SQL> DELETE FROM R;
Note : R1 table records auto delete

What are the data types allowed in a table?


CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG RAW AND BLOB.

ABSTRACT DATYPES

CREATE TYPE CUST_ADDRESS_TY AS OBJECT


(STREET VARCHAR2(25),
CITY VARCHAR2(25),
COUNTRY VARCHAR2(10))
/

CREATE TABLE CUSTOMER (


ID NUMBER(4),
NAME VARCHAR2(25),
ADDRESS CUST_ADDRESS_TY)
Oracle Page 9 of 87

/
SQL> DESC CUSTOMER
SQL>
ID NUMBER(4)
NAME VARCHAR2(25)
ADDRESS CUST_ADDRESS_TY

SQL> SELECT * FROM USER_TYPE_ATTRS;

SQL>
INSERT INTO CUSTOMER VALUES (1,’RAMESH’,CUST_ADDRESS_TY(‘BANK’,’JANA’,’INDIA’));
SQL> SELECT * FROM CUSTOMER;

What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?
CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255 and 2000
for VARCHAR2.

Difference between VARCHAR and VARCHAR2?


1. VARCHAR is going to be replaced by VARCHAR2 in next version. So, Oracle suggests the use VARCHAR2 instead of
VARCHAR while declaring datatype.
2. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
3. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it
will not occupy any space.

How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER
BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

Which datatype is used for storing graphics and images


LONG RAW data type is used for storing BLOB's (binary large objects).

What is difference between Rename and Alias


Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or
column which do not exist once the SQL statement is executed.

What are the pre requisites?


I. To modify datatype of a column?
ii. To add a column with NOT NULL constraints?

To modify the datatype of a column the column must be empty.


To add a column with NOT NULL constrain, the table must be empty.

Where the integrity constraints are stored in Data Dictionary?


The integrity constraints are stored in USER_CONSTRAINTS.

How will you activate/deactivate integrity constraints?


The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint.

If a unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?
It won't, Because SYSDATE format contains time attached with it.

How to access the current value and next value from a sequence? Is it possible to access the current value in a
session before accessing next value?
Sequence name CURRVAL, Sequence name NEXTVAL.
It is not possible. Only if you access next value in the session, current value can be accessed.

What is CYCLE/NO CYCLE in a Sequence?


CYCLE specifies that the Sequence number generates between minimum and maximum values continuously
NO CYCLE specifies that the sequence cannot generate more values after reaching maximum or minimum value.
CREATE SEQUENCE <sequence_name>
START WITH <integer>
INCREMENT BY <integer>
Oracle Page 10 of 87

MAXVALUE <integer> / NOMAXVALUE


MINVALUE <integer> / NOMINVALUE
CYCLE / NOCYCLE
CACHE <#> / NOCACHE
ORDER / NOORDER;

CREATE SEQUENCE customers_seq


START WITH 1
MINVALUE 1
MAX VALUE 100
INCREMENT BY 1
NOCACHE
NOCYCLE;

CREATE SEQUENCE seq_reverse MAXVALUE 150


START WITH 150 INCREMENT BY -5;

What is a View?
A view is a virtual table. Every view has a Query attached to it.
Simple View : Single table view,
Complex View : More than one table view

Does View contain Data?


Views do not contain or store data.
If table delete, then view data will not show. It will show error when select view.
Can a View based on another View?
Yes.

What are the advantages of VIEW?


To protect some of the columns of a table from other users. (Provide additional security for table)
To hide complexity of a query. (Mask the original name)
To hide complexity of calculations. (Simplify commands for developers)
Reduce the complexity of a SQL statement
Restrict access to data

Explain materialized views and how they are used?


Materialized views are objects that are reduced sets of information that have been summarized, grouped, or
aggregated from base tables. They are typically used in data warehouse or decision support systems.
Upto 8i materialized view called as SNAPSHOT.

There are three types of materialized views:


 Read only materialized view
1. There is no possibility for conflicts as they cannot be updated.
2. Complex materialized views are supported
Ex : CREATE MATERIALIZED VIEW hr.employees AS
SELECT * FROM hr.employees@orc1.world;
 Updateable materialized view
1. Can be updated even when disconnected from the master site or master materialized view site.
2. Requires fewer resources than multimaster replication.
3. Are refreshed on demand. Hence the load on the network might be reduced compared to using
multimaster replication because multimaster replication synchronizes changes at regular intervals.
Ex : CREATE MATERIALIZED VIEW hr.departments FOR UPDATE AS
SELECT * FROM hr.departments@orc1.world;
 Writeable materialized view
1. They are created with the for update clause during creation without then adding the materialized
view to a materialized view group. In such a case, the materialized view is updatable, but the
changes are lost when the materialized view refreshes. multimaster replication synchronises
changes at regular intervalls.

What background process refreshes materialized views?


The Job Queue Processes.

What is a SNAPSHOT ?
Snapshots are read-only copies of a master table located on a remote node, which is periodically refreshed to
reflect changes made to the master table.
Oracle Page 11 of 87

What is a SNAPSHOT LOG ?


(for refreshing the latest updations, whenever snapshot log occurs, then refresh the snapshot data)
A snapshot log is a table in the master database that is associated with the master table. ORACLE uses a snapshot
log to track the rows that have been updated in the master table. Snapshot logs are used in updating the snapshots
based on the master table.

Explain an ORA-01555 (Snapshot too old)


You get this error when you get a snapshot too old within rollback. It can usually be solved by increasing the undo
retention or increasing the size of rollbacks. You should also look at the logic involved in the application getting the
error message.

What are the various type of snapshots?


Simple and Complex.
A simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT BY clauses, JOINs, sub-
query or snashot of operations.
- A complex snapshots contain atleast any one of the above.

How can you Enforce Referential Integrity in snapshots?


Time the references to occur when master tables are not in use. Perform the reference the manually immediately
locking the master tables. We can join tables in snapshots by creating a complex snapshots that will based on the
master tables.

What are the options available to refresh snapshots or materialized views?


COMPLETE - Tables are completely regenerated using the snapshots query and the master tables every time the
snapshot referenced.
FAST - If simple snapshot used then a snapshot log can be used to send the changes to the snapshot tables.
FORCE - Default value. If possible it performs a FAST refresh; Otherwise it will perform a complete refresh.

What is Inline View?


A query is written at the from clause of an another query is called inline view.
Ex :
Select e.empno, e.ename, d.dname from emp e, (select deptno, dname from dept) d where e.deptno=d.deptno;

Can a view be updated/inserted/deleted? If Yes under what conditions?


A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or
more tables then insert, update and delete is not possible.

How do I display row number with records?


SELECT rownum,table_name.* FROM table_name;

Difference between group functions and single row functions?


Group functions : AVG, MAX, MIN
Single row functions : lower, upper, substr

What are analytical functions?uses of analytical functions?


Enable to calculate area like market shares. We can use analytical fun's to calculate running total, to find
percentage with a group and top “N queries
Ex:
Analytical Functions : Rank(), dense_rank(),cume_dist(),percent_rank(),
Aggregated Functions : sum(),avg(), max(), min() ..............

Rank :
SELECT deptno, ename,sal,
RANK() OVER (PARTITION BY deptno ORDER BY sal) "rank"
FROM emp
WHERE deptno = 30;

DEPTNO ENAME SAL rank


---------- ---------- ---------- ----------
30 JAMES 950 1
30 WARD 1250 2
30 MARTIN 1250 2
30 TURNER 1500 4
30 ALLEN 1600 5
Oracle Page 12 of 87

30 BLAKE 2850 6

SELECT empno, deptno,


COUNT(*) OVER (PARTITION BY
deptno) DEPT_COUNT
FROM emp
WHERE deptno IN (20, 30);

EMPNO DEPTNO DEPT_COUNT


---------- ---------- ----------
7369 20 5
7566 20 5
7788 20 5
7902 20 5
7876 20 5
7499 30 6
7900 30 6
7844 30 6
7698 30 6
7654 30 6
7521 30 6

11 rows selected.

In absence of any PARTITION or <window_clause> inside the OVER( ) portion, the function acts on entire record set
returned by the where clause. Note the results of Query-3 and compare it with the result of aggregate function
query Query-4.

SELECT empno, deptno,


COUNT(*) OVER ( ) CNT
FROM emp
WHERE deptno IN (10, 20)
ORDER BY 2, 1;

EMPNO DEPTNO CNT


---------- ---------- ----------
7782 10 8
7839 10 8
7934 10 8
7369 20 8
7566 20 8
7788 20 8
7876 20 8
7902 20 8

ROW_NUMBER( ) gives a running serial number to a partition of records. It is very useful in reporting, especially in
places where different partitions have their own serial numbers. In Query-5, the function ROW_NUMBER( ) is used to
give separate sets of running serial to employees of departments 10 and 20 based on their HIREDATE.

SELECT empno, deptno, hiredate,


ROW_NUMBER( ) OVER (PARTITION BY
deptno ORDER BY hiredate
NULLS LAST) SRLNO
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, SRLNO;

EMPNO DEPTNO HIREDATE SRLNO


------ ------- --------- ----------
7782 10 09-JUN-81 1
7839 10 17-NOV-81 2
7934 10 23-JAN-82 3
7369 20 17-DEC-80 1
7566 20 02-APR-81 2
7902 20 03-DEC-81 3
Oracle Page 13 of 87

7788 20 09-DEC-82 4
7876 20 12-JAN-83 5

Query-6 shows the usage of both RANK and DENSE_RANK. For DEPTNO 20 there are two contenders for the first
position (EMPNO 7788 and 7902). Both RANK and DENSE_RANK declares them as joint toppers. RANK skips the next
value that is 2 and next employee EMPNO 7566 is given the position 3. For DENSE_RANK there are no such gaps.

SELECT empno, deptno, sal,


RANK() OVER (PARTITION BY deptno
ORDER BY sal DESC NULLS LAST) RANK,
DENSE_RANK() OVER (PARTITION BY
deptno ORDER BY sal DESC NULLS
LAST) DENSE_RANK
FROM emp
WHERE deptno IN (10, 20)
ORDER BY 2, RANK;

EMPNO DEPTNO SAL RANK DENSE_RANK


------ ------- ----- ----- ----------
7839 10 5000 1 1
7782 10 2450 2 2
7934 10 1300 3 3
7788 20 3000 1 1
7902 20 3000 1 1
7566 20 2975 3 2
7876 20 1100 4 3
7369 20 800 5 4

8 rows selected.

LEAD and LAG


LEAD has the ability to compute an expression on the next rows (rows which are going to come after the current
row) and return the value to the current row.

The syntax of LAG is similar except that the offset for LAG goes into the previous rows.
Query-7 and its result show simple usage of LAG and LEAD function.

SELECT deptno, empno, sal,


LEAD(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC NULLS LAST) NEXT_LOWER_SAL,
LAG(sal, 1, 0) OVER (PARTITION BY dept ORDER BY sal DESC NULLS LAST) PREV_HIGHER_SAL
FROM emp
WHERE deptno IN (10, 20)
ORDER BY deptno, sal DESC;

DEPTNO EMPNO SAL NEXT_LOWER_SAL PREV_HIGHER_SAL


------- ------ ----- -------------- ---------------
10 7839 5000 2450 0
10 7782 2450 1300 5000
10 7934 1300 0 2450
20 7788 3000 3000 0
20 7902 3000 2975 3000
20 7566 2975 1100 3000
20 7876 1100 800 2975
20 7369 800 0 1100

8 rows selected.

FIRST VALUE and LAST VALUE function

The FIRST_VALUE analytic function picks the first record from the partition after doing the ORDER BY. The
<sql_expr> is computed on the columns of this first record and results are returned. The LAST_VALUE function is
used in similar context except that it acts on the last record of the partition.

SELECT empno, deptno, hiredate, hiredate-FIRST_VALUE(hiredate)


OVER (PARTITION BY deptno ORDER BY hiredate) DAY_GAP
Oracle Page 14 of 87

FROM emp
WHERE deptno IN (20, 30)
ORDER BY deptno, DAY_GAP;

EMPNO DEPTNO DAY_GAP


---------- ---------- ----------
7369 20 0
7566 20 106
7902 20 351
7788 20 722
7876 20 756
7499 30 0
7521 30 2
7698 30 70
7844 30 200
7654 30 220
7900 30 286

11 rows selected.

Cumulative sum

SQL> select empno, deptno, sum(sal) over (partition by trunc(deptno) order by empno rows between
unbounded preceding and current row) s, sal from emp;

Running AVG sal

SELECT empno, sal, TRUNC(AVG(sal)


OVER(ORDER BY empno ROWS UNBOUNDED PRECEDING)) AVG_sal
FROM emp
ORDER BY empno

Returns a running count of all records or by partition

SELECT empno, sal, TRUNC(COUNT(sal)


OVER(ORDER BY empno ROWS UNBOUNDED PRECEDING)) AS DAY_COUNT
FROM emp
ORDER BY empno

Return a frequency distribution (how many times the same basic sal is there in that column)

select basic, count(basic) over (partition by basic) freq1 from erphr1.hr_mis_emp_dtl_v where c
order by basic

Difference between DECODE and TRANSLATE and REPLACE?


Ex SELECT DECODE('ABC','A',1,'B',2,'ABC',3) eg SELECT TRANSLATE('ABCGH', 'ABCDEFGHIJ', 1234567899)
from dual; FROM DUAL;
o/p 3 o/p 12378

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;


OUTPUT : TROUBLETHETROUBLE

SELECT TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**') FROM DUAL;


OUTPUT : *THE*

SELECT REPLACE('*THE*','*','TROUBLE') FROM DUAL;


OUTPUT : TROUBLETHETROUBLE

REPLACE : SELECT REPLACE('So What', 'o', 'ay') from dual;


OUTPUT : Say What

TRANSLATE : SELECT TRANSLATE('So What', 'o', 'ay') from dual;


OUTPUT : Sa What
Oracle Page 15 of 87

TRANSLATE('333SQD234','0123456789ABCDPQRST','0123456789') will return


333234

Which is more faster - IN or EXISTS


EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.

IN : select count(*) from prod_hour_lu_dtl where emp_id in (select emp_id from hr_emp_mst);
EXISTS :
select count(*) from prod_hour_lu_dtl a where exists (select '1' from hr_emp_mst b where a.emp_id=b.emp_id);

The EXISTS function searches for the presence of a single row meeting the stated criteria as opposed to the IN
statement which looks for all occurrences. For example:

TABLE1 - 1000 rows and TABLE2 - 1000 rows


(A) SELECT t1.id FROM table1 t1 WHERE t1.code IN (SELECT t2.code FROM table2 t2);
(B) SELECT t1.id FROM table1 t1 WHERE EXISTS (SELECT '1' FROM table2 t2 WHERE t2.code = t1.code)

For query A, all rows in TABLE2 will be read for every row in TABLE1. The effect will be 1,000,000 rows read from
items. In the case of query B, a maximum of 1 row from TABLE2 will be read for each row of TABLE1, thus reducing
the processing overhead of the statement.

Rule of thumb:
If the majority of the filtering criteria are in the subquery then the IN variation may be more performant.
If the majority of the filtering criteria are in the top query then the EXISTS variation may be more performant.
I would suggest they you should try both variants and see which works the best.

Note. In later versions of Oracle there is little difference between EXISTS and IN operations.

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.

EX :

CREATE CLUSTER personnel


( department_number NUMBER(2) )
SIZE 512
STORAGE (INITIAL 100K NEXT 50K);

CREATE TABLE emp1


(empno NUMBER PRIMARY KEY,
ename VARCHAR2(10) NOT NULL
CHECK (ename = UPPER(ename)),
job VARCHAR2(9),
mgr NUMBER REFERENCES scott.emp(empno),
hiredate DATE
CHECK (hiredate < TO_DATE ('08-14-1998', 'MM-DD-YYYY')),
sal NUMBER(10,2) CHECK (sal > 500),
comm NUMBER(9,0) DEFAULT NULL,
deptno NUMBER(2) NOT NULL )
CLUSTER personnel (deptno);

CREATE TABLE dept1


(deptno NUMBER(2),
dname VARCHAR2(9),
loc VARCHAR2(9))
CLUSTER personnel (deptno);

CREATE INDEX idx_personnel ON CLUSTER personnel;

What are the advantages of clusters?


Oracle Page 16 of 87

Access time reduced for joins.

What are the disadvantages of clusters?


The time for Insert increases.

What is difference between a formal and an actual parameter?


Formal parameters are the placeholders for the values of actual parameters

What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?
sql> execute dbms_output.enable(1000000); (10 lacs)
or
sql> SET SERVEROUTPUT ON SIZE 1000000;

How to call STORED PROCEDURE


Calling stored procedure PL/SQL:
exec FABRIC_AGE (1,8,NULL,NULL,'14-NOV-2007');

Calling stored procedure in Reports:


BOXNO_GEN_NEW(:PORDCONFNO, :PBOX_NO, :PCRTN_NO);

Calling stored procedure in Forms:


BOXNO_GEN_NEW(:PORDCONFNO, :PBOX_NO, :PCRTN_NO);

Advantages of Subprograms
Provide Extensibility
– PL/SQL language can be tailored to suit the needs of the application
Promote reusability and maintainability
– Once validated, they can be used with confidence in any number of applications
– Simplifies maintenance/enhancement, as subprogram is only affected if definition changes
Provide Modularity
– Program can be broken down into manageable, well-defined logical modules
– Supports top-down design and stepwise refinement approach to problem solvingAid in abstraction
– Allow mental separation from particulars
– Stubs allow programmers to defer definition of procedures/functions until main
program is tested and debugged
Procedure performs specific action
Stored in database and can be invoked or called by any anonymous block
Can take parameters
Datatype specifier in parameter declaration must be unconstrained
Has two parts
– Specification
• begins with keyword PROCEDURE, ends with procedure name or parameter list
– Body
• begins with keyword IS, ends with keyword END followed by optional procedure name
When a procedure is created, Oracle automatically performs these steps
– Compiles the procedure
– Stores the compiled code
– Stores the procedure in the database
The PL/SQL compiler used to compile the code
If an error occurs, the procedure is created but it is invalid

Enforce Data Security


– Can grant users access to a procedure that queries a table, but not grant access to the table itself

Improve Database Performance


– Less amount of information sent over network
– Compilation not required to execute code
– Procedure present in shared pool so retrieval from disk not required

Memory Savings
– Only one copy of procedure needs to be loaded in memory for execution by multiple users

Increase in Development Productivity


– Can avoid redundant coding and increase productivity, by writing a single procedure
Oracle Page 17 of 87

Integrity
– Procedures need to be tested only once, to guarantee that it returns accurate results

• Procedures improve database security. You can restrict database access by allowing users to access data only
through stored procedures.
• Procedures take advantage of shared memory resources.
How to call STORED FUNCTION
calling stored function in PL/SQL:
SELECT rs_words(13456) FROM dual;

calling stored function in Forms:


:master.tot_words:= RS_WORDS(:MASTER.INVOICE_TOT1);

calling stored function in Reports:


:master.tot_words:= RS_WORDS(:MASTER.INVOICE_TOT1);

or

In Select commands also (select empno, emp_f(empno) from emp);

Explain how procedures and functions are called in a PL/SQL block ?


Function is called as part of an expression.
sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');

What is difference between SQL, PL/SQL and SQL*PLUS?


SQL stands for Structured Query Language.
SQL is a language that can communicate with Oracle server to access the data.

PL/SQL is a procedural language that has both interactive SQL and procedural programming language.
PL/SQL is the procedural language extension to SQL.

SQL is a limited language that allows you to directly interact with the database. You can write queries (SELECT),
manipulate objects (DDL) and data (DML) with SQL. However, SQL doesn't include all the things that normal
programming languages have, such as loops and IF...THEN...ELSE statements. PL/SQL is a normal programming
language.

SQL*Plus is an interactive tool that allows you to type SQL or PL/SQL statements at the command prompt.
SQL*PLUS is oracle command line tool,
SQL*PLUS recognizes SQL and PL/SQL statements and sends them to the server.

What is shared SQL?


Oracle recognizes similar statements. The SQL area is used many times for similar statements.

What are the components of a PL/SQL Block?


Declarative part, Executable part and Exception part.

Syntax
Oracle Page 18 of 87

DECLARE
variable_declarations
BEGIN
program_code
EXCEPTION
exception_handlers
END;

variable_declarations are any variables that you might want to define.


Cursor definitions and nested PL/SQL procedures and functions are also defined here.

GOTO Statement
DECLARE
v_Counter BINARY_INTEGER := 1;
BEGIN
LOOP
INSERT INTO MyTable
VALUES (v_Counter, 'Loop count');
v_Counter := v_Counter + 1;
IF v_Counter > 50 THEN
GOTO l_EndOfLoop;
END IF;
END LOOP;
INSERT INTO MyTable (char_col)
VALUES ('Done!');
<<l_EndOfLoop>>
INSERT INTO MyTable (char_col)
VALUES ('Ramesh');
END;
What are the data types are available in PL/SQL?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.
Composite data types are of two types
PL/SQL RECORDS
PL/SQL COLLECTIONS
----- Index by Tables
----- Nested Tables
----- Varray

VARCHAR2 -- Variable-length character strings


CHAR -- Fixed-length character strings
NUMBER -- Fixed or floating-point numbers
BINARY_INTEGER -- Integer values
PLS_INTEGER -- New in version 2.3; used for fast integer computations
DATE -- Dates
BOOLEAN -- true/false values
NVARCHAR2 - Variable-length character strings using the national character set
NCHAR -- Fixed-length character strings using the national character set
ROWID -- Used to store physical rowids (obsolete, use UROWID instead)
UROWID -- Used to store both physical and logical rowids
LONG -- Used to store long character strings (obsolete)
LONG RAW -- Used to store large amounts of binary data (obsolete)
RAW -- Used to store binary data (obsolete)

What are % TYPE and % ROWTYPE? What are the advantages of using these over data types?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents an 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.

gtype mech_garment_type_mst.garment_Desc%type;
Oracle Page 19 of 87

What is Pl/SQL Records?


Objects of type RECORD are called PL/SQL records
PL/SQL records have uniquely named fields, which can belong to different datatypes
Ex : %TYPE and %ROWTYPE can be used to specify

What is PL/SQL table?


PL/SQL tables are PL/SQL’s way of providing arrays. Arrays are like temporary tables in memory and thus are
processed very quickly. One-dimensional and Two-dimensional arrays.

Objects of type TABLE are called "PL/SQL tables”


PL/SQL tables reside in the private PL/SQL area of the Oracle Server database instance; they are not available as
client-side structures at this time, you cannot declare and manipulate PL/SQL tables in your Oracle Developer/2000
environment.

DECLARE
TYPE t_varray IS VARRAY(2) OF NUMBER; -- Limited to 2 cells
va t_varray := t_varray(0,0);
BEGIN
FOR i in va.first .. va.last LOOP
va(i) := 10*i;
dbms_output.put_line('Index '||to_char(i)||' is: '||to_char(va(i)));
END LOOP;
END;

Features of PL/SQL tables are as follows –

1) It is a composite data type.


2) They are modeled as similar to database tables, but they are not permanent tables. So they can be created and
manipulated only in a PL SQL block.
3) They can have only one column but any data type
4) It will have a primary key which is compulsory for the reference of values
5) There is no name to the column and primary key
6) The data type of the primary key is BINARY_INTEGER.
BINARY_INTEGER is a special data type which can be given only to the column of PL/SQL table for it’s indexing
purpose to store and retrieve values.
Range of binary_integer is -2147483647 to 2147483647
7) Size is unconstrained (Table size grows as the rows are added to the table).
8) Can visualize a Pl/SQL table as a single dimensional vertical array, which can hold unlimited elements.
Suitable for storing and displaying the values of one column of a table given by a cursor

Ex :

Declare
Type nametable IS TABLE OF CHAR(10) INDEX BY BINARY_INTEGER;
vname nametable;
Cursor cf is select ename from emp;
i number;
Begin
Open cf;
i := 1;
Loop
Fetch cf into vname(i);
Exit when cf%NotFound;
i := i+ 1;
End Loop;
Close cf;
For n in 1 .. vname.count
Loop
dbms_output.put_line('Name is '||vname(n));
End Loop;
End;

NESTED TABLES
A nested table is defined as table within another table. They can also be called one-column database tables. A
nested table is collection of rows, represented as column within the table; nested table may contain many rows.
Oracle Page 20 of 87

Using nested tables we can store one-to-many relationships within one table. You can have multiple rows in the
nested table for each row in the main table A nested table is like one-dimensional array but it has the following
differences. Size of an array is fixed but nested table can grow to any size. The subscript of an Array is consecutive
but subscript of a nested table may not be consecutive.

SQL> CREATE OR REPLACE TYPE SUBJECT_TY AS OBJECT


(SUBJNAME VARCHAR2(20),
CREDITS NUMBER(4))
/

SQL> CREATE TYPE SUBJECT_NT AS TABLE OF SUBJECT_TY;

SQL> CREATE TABLE STUDCREDITS (


ROLLNO NUMBER(4),
SUBJ_CREDITS SUBJECT_NT)
NESTED TABLE SUBJ_CREDITS STORE AS SUBJECT_NT_TAB
/

SQL> SELECT TYPECODE, ATTRIBUTES FROM USER_TYPES;

SQL > INSERT INTO STUDCREDITS VALUES (1001, SUBJECT_TY (‘ORACLE’, 24),
SUBJECT_TY (‘JAVA’,’24))
/
SQL> SELECT * FROM S.CREDITS FROM THE (SELECT STBJ_CREDITS FROM STUDCREDITS
WHERE ROLLNO=1001) S
WHERE S.SUBNAME=’ORACLE’
/
OUTPUT : 24

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 a cursor? Why Cursor is required?


Cursor is a named private SQL area (pointer) from where information can be accessed. Cursors are required to
process rows individually for queries returning multiple rows.

What is meant by Scrollable cursor?


While using general cursors, we can only move forward. Once moved forward, we can't go back to previous record in
cursor. But Scrollable cursors move forward as well as backward also.

Restrictions of Cursors
u cannot declare cursor in package specification
not allowed when using db links
cannot use comparison operators
cannot assign NULL
cursor's values cannot be stored in table columns
cannot be used with associative array, nested tables and varray
cannot be use one where the other is expected
cannot reference a cursor variable in cursor FOR LOOP
cannot direclty goto any columns
What is Index and Types?

Unique Index : CREATE UNIQUE INDEX EMPPRIM ON EMP(EMPNO);


Composite Index : CREATE INDEX DEPTNAME ON DEPT(DEPTNO,DNAME);

Using INDEX Hints

Ex : select /*+ INDEX(emp_city idx_job_code) */ empname, job_code from emp where job_code = 'T';

Ex: DELETE /*+ INDEX(emp_status idx_emp_status)*/ FROM emp_status WHERE status = 'T';

INDEX_ASC

Ex : /*+ INDEX_ASC(table index[index .. index]) */


Oracle Page 21 of 87

INDEX_DESC
Ex : /*+ INDEX_DESC (table index[index .. index]) */

FULL
Ex : select /*+ FULL(emp_status) */ empname, status from emp_status where status = 'P';

NO_INDEX
Ex : elect /*+ NO_INDEX(emp_status emp_status) */ empname, status from emp_status where status = 'P';

Why Indexes Aren't Used?


The presence of an index on a column does not guarantee it will be used. The following is a small list of factors that
will prevent an index from being used:
 You perform a function on the indexed column i.e. WHERE UPPER(name) = 'JONES'
 You perform mathematical operations on the indexed column i.e. WHERE salary + 1 = 10001
 You concatenate a column i.e. WHERE firstname || ' ' || lastname = 'JOHN JONES'

Select * from emp where upper(ename)='AA'


Q : it uses the index or not if not why?
A : No, if you create index like this it will work
create index idx_fnc_ename on upper(ename)

select * from emp where ename like 'A%'


Q : it uses the index or not if not why?
A : Like will use an index

select * from emp where ename like '%A'


Q : it uses the index or not if not why?
A : Like will use an index

Difference between “FOR UPDATE” and “WHERE CURRENT OFF” clause in cursor?
FOR UPDATE clause in the cursor declaration part, WHERE CURRENT OF clause is in execution part.

The CURSOR FOR XE "CURSOR FOR" UPDATE using the WHERE CURRENT OF clause is the fastest way to update data.
The cursor will use the rowid to perform the update (or delete) which is the fastest way to locate a specific row in
an Oracle database table.

create or replace procedure wco as


cursor c_f is
select a,b from f where length(b) = 5 for update;
v_a f.a%type;
v_b f.b%type;
begin
open c_f;
loop
fetch c_f into v_a, v_b;
exit when c_f%notfound;
update f set a=v_a*v_a where current of c_f;
end loop;

close c_f;
end;

What is use of a cursor variable? How it is defined?


%TYPE, %ROWTYPE

Explain the two types of Cursors?


Implicit Cursor : The Oracle server uses implicit cursors to parse and execute your SQL statements.
For SQL queries returning a single row, PL/SQL declares all implicit cursors. Oracle performs the open, fetches, and
close for you automatically; these actions are outside of your programmatic control.

 Any given PL/SQL block issues an implicit cursor whenever a SQL statement is executed, as long as an
explicit cursor does not exist for that SQL statement.
Oracle Page 22 of 87

 A cursor is automatically associated with every DML (data manipulation) statement (UPDATE, DELETE,
INSERT).
 All UPDATE and DELETE statements have cursors that identify the set of rows that will be affected by the
operation.
 An INSERT statement needs a place to receive the data that is to be inserted into the database; the implicit
cursor fulfills this need.
 The most recently opened cursor is called the SQL cursor.

Explicit Cursor :
For queries that returning more than one row, the cursor needs to be explicitly declared.
Explicit cursor has three sub-types
1) Simple Cursor
2) Parameterised Cursor
3) Ref Cursor

What are the PL/SQL Statements used in cursor processing?


DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.
(DECLARE, OPEN, FETCH, CLOSE)

How to control how many cursors are open ?


Set OPEN_CURSORS parameter in initialization parameters.

What are the cursor attributes used in PL/SQL ? (Both implicit and Explicit)
Explicit :

CURSOR_NAME%ISOPEN - to check whether cursor is open or not


CURSOR_NAME %ROWCOUNT - number of rows fetched/updated/deleted.
CURSOR_NAME %FOUND - to check whether cursor has fetched any row. True if rows are fetched.
CURSOR_NAME % NOT FOUND - to check whether cursor has fetched any row. True if no rows are fetched.

Implicit :
SQL%ISOPEN, SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND
Ex : UPDATE employee SET salary = salary * 1.1;

What is an Exception? What are types of Exception?


Exception is the error handling part of PL/SQL block. Some of Predefined execptions are.
CURSOR_ALREADY_OPEN
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
VALUE_ERROR
ZERO_DIVIDE
OTHERS.

How will use Exception in PL/SQL (Sub programs)

Pre-Defined Exception

Declare
N number;
Begin
N:=10/0;
Exception
When Zero_divide then
Dbms_output.put_line (‘Zero Divide Error’);
End;

User Defined Exception :

Declare
Myexception Exception;
Begin
If to_char(sysdate,’DY’)=’SUN’ then
Oracle Page 23 of 87

Raise myexception;
End if;

Exception
When Myexception then
Dbms_output.put_line (‘No Transactions Today’);
End;

Can you pass a parameter to a cursor ?


Explicit cursors can take parameters, as the example below shows. A cursor parameter can appear in a query
wherever a constant can appear

CURSOR c_zip (p_state IN zipcode.state%TYPE) IS


SELECT zip, city, state
FROM zipcode
WHERE state = p_state;

The main points to keep in mind for parameters in cursors are as follows:
 Cursor parameters make the cursor more reusable.
 Cursor parameters can be assigned default values.
 The scope of the cursor parameters is local to the cursor.
 The mode of the parameters can only be IN.

declare
CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal > median;
c2 c1%rowtype;
begin
open c1(2000);
loop
fetch c1 into c2;
exit when c1%notfound ;
dbms_output.put_line (c2.ename);
end loop;
close c1;
end;

declare
CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal > median;
--c2 c1%rowtype;
begin
for c2 in c1(2000) loop
dbms_output.put_line (c2.ename);
end loop;
end;

The following PL/SQL code is complex. It involves all of the topics covered so far in this chapter. There is a nested
cursor with three levels, meaning a grandparent cursor, a parent cursor, and a child cursor. Before running this
script, review the code and identify the levels of nesting in the code. When you describe each level of the code,
explain what parameters are being passed into the cursor and why. What do you think the result will be from
running this statement?

SET SERVEROUTPUT ON
1 DECLARE
2 CURSOR c_student IS
3 SELECT first_name, last_name, student_id
4 FROM student
5 WHERE last_name LIKE 'J%';
6 CURSOR c_course
7 (i_student_id IN
student.student_id%TYPE)
8 IS
9 SELECT c.description, s.section_id sec_id
10 FROM course c, section s, enrollment e
11 WHERE e.student_id = i_student_id
Oracle Page 24 of 87

12 AND c.course_no = s.course_no


13 AND s.section_id = e.section_id;
14 CURSOR c_grade(i_section_id IN
section.section_id%TYPE,
15 i_student_id IN
student.student_id%TYPE)
16 IS
17 SELECT gt.description grd_desc,
18 TO_CHAR
19 (AVG(g.numeric_grade), '999.99')
num_grd
20 FROM enrollment e,
21 grade g, grade_type gt
22 WHERE e.section_id = i_section_id
23 AND e.student_id = g.student_id
24 AND e.student_id = i_student_id
25 AND e.section_id = g.section_id
26 AND g.grade_type_code =
gt.grade_type_code
27 GROUP BY gt.description ;
28 BEGIN
29 FOR r_student IN c_student
30 LOOP
31 DBMS_OUTPUT.PUT_LINE(CHR(10));
32 DBMS_OUTPUT.PUT_LINE(r_student.first_name||
33 ' '||r_student.last_name);
34 FOR r_course IN
c_course(r_student.student_id)
35 LOOP
36 DBMS_OUTPUT.PUT_LINE
('Grades for course :'||
37 r_course.description);
38 FOR r_grade IN c_grade(r_course.sec_id,
39 r_student.student_id)
40 LOOP
41 DBMS_OUTPUT.PUT_LINE(r_grade.num_grd||
42 ' '||r_grade.grd_desc);
43 END LOOP;
44 END LOOP;
45 END LOOP;
46 END;

REF cursors or Cursor Variables?


Ref Cursors also known as Dynamic cursors can be associated with as many SELECT statements you want at different
times. You can associate with different SELECT statements at dynamic time.

Ref cursor are just like pointer which can point to different select statements i.e., same cursor can be associated
with different select statements

Regular cursor – static, ref cursors – dynamic, cursors will be change at runtime as per requirement.

There are 2 basic types: Strong ref cursor and weak ref cursor
For the strong ref cursor the returning columns with data type 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.
1.strong ref cursor:
This has a return type defined.
2. Weak ref cursor.
this doesn’t have a return type

Rules for Using Cursor Variables

 You cannot use cursor variables with remote subprograms on another server.
 Do not use FOR UPDATE with OPEN FOR in processing a cursor variable.
Oracle Page 25 of 87

 You cannot use comparison operators to test cursor variables.

 A cursor variable cannot be assigned a null value.

 A REF CURSOR types cannot be used in a CREATE TABLE or VIEW statements.

 A stored procedure that uses a cursor variable can only be used as a query block data source; it cannot be
used for a DML block data source. Using a ref cursor is ideal for queries that are dependent only on
variations in SQL statements and not PL/SQL.

CREATE OR REPLACE PROCEDURE dept_query (


p_deptno emp.deptno%TYPE,
p_sal emp.sal%TYPE
)
IS
emp_refcur SYS_REFCURSOR;
v_empno emp.empno%TYPE;
v_ename emp.ename%TYPE;
BEGIN
OPEN emp_refcur FOR 'SELECT empno, ename FROM emp WHERE deptno = :dept' ||
' AND sal >= :sal' USING p_deptno, p_sal;
DBMS_OUTPUT.PUT_LINE('EMPNO ENAME');
DBMS_OUTPUT.PUT_LINE('----- -------');
LOOP
FETCH emp_refcur INTO v_empno, v_ename;
EXIT WHEN emp_refcur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(v_empno || ' ' || v_ename);
END LOOP;
CLOSE emp_refcur;
END;
/
SQL> exec dept_query(30,1500);

Two select statements in single cursor

REF CURSOR can be associated with more than one SELECT statement at run-time. Before associating a new SELECT
statement, we need to close the CURSOR. Let us have an example as follows:

declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
type rec_emp is record
(
name varchar2(20),
sal number(6)
);
er rec_emp;
begin
open c_emp for select ename,sal from emp where deptno = 10;
dbms_output.put_line('Department: 10');
dbms_output.put_line('--------------');
loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.name || ' - ' || er.sal);
end loop;
close c_emp;
open c_emp for select ename,sal from emp where deptno = 20;
dbms_output.put_line('Department: 20');
dbms_output.put_line('--------------');
Oracle Page 26 of 87

loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.name || ' - ' || er.sal);
end loop;
close c_emp;
end;
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.

Sequence if Trigger firing

 Before statement trigger


 Before rowlevel trigger
 After rowlevel trigger
 After statement trigger

********** ROW LEVEL ****

Create or Replace Trigger Trig_name


After Update or Delete on Mech_sales_cd_mst
For Each Row
Declare
ST Varchar2(2);
Begin
If Updating then
St=’U’;
Elsif Deleting then
St=’D’;
End if;

If st=’U’ then
Insert into mech_sales_cd_mst_his (po, sales_cd) values (
:old.po, :old.sales_cd);
Insert into mech_sales_cd_mst_his (po, sales_cd) values (
:new.po, :new.sales_cd);
end if;
if st=’D’ then
Insert into mech_sales_cd_mst_his (po, sales_cd) values (
:old.po, :old.sales_cd);
End if;
End;

************** STATEMENT LEVEL

create or replace trigger trig_st_1


before insert or delete or update on emp
declare
begin
if to_char(sysdate,'HH24MM')>'1430' then
raise_application_error(-20001,'Time is over');
end if;
end;
/

What are cascading triggers? What is the maximum no of cascading triggers at a time?
When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading. Max =
32.

What is the maximum no. of statements that can be specified in a trigger statement?
One.
Oracle Page 27 of 87

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 is Database Trigger?


A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a result of an
insert in, update to, or delete from a table.

The events that fire a trigger include the following:


DML statements that modify data in a table (INSERT, UPDATE, or DELETE)
DDL statements (CREATE, ALTER, or DROP on clusters, tables, views, procedures, functions, packages, roles)

BEFORE CREATE OR AFTER CREATE trigger is fired when a schema object is created.
BEFORE OR AFTER ALTER trigger is fired when a schema object is altered.
BEFORE OR AFTER DROP trigger is fired when a schema object is dropped.

System events such as startup, shutdown, and error messages


User events such as logon and logoff

A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.


We can use only one trigger of a particular type (so Max : 12 Triggers)
We use correlation names : new and :old can be used to refer to data in command line and data in table
respectively.

1. row level, 2. statement level, 3. instead of, 4.schema level, 5. system level, 6. Compound Trigger

Statement Level :
A statement trigger is fired only for once for a DML statement irrespective of the number of rows affected by the
statement.
For example, if you execute the following UPDATE command STUDENTS table, statement trigger for UPDATE is
executed only for once.
Statement-level trigger is the default type of trigger.
Statement-level triggers are typically used to enforce rules that are not related to data. For example, it is possible
to implement a rule that says “no body can modify BATCHES table after 9 P.M”.

Row Level :
A row trigger is fired once for each row that is affected by DML command. For example, if an UPDATE command
updates 100 rows then row-level trigger is fired 100 times whereas a statement-level trigger is fired only for once.
Row-level trigger are used to check for the validity of the data. They are typically used to implement rules that
cannot be implemented by integrity constraints.

Instead Of :
These trigger are defined on relation-views and object-views. These triggers are used to modify views that cannot
be directly modified by DML commands. Unlike normal trigger, which are fired during the execution of DML
commands, these triggers are fired instead of execution of DML commands. That means instead of executing DML
command on the view, Oracle invokes the corresponding INSTEAD-OF trigger.
The following is a view based on STUDENTS and PAYMENTS tables.

create view newstudent as


select s.rollno, name, bcode,gender, amount
from students s, payments p
where s.rollno = p.rollno;

If you try to insert data into NEWSTUDENT table then Oracle displays the following error.
SQL> insert into newstudent values (15,'Joe','b2','m',2000);
insert into newstudent values (15,'Joe','b2','m',2000)
*
ERROR at line 1:
ORA-01779: cannot modify a column which maps to a non key-preserved table

But, we want the data supplied to NEWSTUDENT view to be inserted into STUDENTS and PAYMENTS table. This can
be done with an instead of trigger as follows:
Oracle Page 28 of 87

create or replace trigger newstudent_it_bi_row


instead of insert on newstudent
for each row
begin
-- insert into STUDENTS table first
insert into students(rollno,bcode,name,gender,dj)
values(:new.rollno, :new.bcode, :new.name, :new.gender,sysdate);
-- insert a row into PAYMENTS table
insert into payments
values(:new.rollno, sysdate, :new.amount);
end;

Compound Triggers

A compound trigger is a single trigger on a table that enables you to specify actions for each of four timing points:

 Before the firing statement


 Before each row that the firing statement affects
 After each row that the firing statement affects
 After the firing statement

The compound trigger body supports a common PL/SQL state that the code for each timing point can access. The
common state is automatically destroyed when the firing statement completes, even when the firing statement
causes an error.

The effect of the compound trigger is similar to what you could achieve with a simple trigger for each of the timing
points for which you needed to code action, with an ancillary package to hold the state that these simple triggers
would share. The obvious advantage of the compound trigger is that the required code is managed in a single
compilation unit, but the more important advantage is that the lifetime of the compound trigger's state is
automatically limited to the duration of the firing statement.

The compound trigger is useful when you want to accumulate facts that characterize the "for each row" changes and
then act on them as a body at "after statement" time. Sometimes you are forced to use this approach (to avoid the
mutating table error). Sometimes this approach gives better performance; for example, when maintaining a
denormalized aggregate value in a master table in response to changes in a detail table, or when maintaining an
audit table.

System events

 Database startup and shutdown


 Data Guard role transitions
 Server error message events

User events (session)

 User logon and logoff


 DDL statements (CREATE, ALTER, and DROP)
 DML statements (INSERT, DELETE, and UPDATE)

Components of a Trigger
The Triggering Event or Statement -- (After Update on inventory)
Trigger Restriction or Constraint - (for each row when <condition>)
Trigger Action – (Begin ….. Statements …… End)

What are the uses of Database Trigger?

 Automatically generate derived column values


 Prevent invalid transactions
 Enforce complex security authorizations
 Enforce referential integrity across nodes in a distributed database
 Enforce complex business rules
 Provide transparent event logging
 Provide auditing
Oracle Page 29 of 87

 Maintain synchronous table replicates


 Gather statistics on table access
 Modify table data when DML statements are issued against views
 Publish information about database events, user events, and SQL statements to subscribing applications

These Database triggers stored in DBA_TRIGGERS view, USER_TRIGGERS view data dictionary.

What are the differences between Database Trigger and Integrity constraints?
A declarative integrity constraint is a statement about the database that is always true. A constraint applies to
existing data in the table and any statement that manipulates the table.

A trigger does not apply to data loaded before the definition of the trigger, therefore, it does not guarantee all data
in a table conforms to the rules established by an associated trigger.

A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.

What are Database Triggers and Stored Procedures?


Database Triggers :: Database Triggers are Procedures that are automatically executed as a result of insert in,
update to, or delete from table.
Database triggers have the values old and new to denote the old value in the table before it is deleted and the new
indicated the new value that will be used. DT are useful for implementing complex business rules which cannot be
enforced using the integrity rules.We can have the trigger as Before trigger or After Trigger and at Statement or Row
level.
e.g:: operations insert,update ,delete 3
before ,after 3*2 A total of 6 combinatons
At statment level(once for the trigger) or row level( for every execution ) 6 * 2 A total of 12.
Thus a total of 12 combinations are there and the restriction of usage of 12 triggers has been lifted from Oracle

7.3 Onwards.
Stored Procedures :: Stored Procedures are Procedures that are stored in Compiled form in the database.The
advantage of using the stored procedures is that many users can use the same procedure in compiled and ready to
use format.

Can you use a commit statement within a database trigger?


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.

Directly its not possible, Using pragma autonomous_transaction it is possible.

CREATE OR REPLACE TRIGGER t_trigger


AFTER INSERT ON t1 FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
i PLS_INTEGER;
BEGIN
SELECT COUNT(*) INTO I FROM t1;
INSERT INTO t2 VALUES (i);
COMMIT;
END;
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.

This happens with triggers. It occurs because the trigger is trying to update a row it is currently using.

Ex :
create table am27
(col1 number, col2 varchar2(30))
/
create or replace trigger am27_trg
before insert or update or delete on am27
for each row
declare
l_chk pls_integer;
begin
Oracle Page 30 of 87

select count(1) into l_chk from am27;


end;
/

SQL>insert into am27 values (1,'234');


SQL>update am27 set col1=2;

ERROR at line 1:
ORA-04091: table SCOTT.AM27 is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.AM27_TRG", line 4
ORA-04088: error during execution of trigger 'SCOTT.AM27_TRG'

How to Avoid Mutation error?


To avoid following can be used :
1.Use statement level triggers instead of row-level triggers.
2.By using temporary tables.
3.By using AFTER triggers so that the triggers can see the table only after the table is acted upon.
4. By using AUTONOMOUS TRANSACTIONS
 Don't use triggers - The best way to avoid the mutating table error is not to use triggers. While the object-
oriented Oracle provides "methods" that are associated with tables, most savvy PL/SQL developers avoid triggers
unless absolutely necessary.

 Use an "after" trigger - If you must use a trigger, it's best to avoid the mutating table error by using an "after"
trigger, to avoid the currency issues associated with a mutating table. For example, using a trigger ":after
update on xxx", the original update has completed and the table will not be mutating.

 Re-work the trigger syntax - Dr. Hall has some great notes on mutating table errors, and offers other ways to
avoid mutating tables with a combination of row-level and statement-level triggers.

 Use autonomous transactions - You can avoid the mutating table error by marking your trigger as
an autonomous transaction, making it independent from the table that calls the procedure.
What are constraining triggers?
A trigger giving an Insert/Update on a table having referential integrity constraint on the triggering table.

What's Locking?
Locking are mechanisms intended to prevent destructive interaction between users accessing data. Locks are used
to achieve.
Oracle Page 31 of 87

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.

Syntax :

RAISE_APPLICATION_ERROR(error_number, error_message);
or
RAISE_APPLICATION_ERROR(error_number, error_message, keep_errors);

The error_number is a number of the error that a programmer associates with a specific error message, and can
be any number between -20,999 and -20,000. The error_message is the text of the error, and it can contain up
to 512 characters.

Ex : in Trigger

CREATE TRIGGER employee_bir


BEFORE INSERT ON employee
FOR EACH ROW
begin
if upper(:new.name) = 'J' then
raise_application_error(20000, 'Sorry, that genius is not allowed.');
end if;
end;

Ex : in Sub Program

Declare
str1 varchar2(40);
Begin
Dbms_output.put_line ('Enter Your Name ::');
Str1:='&Name';
If Length(str1)<2 then
Raise_application_error (-20888, 'What a funny name you have');
Else
Raise_application_error (-20888, 'What a Lovely Name');
End if;
End;

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)

SET SERVEROUTPUT ON
DECLARE
e_constraint_violation EXCEPTION;
PRAGMA EXCEPTION_INIT(e_constraint_violation, -2290);
BEGIN
INSERT INTO course
(course_no, description, created_by, created_date)
VALUES
(COURSE_NO_SEQ.NEXTVAL, 'TEST COURSE', USER, SYSDATE);
COMMIT;
DBMS_OUTPUT.PUT_LINE ('One course has been added');
EXCEPTION
WHEN e_constraint_violation THEN
DBMS_OUTPUT.PUT_LINE ('INSERT statement is '||
'violating a constraint');
END;

What is the Difference between Raise_application_error and Pragma_exception_init?


The main difference is Pragma Exception_init is used for Oracle errors only, whereas raise_application_error is
used for user defined errors.
Oracle Page 32 of 87

What are the return values of functions SQLCODE and SQLERRM?


SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.

A Database Procedure is stored in the Database in which form?


In complied form and Source code form

How to debug the procedure/Function/Package?

use dba_errors(have privileges) /user_errors

select name,type,line,position,text from user_errors where name='<procedure name>'

What is difference Between a PROCEDURE & FUNCTION?


A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
Functions can be called from SQL, procedure cannot
Stored procedures compiled only once and can be called again and again without being compiled each time, this
improves performance and saves time, on the other hand functions compile each time they get called.
You can write Insert, Update, Delete Statements in proc, but can't in Fun. Except Select.
Procedure can call in another project but function work in same project.

create or replace procedure r_p as


no1 number;
begin
select count(*) into no1 from emp;
dbms_output.put_line(no1);
end;

create or replace function r_f return number as


no1 number(4);
begin
select count(*) into no1 from emp;
return(no1);
end;

What is one time procedure?


One time only procedure is executed only once when the package is first invoked within the user session. The
key word END is not used at the end of the one time only procedure.

One time procedures is a Simple anonymous block in a package body which will not have an end keyword . end
for package will serve the both task. this procedure is executed very first time when first call made to this
package.

example:
create package body demo as
function show_num return number is
begin
return num;
end;
begin
num : 50;
end;
end demo;
create or replace package body demo as
function show_num return number is
begin
return num;
end;
begin
num : 50;
end demo;
Oracle Page 33 of 87

Can a function take OUT parameters. If not why?


No. A function has to return a value, an OUT parameter cannot return a value.

What are advantages of Stored Procedures?


Extensibility, Modularity, Reusability, Maintainability and one time compilation.

What are the modes of parameters that can be passed to a procedure ?


IN, OUT, IN-OUT parameters

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 two parts of package?


PACKAGE SPECIFICATION & PACKAGE BODY.

What is a package? What are the advantages of packages?


A package is a group of procedures, functions, cursors, variables and SQL statements created as a single unit. It
is used to store together related objects. A package has two parts, Package Specification or spec or package
header and Package Body.

Package Specification acts as an interface to the package. Declaration of types, variables, constants,
exceptions, cursors and subprograms is done in Package specifications. Package specification does not contain
any code.

Package body is used to provide implementation for the subprograms, queries for the cursors declared in the
package specification or spec.

We can use these in packages


•Cursors
•Variables (scalars, records, tables, etc.) and constants
•Exception names and pragmas for associating an error number with an exception
•PL/SQL table and record TYPE statements
•Procedures and functions

Advantages of package:
----------------------------
A. Modularity
- Encapsulate related constructs.

B. Easier Application Design


- Code and compile specification and body separately.

C. Hiding Information
- Only the declarations in the package specification are visible and accessible to application.
- Private constructs in the package body are hidden and inaccessible.
- All coding is hidden in the package body.

D. Added Functionality
- Persistency of variables and cursors.

E. Better Performance
- The entire package is loaded into memory when the package is first referenced.
- There is only one copy in memory for all users.
- The dependency hierarchy is simplified.

F. Overloading
- Multiple subprograms of the same name.

G. Object Oriented Design


Oracle Page 34 of 87

- While PL/SQL does not yet offer full object-oriented capabilities, packages do offer the ability to
follow many object-oriented design principles. The package gives developers very tight control over how
the modules and data structures inside the package can be accessed.

create or replace package pack1 as


procedure r_p;
function r_f return number;
end pack1;

create or replace package body pack1 as

procedure r_p as
no1 number;
begin
select count(*) into no1 from emp;
dbms_output.put_line(no1);
end r_p;

function r_f return number is


no1 number(4);
begin
select count(*) into no1 from emp;
return(no1);
end r_f;
end pack1;

set serveroutput on;


exec pack1.r_p;
select pack1.r_f from dual;

Using cursors in package

Below given is the example that explains how to access the cursor values.
Oracle Page 35 of 87

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

What is difference between a Cursor declared in a procedure and Cursor declared in a package
specification?
A cursor declared in a package specification is global and can be accessed by other procedures or procedures in
a package.
A cursor declared in a procedure is local to the procedure that cannot be accessed by other procedures.

What is Distributed database?


A distributed database is a network of databases managed by multiple database servers that appears to a user as
single logical database. The data of all databases in the distributed database can be simultaneously accessed
and modified.

Two-phase commit?
Two phase commit is the tool used for handling distributed databases
Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes
or rolls back on all involved nodes to maintain data consistency across the global distributed database.

It has two phases, Prepare Phase and a Commit Phase.


The Prepare Phase, where the global coordinator (initiating database) requests that all participants (distributed
databases) will promise to commit or rollback the transaction. (Note: Any database could serve as the global
coordinator, depending on the transaction.)
The Commit Phase, where all participants respond to the coordinator that they are prepared, then the
coordinator asks all nodes to commit the transaction. If all participants cannot prepare or there is a system
component failure, the coordinator asks all databases to roll back the transaction.

Index types can we index more than one column and how to find which index is activated?
Use explain plan

Give the reasoning behind using an index?


Faster access to data blocks in a table.

Give the two types of tables involved in producing a star schema and the type of data they hold?
Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain data
that will help describe the fact tables.

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


A Bitmap index.
Oracle Page 36 of 87

What are the components of Physical database structure of Oracle Database?


ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and
one or more Control files.

What are the components of Logical database structure of ORACLE database?


Tablespaces and the Database's Schema Objects. (Tables, Views, Sequences, Synonyms, Indexes, Procedures,
Functions, Clusters …)

The logical structures of an Oracle database include schema objects, data blocks, extents, segments, and
tablespaces.

What is a Data File ?


Every ORACLE database has one or more physical data files. A database's data files contain all the database data.
The data of logical database structures such as tables and indexes is physically stored in the data files allocated for
a database.

What are the Characteristics of Data Files ?


A data file can be associated with only one database. Once created a data file can't change size.
One or more data files form a logical unit of database storage called a tablespace.

What is a Redo Log?


The Oracle server maintains the redo Oracle log files to minimize the loss of data in the Database in case of an
uncontrolled shutdown. It stores the database recent transactions data stored in redo log files.

What is the function of Redo Log ?


The Primary function of the redo log is to record all changes made to data.

What is the use of Redo Log Information ?


The Information in a redo log file is used only to recover the database from a system or media failure prevents
database data from being written to a database's data files.

What does a Control file Contain ?


A Control file records the physical structure of the database.
 Database Name
 Names and locations of a database's files and redolog files.
 Time stamp of database creation.

What is the use of Control File?


When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files
that must be opened for database operation to proceed. It is also used in database recovery.

What is a Tablespace?
A database is divided into Logical Storage Unit called tablespaces. Each Tablespace contains one or more
datafiles. Oracle data stored into these datafiles.

What is SYSTEM tablespace and When is it Created?


Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database
is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

Explain the relationship among Database, Tablespace and Data file.


Each databases logically divided into one or more tablespaces One or more data files are explicitly created for
each tablespace.

What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace?


A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are
used to store those objects meant to be used as the true objects of the database.

What is schema?
A schema is collection of database objects of a User.

What are Schema Objects ?


Schema objects are the logical structures that directly refer to the database's data. Schema objects include
Oracle Page 37 of 87

tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages
anddatabase links.

Can objects of the same Schema reside in different tablespaces?


Yes.

Can a Tablespace hold objects from different Schemes?


Yes.

What is Table?
A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user
accessible data. Table data is stored in rows and columns.

What is a Sequence?
Sequence is a Database object used to generate unique sequential integer values.
It can be use in procedures and insert, update, delete ….

Ex : create sequence rs increment by 1 start with 1


insert into r values (rs.nextval, ‘stud1’);

What is a Synonym?
A synonym is an alias for a table, view, sequence or program unit.

A synonym is an alias for one of the following objects:


Table, object table, view, object view, sequence, stored procedure, stored function, package, materialized
view, java class, used defined object type, another synonym

Sql> create synonym t for test


SQL> insert into t values(4);
SQL> insert into t values(5);
SQL> delete from t where a = 5;

SQL> truncate table t;


ERROR at line 1:
ORA-00942: table or view does not exist

SQL> drop table t;


drop table t
*
ERROR at line 1:
ORA-00942: table or view does not exist

Synonyms cannot be used in a drop table, drop view or truncate table/cluster statements. If this is tried, it
results in a ORA-00942: table or view does not exist

Existing synonyms can be found via all_synonyms (or dba_synonyms, or user_synonyms).

What are the types of Synonyms?


There are two types of Synonyms Private and Public.
A Private Synonyms can be accessed only by the owner.
A Public synonyms can be accessed by any user on the database.

What are synonyms used for?


Synonyms are used to : Mask the real name and owner of an object.
Provide public access to an object
Provide location transparency for tables, views or program units of a remote database.
Simplify the SQL statements for database users.

Can database trigger written on synonym of a table and if it can be then what would be the effect if original
table is accessed.
Yes, database trigger would fire.

Can Long/Long RAW be clustered ?


Oracle Page 38 of 87

No.

What is Database Link ?


A database link is a named object that describes a "path" from one database to another.

What are the types of Database Links ?


Private Database Link, Public Database Link & Network Database Link.
Private database link is created on behalf of a specific user. A private database link can be used only when the
owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or
procedures.
Public database link is created for the special user group PUBLIC. A public database link can be used when any
user in the associated database specifies a global object name in a SQL statement or object definition.
Network database link is created and managed by a network domain service. A network database link can be
used when any user of any database in the network specifies a global object name in a SQL statement or object
definition.
Oracle Page 39 of 87

What is Data Block ?


ORACLE database's data is stored in data blocks. One data block corresponds to a specific number of bytes of
physical database space on disk.

How to define Data Block size?


A data block size is specified for each ORACLE database when the database is created. A database users and
allocated free database space in ORACLE datablocks. Block size is specified in INIT.ORA file and cann't be changed
latter.

What is Row Chaining & Row Migration?

Row Chaining
A row is too large to fit into a single database block. For example, if you use a 4KB blocksize for your database, and
you need to insert a row of 8KB into it, Oracle will use 3 blocks and store the row in pieces.

Row Migration
We will migrate a row when an update to that row would cause it to not fit on the block anymore (with all
of the other data that exists there currently). A migration means that the entire row will move and we just
leave behind the «forwarding address». So, the original block just has the rowid of the new block and the
entire row is moved.

What is an Extent ?
An Extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific
type of information.

What is a Segment ?
A segment is a set of extents allocated for a certain logical structure.

What are the different type of Segments ?


Data Segment, Index Segment, Rollback Segment and Temporary Segment.
Oracle Page 40 of 87

What is a Data Segment ?


Each Non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment.
Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.

What is an Index Segment ?


Each Index has an Index segment that stores all of its data.

What is Rollback Segment ?


A Database contains one or more Rollback Segments to temporarily store "undo" information.

What are the uses of Rollback Segment?


To generate read-consistent database information during database recovery to rollback uncommitted transactions
for users.

What is a Data Dictionary?


The data dictionary of an ORACLE database is a set of tables and views that are used as a read-only reference about
the database.

It stores information about both the logical and physical structure of the database.

 The valid users of an Oracle database


 Information about integrity constraints defined for tables in the database
 The amount of space allocated for a schema object and how much of it is in use
Oracle Page 41 of 87

What constitute an ORACLE Instance?


SGA and ORACLE background processes constitute an ORACLE instance. (or) Combination of memory structure
and background process.
A database instance (Server) is a set of memory structure and background processes that access a set of
database files. The processes can be shared by all of the users.
The memory structure that is used to store the most queried data from database. This helps up to improve
database performance by decreasing the amount of I/O performed against data file.

What is SGA?
The System Global Area (SGA) is a shared memory region allocated by ORACLE that contains data and control
information for one ORACLE instance.

The SGA (System Global Area) is an area of memory (RAM) allocated when an Oracle Instance starts up. The
SGA's size and function are controlled by initialization (INIT.ORA or SPFILE) parameters.

What are the components of SGA ?


Database buffers, Redo Log Buffer, Shared Pool and Cursors.

Data buffer cache - It holds copies of data blocks so as they can be accessed quicker by oracle than by reading
them off disk.
 Shared pool – it is used to store SQL and PL/SQL statements. Which is responsible for collecting,
parsing, interpreting, and executing all of the SQL statements.
 Dictionary Cache - information about data dictionary objects. (Definitions of schema objects, integrity
constraints, users information, privileges and roles, auditing information)
 Redo Log Buffer - committed transactions that are not yet written to the redo log files.
 JAVA pool - caching parsed Java programs.
 Streams pool - cache Oracle Streams objects.
 Large pool - used for backups, UGAs, etc.

What is PGA?
Program Global Area (PGA) is a memory buffer that contains data and control information for a server process.

Name the ORACLE Background Process ?


Data Base Writer(DBWR) :: Data Base Writer Writes Modified blocks from Database buffer cache to Data Files.
This is required since the data is not written whenever a transaction is commited.

LogWriter(LGWR) LGWR writes Redo log buffer of SGA into a online redo log file. (Log writer writes the
information whenever transactions commits and log buffer fills).
Oracle Page 42 of 87

System Monitor(SMON) :: The System Monitor performs instance recovery at instance startup. This is useful for
recovery from system failure.

Process Monitor(PMON) :: The Process Monitor performs process recovery when user Process fails. Pmon Clears
and Frees resources that process was using.

Checkpoint(CKPT) :: At Specified times, all modified database buffers in SGA are written to data files by DBWR
at Checkpoints and Updating all data files and control files of database to indicate the most recent checkpoint

Archieves(ARCH) :: The Archiver copies online redo log files to archival store when they are busy.

Recoveror(RECO) :: The Recoverer is used to resolve the distributed transaction in network

Dispatcher (Dnnn) :: The Dispatcher is useful in Multi Threaded Architecture

Lckn :: We can have upto 10 lock processes for inter instance locking in parallel SQL.

What are the two types of Server Configurations?


Dedicated Server Configuration and Multi-threaded Server Configuration.

What is Dedicated Server Configuration?


In a Dedicated Server Configuration a Server Process handles requests for a Single User Process.
(One server and one user)
What is a Multi-threaded Server Configuration?
In a Multi-threaded Server Configuration many user processes share a group of server process.

What is a Parallel Server option in ORACLE?


Multiple instances accessing the same database (Only in Multi-CPU environments).

What is the maximum number of Lock Processes used?


Oracle Page 43 of 87

Though a single LCK process is sufficient for most Parallel Server systems upto Ten Locks (LCK0,....LCK9) are
used for inter-instance locking.

What is the function of Optimizer?


The goal of the optimizer is to choose the most efficient way to execute a SQL statement.
Cost-Based and Rule Based, rule-based optimization is faster than cost-based.
Parameters : CHOOSE, ALL_ROWS, FIRST_ROWS, RULE

Choose : If the Data Dictionary contains no statistics for any of the accessed tables, then the optimizer uses a
rule-based approach, if statistics are available of the accessed tables then the optimizer uses cost-based
approach.

All_Rows : The optimizer uses a cost-based approach for all SQL statements in the session regardless of the
presence of statistics and optimizes with a goal of best throughput.

First_Rows : The optimizer uses a mix of cost and heuristics to find a best plan for fast delivery of the first few
rows.

Rule : The optimizer chooses a rule-based approach for all SQL statements regardless of the presence of
statistics.

What is the use of ANALYZE command ?


To perform one of these function on an index, table, or cluster:
- To collect statistics about object used by the optimizer and store them in the data dictionary.
- To delete statistics about the object used by object from the data dictionary.
- To validate the structure of the object.
- To identify migrated and chained rows of the table or cluster.

Syntax : ANALYZE TABLE <table name> COMPUTE STATISTICS; (for individual table)
EXEC DBMS_UTILITY.analyze_schema('SCOTT','COMPUTE');
EXEC DBMS_UTILITY.analyze_schema('SCOTT','ESTIMATE', estimate_rows => 100);
EXEC DBMS_UTILITY.analyze_schema('SCOTT','ESTIMATE', estimate_percent => 15);

EXEC DBMS_UTILITY.analyze_database('COMPUTE');
EXEC DBMS_UTILITY.analyze_database('ESTIMATE', estimate_rows => 100);
EXEC DBMS_UTILITY.analyze_database('ESTIMATE', estimate_percent => 15);

What is Execution Plan?


The combination of the steps the optimizer chooses to execute a statement is called an execution plan.
This execution plan is basically a step by step instruction for how the statement must be executed.

What is Explain Plan?


The execution plan for an SQL statement can be viewed with the explain plan statement.

What are the different types of PL/SQL program units that can be defined and stored in ORACLE database ?
Procedures and Functions, Packages and Database Triggers.

What are Roles?


Roles are named groups of related privileges that are granted to users or other roles.

What are the use of Roles ?


REDUCED GRANTING OF PRIVILEGES - Rather than explicitly granting the same set of privileges to many users a
database administrator can grant the privileges for a group of related users granted to a role and then grant only
the role to each member of the group.

How to prevent unauthorized use of privileges granted to a Role?


By creating a Role with a password.

What are various privileges that a user can grant to another user?
SELECT, CONNECT, RESOURCES

What Are the System Predefined User Roles?


CONNECT, RESOURCE
Oracle Page 44 of 87

What is Tablespace Quota ?


The collective amount of disk space available to the objects in a schema on a particular tablespace.

What is Auditing ?
Monitoring of user access to aid in the investigation of database use.

What are the different Levels of Auditing ?


Statement Auditing, Privilege Auditing and Object Auditing.
Statement auditing is the auditing of the powerful system privileges without regard to specifically named
objects.
Privilege auditing is the auditing of the use of powerful system privileges without regard to specifically named
objects.
Object auditing is the auditing of accesses to specific schema objects without regard to user.

What is the mechanism provided by ORACLE for table replication?


Snapshots and SNAPSHOT LOGs

What are the steps involved in Database Startup ?


Start an instance, Mount the Database and Open the Database.
Startup the database(Background Process in play )
Mount Database(Database is mount but not open for read and write)
database open(database is ready for read and write)

What are the steps involved in Database Shutdown ?


Close the Database, Dismount the Database and Shutdown the Instance.

What is Full Backup ?


A full backup is an operating system backup of all data files, on-line redo log files and control file that
constitute ORACLE database and the parameter.

Explain the difference between a hot backup and a cold backup and the benefits associated with each.
A hot backup is basically taking a backup of the database while it is still up and running and it must be in archive
log mode.
A cold backup is taking a backup of the database while it is shut down and does not require being in archive log
mode.
The benefit of taking a hot backup is that the database is still available for use while the backup is occurring
and you can recover the database to any point in time. The benefit of taking a cold backup is that it is typically
easier to administer the backup and recovery process. In addition, since you are taking cold backups the
database does not require being in archive log mode and thus there will be a slight performance gain as the
database is not cutting archive logs to disk.

You have just had to restore from backup and do not have any control files. How would you go about
bringing up this database?
I would create a text based backup control file, stipulating where on disk all the data files where and then issue
the recover command with the using backup control file clause.

Can Full Backup be performed when the database is open?


No.

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


Issue the create spfile from pfile command.

Where would you look for errors from the database engine?
In the alert log.

What are the inline and the precompiler directives?


The inline and precompiler directives detect the values directly

What are the OOPS concepts in Oracle.


Oracle does implement the OOPS concepts. The best example is the Property Classes. We can categorise the
properties by setting the visual attributes and then attach the property classes for the objects. OOPS supports
the concepts of objects and classes and we can consider the property classes as classes and the items as objects
Oracle Page 45 of 87

What is the difference between candidate key, unique key and primary key?
Candidate keys are the columns in the table that could be the primary keys and the primary key is the key that
has been selected to identify the rows. Unique key is also useful for identifying the distinct rows in the table. In
short all primary keys are definitely candidate keys. That is one of the candidate keys is chosen as primary key.

Candidate key:

It is important to have an attribute in a table that uniquely identifies a row. An attribute or set of attributes
that uniquely identifies a row is called a Candidate key. This attribute has values that are unique. Consider the
table Vehicle. The values of the attributes Serial#, Regn# and description are unique in every row. Therefore,
all three are Candidate keys. A candidate key can also be referred to as a Surrogate key.

Primary key:

The candidate key that you choose to identify each row uniquely is called the primary key. In the table Vehicle,
if you choose Serial# to identify rows uniquely is called the primary key.

Alternate Key (Unique: A column which is used for unique identification but not a primary key is called the
alternate key

What is concurrency?
Concurrency is allowing simultaneous access of same data by different users.
Locks useful for accessing the database are
a) Exclusive
The exclusive lock is useful for locking the row when an insert, update or delete is being done. This lock should
not be applied when we do only select from the row.
b) Share
We can do the table as Share_Lock as many share_locks can be put on the same resource.

LOCK TABLE : The LOCK TABLE command is used to prevent concurrent processes from changing a table or from
using it.
The two Locking modes are
1)IN SHARE MODE: In which concurrent processes are allowed to perform only read-only operations.
2)IN EXCLUSIVE MODE:Prevents concurrent processes from performing any operation the table.
Only the Owner of the table, DBA, or a user having ALTER, DELETE, INSERT, SELECT, UPDATE can lock a table. A
table can have multiple SHARE LOCKS but only one EXCLUSIVE LOCK
Example: For obtaining EXCLUSIVE LOCK we write.
SQL> LOCK TABLE STUD in EXCLUSIVE MODE;
SQL> LOCK TABLE STUD in EXCLUSIVE MODE NOWAIT;
If we try to obtain a lock using the first statement then Oracle waits if the table is not available for locking. In
second statement it returns immediately.
SQL> LOCK TABLE STUD in SHARE MODE; --- to obtain shared mode lock

What's Consistency
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.

Privileges and Grants


Privileges are the right to execute a particular type of SQL statements.
Privileges are given to the statements (DML)
e.g :: Right to Connect, Right to create, Right to resource
Grants are given to the objects so that the object might be accessed accordingly. The grant has to be given by
the owner of the object.

When creating a user, what permissions must you grant to allow them to connect to the database?
Grant the CONNECT to the user.

What are the PCT FREE and PCT USED


Pct Free is used to denote the percentage of the free space that is to be left when creating a table. Similarly
Pct Used is used to denote the percentage of the used space that is to be used when creating a table
eg.:: Pctfree 20, Pctused 40
Oracle Page 46 of 87

What is Normalisation
Normalisation is the process of organizing the tables to remove the redundancy.
There are mainly 5 Normalisation rules.
a) 1 Normal Form : A table is said to be in 1st Normal Form when the attributes are atomic
Each column in a row can have only one value, and that value must be atomic.
b) 2 Normal Form : A table is said to be in 2nd Normal Form when all the candidate keys are dependant
on the primary key
c) 3rd Normal Form : A table is said to be third Normal form when it is not dependant transitively
d) 4th Normal Form : one-to-may relationships between primary key columns and non-key columns.
e) 5th Normal Form : breaks tables into the smallest possible pieces in order to eliminate all redundancy
within a table.

What is a deadlock? Explain?


Two processes waiting to update the rows of a table, which are locked by other processes, then deadlock arises.

How many columns can table have?


The number of columns in a table can range from 1 to 254.

Explain the difference between $ORACLE_HOME and $ORACLE_BASE.


ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath ORACLE_BASE is where the oracle
products reside.

How would you determine what sessions are connected and what resources they are waiting for?
Use of V$SESSION and V$SESSION_WAIT

How can you enable a trace for a session?


Use the DBMS_SESSION.SET_SQL_TRACE or Use ALTER SESSION SET SQL_TRACE = TRUE;

How would you force a log switch?


ALTER SYSTEM SWITCH LOGFILE;

Give two methods you could use to determine what DDL changes have been made?
You could use Logminer or Streams.

Which date function returns number value?


months_between

Any three PL/SQL Exceptions?


Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

What are PL/SQL Cursor Exceptions?


Cursor_Already_Open, Invalid_Cursor

What are the basic elements of base configuration of an Oracle database?


It consists of
one or more data files, one or more control files, two or more redo log files.

The Database contains


multiple users/schemas, one or more rollback segments, one or more tablespaces, Data dictionary tables
User objects (table,indexes,views etc.,)

The server that access the database consists of


SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)
SMON (System MONito)
PMON (Process MONitor)
LGWR (LoG Write)
DBWR (Data Base Write)
ARCH (ARCHiver)
CKPT (Check Point)
RECO
Dnnn - Dispatcher, and
Oracle Page 47 of 87

LCKn - Lock
Snnn - Server.

Give one method for transferring a table from one schema to another
There are several possible methods, export-import, CREATE TABLE... AS SELECT, or COPY.

What is the purpose of the IMPORT option IGNORE? What is it?s default setting?
The IMPORT IGNORE option tells import to ignore "already exists" errors. If it is not specified the tables that
already exist will be skipped. If it is specified, the error is ignored and the tables data will be inserted. The
default value is N.

What are some of the Oracle provided packages that DBAs should be aware of?
Oracle provides a number of packages in the form of the DBMS_ packages owned by the SYS user. The packages
used by DBAs may include: DBMS_SHARED_POOL, DBMS_UTILITY, DBMS_SQL, DBMS_DDL, DBMS_SESSION,
DBMS_OUTPUT and DBMS_SNAPSHOT. They may also try to answer with the UTL*.SQL or CAT*.SQL series of SQL
procedures.

What happens if the constraint name is left out of a constraint clause?


The Oracle system will use the default name of SYS_Cxxxx where xxxx is a system-generated number. This is bad
since it makes tracking which table the constraint belongs to or what the constraint does harder.

How can you tell if a database object is invalid?


By checking the status column of the DBA_, ALL_ or USER_OBJECTS views, depending upon whether you own or
only have permission on the view or are using a DBA account.

If you have an example table, what is the best way to get sizing data for the production table
implementation?
The best way is to analyze the table and then use the data provided in the DBA_TABLES view to get the average
row length and other pertinent data for the calculation. The quick and dirty way is to look at the number of
blocks the table is actually using and ratio the number of rows in the table to its number of blocks against the
number of expected rows.

What are the different tablespaces in database?


1)system tablespace, 2)temp tablespace, 3)tools tablespace, 4)users tablespace, 5)rollback tablespace,
6)data and index tablespace.

How you will avoid your query from using indexes?


Select /*+FULL*/ * from emp where ....;
SELECT /*+ FULL(a) */ ename, emp_no from emp where emp_no=1234;
Oracle Page 48 of 87

DATA BASE

What is the difference between media recovery & crash recovery..?


Media recovery is a process to recover database from backup when physical disk failure occure.
Crash recovery is an automated process take care by oracle when instance failure occure.

What are the advantages of operating a database in ARCHIVELOG mode over operating it in NO ARCHIVELOG
mode ?
Database in archivelog mode chance to take hot backup and no data loss in recovery. you can use RMAN for
backup and recovery .disadvantage is poor ferformance, and more chance to crash disc.

How does one put a database into ARCHIVELOG mode?


SQLPLUS> connect sys as sysdba
SQLPLUS> startup mount exclusive;
SQLPLUS> alter database archivelog;
SQLPLUS> archive log start;
SQLPLUS> alter database open;

My query was fine last week and now it is slow. Why?


The likely cause of this is because the execution plan has changed. Generate a current explain plan of the
offending query and compare it to a previous one that was taken when the query was performing well. Usually
the previous plan is not available.
Some factors that can cause a plan to change are:
. Which tables are currently analyzed? Were they previously analyzed? (ie. Was the query using RBO and now
CBO?)
. Has OPTIMIZER_MODE been changed in INIT.ORA?
. Has the DEGREE of parallelism been defined/changed on any table?
. Have the tables been re-analyzed? Were the tables analyzed using estimate or compute? If estimate, what
percentage was used?
. Have the statistics changed?
. Has the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT been changed?
. Has the INIT.ORA parameter SORT_AREA_SIZE been changed?
. Have any other INIT.ORA parameters been changed?
. What do you think the plan should be? Run the query with hints to see if this produces the required
performance.

How does one see the uptime for a database?


SELECT to_char (startup_time,'DD-MON-YYYY HH24: MI: SS') "DB Startup Time" FROM sys.v_$instance;
SELECT to_char (logon_time,'Dy dd Mon HH24: MI: SS') "DB Startup Time" FROM sys.v_$session WHERE Sid=1;

Where are my TEMPFILES, I don't see them in V$DATAFILE or DBA_DATA_FILE?


SELECT * FROM v$tempfile;
SELECT * FROM dba_temp_files;

How do I find used/free space in a TEMPORARY tablespace?


SELECT tablespace_name, SUM (bytes_used), SUM (bytes_free) FROM V$temp_space_header
GROUP BY tablespace_name

How can one see who is using a temporary segment?


select s.osuser, s.process, s.username, s.serial#,
Sum (u.blocks)*vp.value/1024 sort_size
from sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter VP
where s.saddr = u.session_addr
and vp.name = 'db_block_size'
and s.osuser like '&1'
group by s.osuser, s.process, s.username, s.serial#, vp.value

What are the dictionary tables used to monitor a database spaces?


DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.

What is user Account in Oracle database?


An user account is not a physical structure in Database but it is having important relationship to the objects in
Oracle Page 49 of 87

the database and will be having certain privileges.


What dynamic data replication?
Updating or Inserting records in remote database through database triggers. It may fail if remote database is
having any problem.

How can we reduce the network traffic?


- Replication of data in distributed environment.
- Using snapshots to replicate data.
- Using remote procedure calls.

How does one connect to an administrative user?


Non Secure : Conn / as sysdba
Secure : Conn sys/password as sysdba

What database aspects should be monitored?


One should implement a monitoring system to constantly monitor the following aspects of a database. Writing
custom scripts, implementing Oracle's Enterprise Manager, or buying a third-party monitoring product can
achieve this. If an alarm is triggered, the system should automatically notify the DBA (e-mail, page, etc.) to take
appropriate action.
Infrastructure availability:
. Is the database up and responding to requests
. Are the listeners up and responding to requests
. Are the Oracle Names and LDAP Servers up and responding to requests
. Are the Web Listeners up and responding to requests

Things that can cause service outages:


. Is the archive log destination filling up?
. Objects getting close to their max extents
. User and process limits reached

Where should the tuning effort be directed?


Consider the following areas for tuning. The order in which steps are listed needs to be maintained to prevent
tuning side effects. For example, it is no good increasing the buffer cache if you can reduce I/O by rewriting a
SQL statement.
Database Design (if it's not too late):
Poor system performance usually results from a poor database design. One should generally normalize to the
3NF. Selective denormalization can provide valuable performance improvements. When designing, always keep
the "data access path" in mind. Also look at proper data partitioning, data replication, aggregation tables for
decision support systems, etc.
Application Tuning:
Experience showed that approximately 80% of all Oracle system performance problems are resolved by coding
optimal SQL. Also consider proper scheduling of batch tasks after peak working hours.
Memory Tuning:
Properly size your database buffers (shared pool, buffer cache, log buffer, etc) by looking at your buffer hit
ratios. Pin large objects into memory to prevent frequent reloads.
Disk I/O Tuning:
Database files needs to be properly sized and placed to provide maximum disk subsystem throughput. Also look
for frequent disk sorts, full table scans, missing indexes, row chaining, data fragmentation, etc
Eliminate Database Contention:
Study database locks, latches and wait events carefully and eliminate where possible. Tune the Operating
System:
Monitor and tune operating system CPU, I/O and memory utilization. For more information, read the related
Oracle FAQ dealing with your specific operating system.

What are the common Import/ Export problems? (


ORA-00001: Unique constraint (...) violated - You are importing duplicate rows. Use IGNORE=NO to skip tables
that already exist (imp will give an error if the object is re-created).
ORA-01555: Snapshot too old - Ask your users to STOP working while you are exporting or use parameter
CONSISTENT=NO
ORA-01562: Failed to extend rollback segment - Create bigger rollback segments or set parameter COMMIT=Y
while importing
IMP-00015: Statement failed ... object already exists... - Use the IGNORE=Y import parameter to ignore these
errors, but be careful as you might end up with duplicate rows.
Oracle Page 50 of 87

What command would you use to create a backup control file?


Alter database backup control file to trace.

Explain what partitioning is and what its benefit is?


Partitioning is a method of taking large tables and indexes and splitting them into smaller, more manageable
pieces.

Name two files used for network connection to a database?


TNSNAMES.ORA and SQLNET.ORA

What is a trace file and how is it created ?


Each server and background process can write an associated trace file. When an internal error is detected by a
process or user process, it dumps information about the error to its trace. This can be used for tuning the
database.

What are the roles and user accounts created automatically with the database?
DBA - role Contains all database system privileges.
SYS user account - The DBA role will be assigned to this account. All of the base tables and views for the
database's dictionary are store in this schema and are manipulated only by ORACLE.
SYSTEM user account - It has all the system privileges for the database and additional tables and views that
display administrative information and internal tables and views used by oracle tools are created using this
username.

What is the difference between restoring and recovering?


Restoring involves copying backup files from secondary storage (backup media) to disk. This can be done to
replace damaged files or to copy/move a database to a new location.
Recovery is the process of applying redo logs to the database to roll it forward. One can roll-forward until a
specific point-in-time (before the disaster occurred), or roll-forward until the last transaction recorded in the
log files. Sql> connect SYS as SYSDBA
Sql> RECOVER DATABASE UNTIL TIME '2001-03-06:16:00:00' USING BACKUP CONTROLFILE;

What is an UTL_FILE? What are different procedures and functions associated with it?
The UTL_FILE package lets your PL/SQL programs read and write operating system (OS) text files. It provides a
restricted version of standard OS stream file input/output (I/O).

The Oracle utl_file package allows Oracle SQL and PL/SQL to read and write directly from flat files on the
server.

Writing custom messages to the Oracle alert log requires the following steps:

1- Locate the background dump directory (the location of the alert log).
2- Set the utl_file_dir initialization parameter.
3- Execute utl_file.fopen to open the file for write access.
4- Use dbms_output.put_line to write the custom message to the alert log.
5- Execute utl_file.fclose to close the file

FCLOSE Procedure Closes a file


FCLOSE_ALL Procedure Closes all open file handles
FCOPY Procedure Copies a contiguous portion of a file to a newly created file
FFLUSH Procedure Physically writes all pending output to a file
FGETATTR Procedure Reads and returns the attributes of a disk file
FGETPOS Function Returns the current relative offset position within a file, in bytes
FOPEN Function Opens a file for input or output
FOPEN_NCHAR Function Opens a file in Unicode for input or output
FREMOVE Procedure Deletes a disk file, assuming that you have sufficient privileges
FRENAME Procedure Renames an existing file to a new name, similar to the UNIX mv function
FSEEK Procedure Adjusts the file pointer forward or backward within the file by the number of bytes
specified
GET_LINE Procedure Reads text from an open file
GET_LINE_NCHAR Reads text in Unicode from an open file
GET_RAW Function Reads a RAW string value from a file and adjusts the file pointer ahead by the number
of bytes read
IS_OPEN Function Determines if a file handle refers to an open file
NEW_LINE Procedure Writes one or more operating system-specific line terminators to a file
Oracle Page 51 of 87

PUT Procedure Writes a string to a file


PUT_LINE Procedure Writes a line to a file, and so appends an operating system-specific line terminator
PUT_LINE_NCHAR Writes a Unicode line to a file
PUT_NCHAR Procedure Writes a Unicode string to a file
PUTF Procedure A PUT procedure with formatting
PUTF_NCHAR Procedure A PUT_NCHAR procedure with formatting, and writes a Unicode string to a file, with
formatting
PUT_RAW Function Accepts as input a RAW data value and writes the value to the output buffer
Oracle Page 52 of 87

GENERAL

What is the difference between two null values in a column?


No two Null values are same and if we compare two null values each other the value is garbage. We cannot
determine the value

In a client server environment, what would be the major work that the client deals with?
The client deals with the user interface part of the system.

Why is the most of the processing done at the sever?


To reduce the network traffic and for application sharing and implementing business rules.

Why do stored procedures reduce network traffic?


When a stored procedure is called, only the procedure call is sent to the server and not the statements that the
procedure contains.

What is the difference between file server and a database server?


A file server just transfer all the data requested by all its client and the client processes the data while a
database server runs the query and sends only the query output.

Write the order of precedence for validation of a column in a table ?


Write the order of precedence for validation of a column in a table ?
a. done using Integarity Constraints.
b. done using Database triggers.

Where the Pre_defined_exceptions are stored ?


In the standard package.
Procedures, Functions & Packages

What is the difference between Fields and FlexFields?


A field is a position on a form that one uses to enter, view, update, or delete information. A field prompt
describes each field by telling what kind of information appears in the field, or alternatively, what kind of
information should be entered in the field.

A flexfield is an Oracle Applications field made up of segments. Each segment has an assigned name and a set of
valid values. Oracle Applications uses flexfields to capture information about your organization. There are two
types of flexfields: key flexfields and descriptive flexfields.

State true or false. EXISTS, SOME, ANY, ALL are operators in SQL?
True.

ALL : Compares a value to each value in a list or returned by a subquery and yields TRUE if all of the individual
comparisons yield TRUE.
ANY, SOME : Compares a value to each value in a list or returned by a subquery and yields TRUE if any of the
individual comparisons yields TRUE.

Exists or Not Exists:


1. select * from hr_emp_mst where exists (select emp_id from hr_emp_mst where emp_id=60029)
2. select * from hr_emp_mst where not exists (select emp_id from hr_emp_mst where emp_id=60029)

ALL (Both Query Result Same)


SELECT ts_date, emp_id, gross_pay FROM hr_salary_mst
WHERE gross_pay > ALL (SELECT gross_pay FROM hr_salary_mst WHERE emp_id = 60029);

SELECT * FROM hr_salary_mst


WHERE gross_pay > (SELECT max(gross_pay) FROM hr_salary_mst WHERE emp_id = 60029);

ANY ((Both Query Result Same)


SELECT ts_date, emp_id, gross_pay FROM hr_salary_mst
WHERE gross_pay > ANY (SELECT gross_pay FROM hr_salary_mst WHERE emp_id = 60029);
Oracle Page 53 of 87

SELECT * FROM hr_salary_mst


WHERE gross_pay > (SELECT min(gross_pay) FROM hr_salary_mst WHERE emp_id = 60029);

Which command executes the contents of a specified file?


START or @.

What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all.

What are the wildcards used for pattern matching.?


_ for single character substitution and % for multi-character substitution

ODBC stands for?


Open database connectivity

Display the number value in Words ?


SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;
Oracle Page 54 of 87

Oracle 9i new Features

Suite and not single coat


Oracle9iAS ( Application Server)
Oracle9iDB ( Database)
Oracle9iDS ( Developer Suite)

CASE Expression

SQL> select
2 case when salary between 6 and 8 then '6-8'
3 when salary in (9,10) then '9-10'
4 when exists (select null from avg_sal where avg_sal = salary)
5 then 'EXISTS'
6 when to_char(salary) like '2%' then 'Like2'
7 when salary is null then 'Null'
8 else 'ELSE Empno: '|| emp_no
9 end
10 AS case_test
11 from emp
12 /

Case using in PL/SQL

SQL> CREATE FUNCTION pay_status (


sal_in IN NUMBER
) RETURN VARCHAR2 IS
BEGIN
RETURN CASE
WHEN sal_in < 1000
THEN 'Low paid'
WHEN sal_in BETWEEN 1001 AND 2000
THEN 'Reasonably well paid'
WHEN sal_in BETWEEN 2001 AND 3001
THEN 'Well paid'
ELSE 'Overpaid'
END;
END;
/

SQL> SELECT ename, pay_status(sal) AS pay_status FROM emp;

Filtering data with CASE expressions

SELECT e.ename, e.empno, e.job, e.sal, e.hiredate, d.deptno, d.loc


FROM dept d, emp e
WHERE d.deptno = e.deptno
AND CASE
WHEN e.deptno = 10 AND e.sal >= 1000
THEN 0
WHEN e.hiredate > DATE '1990-01-01'
THEN 0
WHEN d.loc = 'CHICAGO'
THEN 0
ELSE 1
END = 1
Note : If END = 1 Case condition satisfies records, if END = 0 case condition fails.

List Partitioning
Oracle Page 55 of 87

Oracle started providing the facility to divide a large table into partitions right from Oracle8. But the paritioning
is primarly based on the range. That means, Oracle determines into which partition a row is placed based on the
range to which the value in the column belongs.
The following example shows how to create a partition based on the rate of the product.

create table sales_history


( pid number(5),
qty number(3),
rate number(5),
dp date,
state char(2)
)
partition by range(rate)
( partition low values less than (1000),
partition normal values less than(5000),
partition high values less than (maxvalue)
);

Index Skip Scan

Until Oracle8i, a composite index (an index that is based on multiple columns) is used only when either all
columns in the index are referred in the query or at least leading columns are referred.
But in Oracle9i, Oracle uses index even when leading columns are not used.A composite index can be used even
when leading column(s) are not used in the query through a technique called as Index Skip Scan.
During index skip scan, index is searched for each distinct value and then for each distinct value the index is
searched for target values (values in the remaining column(s)). As the result the index scan skips leading values
and starts searching for target values even when they do not belong to leading columns.
For example assume we have the following SALES table:

create table sales


( prodid number(5),
custid number(5),
qty number(2),
.
.
.
);

Now, if we create an index on PRODID and CUSTID as follows:


create index sales_prodid_custid_idx on sales(prodid, custid);
Then the following query will use index as the leading column is referred.
select * from sales where prodid = 100;
But the following query will not use index in Oracle8i.
select * from sales where custid = 1002;
However, in Oracle9i, the same above query will use index by using Index Skip Scan technique.

MERGE statement

This new statement is used to combine Insert and Update commands into a single command. This is also called
as Upsert functionality.
This command is used where we have to insert row of one table into another table if the new row is not
available in the old table. If new row is already available in the old table then the row in the old table is
updated.

MERGE INTO PRODUCTS P


USING NEWPRODUCTS NP
ON (P.PRODID = NP.PRODID)
WHEN MATCHED THEN
UPDATE
SET RATE = NP.RATE
WHEN NOT MATCHED THEN
INSERT (P.PRODID, P.NAME,P.RATE)
VALUES (NP.PRODID,NP.NAME,NP.RATE);

The above MERGE command reads data from NEWPRODUCTS only for once. The same operations in Oracle8i
Oracle Page 56 of 87

needs two different scans of NEWPRODUCTS table - one for INSERT and another for UPDATE command.

Multitable Insert

It is used to take data from one table and insert the data into multiple tables.
Multitable insert facility of Oracle9i will allow the source table to be scanned only for once and insert the data
into multiple tables.
The following example will explain how to use the new feature.

INSERT FIRST
WHEN credit_limit >=50000 THEN
INTO special_customers VALUES(custid,name,credit_limit)
INTO customers
ELSE
INTO customers
SELECT * FROM oldcustomers;

The above command takes data from OLDCUSTOMERS table and first inserts a row into SPECIAL_CUSTOMERS
table if column CREDIT_LIMIT is more than 50000 and then it inserts the same row into CUSTOMERS table also.
If the condition given in WHEN clause is not satisfied then it will execute the ELSE part, where the row taken
from OLDCUSTOMERS is inserted into CUSTOMERS table.

Flashback Query

Before users can use flashback query, DBA has to configure the database for flashback query.
What do we need to use Flashback query?
The following steps are to be performed by DBA to enable a user to use flashback query.
Set the UNDO_RETENTION initialization parameter to a value that represents how far in the past you might want
to query. This is generally set to 10800, which is 3 hours.
Set the initialization parameter UNDO_MANAGEMENT=AUTO. It is also set by default.
Grant EXECUTE privilege on the DBMS_FLASHBACK package to users who want to use it.
For this login into Oracle as sysdba as follows:
sql>connect sys as sysdba
Enter password: .....
Then execute the following command to grant ExECUTE privilege to user SRI
Grant execute on dbms_flashback to sri;

The following are the steps to be taken for Flashback query.


Find out the point in time in the past to which you have to go
Use ENABLE_AT_TIME procedure of DBMS_FLASHBACK package to enable flashback query.
Then execute the requried SELECT command to retrieve the data.
Disable flashback query using DISABLE method of DBMS_FALSHBACK package.
The following example will demonstrate how you can get the rate of the product with id 102 on 1st March,2002
(inspite of serveral changes to rate since then).

EXECUTE DBMS_FLASHBACK.ENABLE_AT_TIME ('01-Mar-2002');


SELECT rate FROM products WHERE prodid = 102;
EXECUTE DBMS_FLASHBACK.DISABLE;

First line takes database to 01-mar-2002. Then SELECT command retrieves RATE from PRODUCTS table where
PRODID is 102. And finally we disable flashback query so that current data is used.
The following is another example where we take the data from the table into cursor and then uses cursor to
insert rows into another table.

-- enable flashback query


EXECUTE DBMS_FLASHBACK.ENABLE_AT_TIME('01-mar-2002');

-- retrieve data into a cursor


OPEN c FOR 'SELECT * FROM employees WHERE ...';

-- disable flashback query.


DBMS_FLASHBACK.DISABLE;

-- use data in the cursor


LOOP
Oracle Page 57 of 87

FETCH ...;
EXIT WHEN c%NOTFOUND;
INSERT ...;
END LOOP;

ANSI Join

SELECT COUNT(DISTINCT E.EMP_ID) CNT FROM HR_EMP_MST E INNER JOIN HR_MONTH_SALARY_DTL S O


E.EMP_ID=S.EMP_ID
Inner like (inner join)
Left like (inner loin)
Right like (Outer join)Full like (Full join)

New Functions
External Table
Table Function
Object-relational Extensions

Export Utility

Full backup.
EXP ERPFINAL/ERP123@PL FILE=E:\ERP_BACKUP\ERP_FINAL\ERPFINAL050808e.DMP LOG=E:\ERP_BACKUP\
ERP_FINAL\ERPFINAL0500808e.LOG

Particular Table
exp scott/tiger@ramesh TABLES=emp,bonus file=c:\temp.dmp LOG=c:\temp.LOG

Particular Tables from Different Users


exp SYSTEM/MANAGER@RAMESH FILE=TEMP.dmp LOG=c:\temp.LOG
TABLES=(scott.emp,PRODUCTION.PROD_EMP_MST) GRANTS=y INDEXES=y

With condition
EXP SCOTT/TIGER FILE= abc.dmp TABLES=emp QUERY=\” WHERE SAL < 2000 \”

IMPORT UTILITY

FULL DMP IMPORT


IMP SYSTEM/POKARNA@PL FROMUSER=ERP TOUSER=ERP_APPAREL FILE=E:\ERP_BACKUP\erp0906.dmp LOG=E:\
ERP_BACKUP\ERP.LOG COMMIT=Y BUFFER=500000

Particular Tables
IMP SYSTEM/STANZA@PL FROMUSER=ERPFINAL TOUSER=ERPFINAL TABLES=(HR_EMP_MST, HR_SEC_MST) FILE=D:\
ERPBACKUP\ERPFINAL\ERPFINAL060408m.DMP LOG=C:\ERPFINAL060408m.LOG COMMIT=Y BUFFER=500000

Particular Tables from Different Users

IMP SYSTEM/STANZA@PL FROMUSER=ERPFINAL TOUSER=ERPFINAL TABLES=(jones.accts, scott.emp,scott.dept)


FILE=D:\ERPBACKUP\ERPFINAL\ERPFINAL060408m.DMP LOG=C:\ERPFINAL060408m.LOG COMMIT=Y
BUFFER=500000
Oracle Page 58 of 87

Personal

What r my interests?
Upgrade Technical skills, Learn new things, Playing

What r my +ve qualities?


Patients, Hard work, Logical Thinking

What are your strengths ?


Honesty, positive attitude, good team player

What are your weakness?

Introduce Yourself
Present working with pokarna limited, apparel division. Its a group of manufacturing companies like granites,
textile, readymade, natural stone; the management would like to develop software in-house only. So they
recruit a software team for group of companies for in-house software development purpose. There we
developed software on oracle backend, d2k front end. In this software team my role is sr.developer cum litter
bit dba activities also. This software having several modules like merchandising, purchasing, material
management, costing, cutting, production, quality control, warehouse, hr and personnel, accounts & finance
and retail outlets software also. These all modules are integrated in single user only. I was participated in all
these modules for developing reports, forms and database designing. We developed so many reports, forms for
company management and user requirements.
I am very good in SQL Queries and Reports, this will be helpful for u.

In pokarna (I mean present working company), I am having 51/2 years experience is there.
Before that I worked with Legend Drugs & Formulations Pvt. Ltd., it was located at Hyd only. In that I worked as
a Foxpro Programmer and little bit oracle and d2k. (duration : Nov – 2000 to Dec – 2003)
Before that I worked with Sujana Industries Ltd., it was located at Hyd only. As a foxpro programmer only.
Duration ( May-1999 to Nov-2000)
Before this company I worked as a foxpro programmer, that’s why I did’t mention in resume.

Actually in forms, reports and oracle (6 years experience is there).


Oracle Page 59 of 87

Advanced SQL & PL/SQL

What is Parsing ?
Syntax checking, privileges checking and allocating Private SQL Area.

What is the difference between anonymous blocks and stored procedures ?


Anonymous Block : All the PL/SQL that you have written up to this point has been anonymous blocks that were
run as scripts and compiled by the database server at runtime.
Anonymous blocks have no name and thus cannot be called by another block. They are not stored in the
database and must be compiled and then run each time the script is loaded.
Stored procedure is compiled and stored in database with the dependency information as well.

What are standalone procedures ?


Those that are not part of package

How is a PL/SQL program stored in database?


Parsed code is stored. It's called P-code

Can you delete a column in table with indexes in Oracle?


We can delete a column with indexes. But if there is a Primary or foreign key present make sure, foreign keys
are deleted first and then column with Primary key.

Can we add a Default value to a column with table having data and the column having null and not null
values?
Yes. But Default value would be applied only to the newly inserted rows.
And existing column values will not be changed
Sql>Alter table dept modify loc default 'Ramesh'

Can we add a Not Null column to a table with data? If no, any workaround in Oracle?
No, we cannot.
Workaround : Provide a Default value to the column being added, along with the NOT NULL constraint. Then the
column gets added and all the existing rows contain the default value for the new column.
SQL> Alter table EMP add comm2 number not null default 100 -- it works

Can we delete a NOT NULL column from a table in Oracle?


Yes, we can

While doing an ascending order sort on a column having NULL values, where does the NULLs show up in the
result set? At the beginning or at the end?
Eg: select col1 from table1 order by col1 desc NULLS LAST
Eg: select col1 from table1 order by col1 desc NULLS FIRST

Time of execution of an SQL Statement


Sql> SET TIMING ON
SQL> select * from emp

What is the Datatype of NULL in Oracle?


Oracle Page 60 of 87

Datatype of NULL is "char(0)" and size is '0'

1.
Declare
var1 Varchar2 (1) := Null;
var2 Varchar2 (1) := Null;
Begin
If (var1 = var2)
Then
DBMS_OUTPUT.put_line ('Working');
Else
DBMS_OUTPUT.put_line ('null != null');
End If;
End;

Output : null != null

2.
SELECT decode(null,null,1,0) from dual;
Output : 1

3.
select
case when null=null then
'Working in case'
else
'not working'
end From dual;

Output : Not working

4.
select empno from scott.emp where emp_age=null;
Output : As we already know, null never equals to another null, query will not return any rows

5.
Cursor

If a cursor returns no records will it return error?


if we use cursor attributes then it will not throw any exception
In Oracle, what happens if there is no statement inside an Anonymous block?
For Eg:
Declare
Begin
End;
Ans: It will throw Error.

Correct:
Declare
Begin
NULL;
End;
How does NULLs work with Indexes? What are the workarounds?
Indexes wont help in giving proper search results if there are NULL values in the indexed columns. So, it is
always advisable to create the NVL() function based indexes for such columns.

User_Source table contains code for which all Objects?


a. Functions
b. Packages for both spec and body
c. Procedures
d. Triggers
Oracle Page 61 of 87

What are the types PL/SQL code blocks?


Anonymous Block :
 It is a block of codes without a name. (unnamed pl/sql block)
 It may contain a declaration part, an execution part, and exception handlers.

Stored Program Unit


 It is a block of codes with a name.
 It is similar to an anonymous block just that it can take parameters and return values.

Trigger
 It is a block of code that is implicitly fired based some specific event.
How many types of Tables supported by Oracle? Explain them
Oracle supports 4 types of tables based on how data is organized in storage:
Ordinary (heap-organized) table
 A basic, general purpose table
 Data is stored as an unordered collection (heap)

Clustered table
 A part of a cluster
 Cluster: A cluster is a group of tables that share the same data blocks as they share common columns
and are often used together.

Index-organized table
 Data is stored in a B-tree index structure in a primary key sorted manner.
 Each index entry in the B-tree stores the non-key column values as well.

Partitioned table
 Data is broken down into smaller, more manageable pieces called partitions or sub-partitions.
 Each partition can be managed individually

 Each partition can operate independently


What are the Predefined Tablespaces in a database?
SYSTEM Tablespace, SYSAUX Tablespace, UNDO Tablespace, TEMP Tablespace

Max lenth of dbms_out.put_line();


max 255 characters

COALESCE command
Select coalesce(comm, deptno) from emp;
If comm. is null then deptno otherwise comm.

READ ONLY TRANSACTIONS in Oracle


For banking databases , to manage concurrent updates , inserts etc.
COMMIT;

When a table or view is dropped, what happens to the associated triggers?


Triggers associated to the dropped Tables, Views also gets DROPPED

Can we define an index on a view?


An index cannot be defined on a view. Because view is virtual table, which consists of a subset of columns from
one more tables.

How can we create a view on a non existing table


Use the keyword force with the create command.
Eg: create force view v222 as select * from emp111;

Even if default values are there, to use "insert into table values" option, once should provide all column
names to be inserted.
Oracle Page 62 of 87

Eg> table: Vacation


(empid varchar2(7) primary key,
ename varchar2(50) not null,
annual_leave number(4) default 0,
casual_leave number(4) default 0,
Lop number(4) default 0,
Year number(4) check (year between 2007 and 2008),
status varchar2(1) default 'N')
Wrong: insert into vacation values('2877','James',2007,'A');
- Note: All column names are not given
Output: ERROR at line 1: ORA-00947: not enough values
Workaround:
Correct : insert into vacation (empid,ename,Year,status) values('267834','JOse Mathew',2007,'A');

How can you do multiple column updates using Update Command:


UPDATE EMP E SET (E.JOB, E.MGR) = (SELECT E1.JOB, E1.MGR FROM EMP E1 WHERE E.EMPNO=E1.EMPNO)
update vacation set ANNUAL_LEAVE=18, CASUAL_LEAVE=7;

Can you insert into, or update a view?


Yes or No could be the answer. It varies on case to case. Cases whos below explains, when and where it is
possible to insert into or update a view.
Note: View doesnt contain any data. Only the underlying tables gets inserted or updated.
Case1. View is created from a single table and is not created Read Only.
Yes. This kind of views could be updated. The changes are effected in the underlying table.

Case2: View is created from mutliple tables using join conditions


Updateable IFF (only if both of the following conditions are satisfied)
a) Tables should have proper Primay key foreign key relationships AND
b) All columns used in the views should unambigously point to the columns of the respective tables which is
being updated through the view.

Case3: View created with READ ONLY option cannot be updated.


Case4: All other views which doesnot satisfy Case1 and Case2 couldnot be updated.

Can a Package Spec exist without a body?


Yes.
Advantage being, we can create global variables or collections and put them in a package Spec. No need to
create any body since there are no procedures/functions.
Eg:
CREATE OR REPLACE PACKAGE EX_PACK_001
AS
V_RECORDS NUMBER;
END EX_PACK_001;
This variable could be called outside in any code like this:
EX_PACK_001.v_records:=1000;
Oracle Page 63 of 87

USER DEFINED EXCEPTION


There are mainly 3 ways to use User Defined Exceptions

A. EXCEPTION
declare
exc_user Exception; --declare exception
begin
begin
--code--
exception
when others then
raise exc_user; --exception raised
exception
when exc_user --handler for exc_user. exception handled
when others then --handler for others
end;

B. PRAGMA EXCEPTION_INIT

SET SERVEROUTPUT ON
DECLARE
e_constraint_violation EXCEPTION;
PRAGMA EXCEPTION_INIT(e_constraint_violation, -2290);
BEGIN
INSERT INTO course
(course_no, description, created_by, created_date)
VALUES
(COURSE_NO_SEQ.NEXTVAL, 'TEST COURSE', USER, SYSDATE);
COMMIT;
DBMS_OUTPUT.PUT_LINE ('One course has been added');
EXCEPTION
WHEN e_constraint_violation THEN
DBMS_OUTPUT.PUT_LINE ('INSERT statement is '||
'violating a constraint');
END;

C. RAISE_APPLICATION_ERROR
declare
exc_user Exception; --declare exception
begin
if (<logic>) then
RAISE_APPLICATION_ERROR(-20001, exc_user); --code greater than -20000
exception
when exc_user then
--handler for exc_user-- --handled when error occurs with the specified Oracle Code
when others then
--handler for others

An inner block has got an exception with the same name as in the outer block. The exception doesnot have
any handler defined in the inner block, but has got a handler defined in the outer block. Will the Exception
get handled assuming that when others exception handler is not defined?
Oracle Page 64 of 87

Declare
A Exception ;
Begin
Declare
A Exception; --Exception with same name decalare in inner block
Begin
if 1=1 then
raise A;
end if;
end; --No handler for exception A in inner block
exception
when A then
--handler-- End;

Answer:
The exception A in the inner block WILL get propagated to the outer block but WILL NOT get handled in
the outer block. Oracle considers both Exceptions to be extremely different, even if they have the same name.

SQL TRACE and TK PROF


Both SQL Trace and TKPROF help to find the statistics of an SQL statement which could be used for query
optimization.

Start Oracle SQLTRACE:


In Oracle, to start an SQLTRACE for the current session, execute:
ALTER SESSION SET SQL_TRACE = TRUE;
Stop Oracle SQLTRACE
In Oracle, to stop SQL tracing for the current session, execute:
ALTER SESSION SET sql_trace = false;

Can one select a random collection of rows from a table?


SELECT * FROM emp SAMPLE(10);
In the above example, Oracle is instructed to randomly return 10% of the rows in the table.

SELECT * FROM emp SAMPLE(5) BLOCKS;


This example will sample 5% of all formatted database blocks instead of rows.

What do you need before implementing a member function?


You need to create a type.

What is the default value of a boolean?


NULL. This is somewhat tricky but apparently there are languages that default boolean to false. A PL/SQL
developer needs to know all variables default to NULL.

What is dual table?


SQL> desc dual

Name Null? Type


----------------------------------------- -------- ----------------------------
DUMMY VARCHAR2(1)
Oracle Page 65 of 87

Dynamic Sql?
If we want to change SQL Query (conditions like (where, and, or) or Table names) at run time, then we can use
dynamic Sql.

Why Use Dynamic SQL?


You should use dynamic SQL in cases where static SQL does not support the operation you want to perform, or in
cases where you do not know the exact SQL statements that must be executed by a PL/SQL procedure. These
SQL statements may depend on user input, or they may depend on processing work done by the program.

In PL/SQL, you can only execute the following types of statements using dynamic SQL, rather than static
SQL:

Data definition language (DDL) statements, such as CREATE, DROP, GRANT, and REVOKE
Session control language (SCL) statements, such as ALTER SESSION and SET ROLE

Also, you can only use the TABLE clause in the SELECT statement through dynamic SQL. For example, the
following PL/SQL block contains a SELECT statement that uses the TABLE clause and native dynamic SQL:

CREATE TYPE t_emp AS OBJECT (id NUMBER, name VARCHAR2(20))


/
CREATE TYPE t_emplist AS TABLE OF t_emp
/

CREATE TABLE dept_new (id NUMBER, emps t_emplist)


NESTED TABLE emps STORE AS emp_table;

INSERT INTO dept_new VALUES (


10,
t_emplist(
t_emp(1, 'SCOTT'),
t_emp(2, 'BRUCE')));

DECLARE
deptid NUMBER;
ename VARCHAR2(20);
BEGIN
EXECUTE IMMEDIATE 'SELECT d.id, e.name
FROM dept_new d, TABLE(d.emps) e -- not allowed in static SQL
-- in PL/SQL
WHERE e.id = 1'
INTO deptid, ename;
END;
/
Oracle Page 66 of 87

Can one use dynamic SQL statements from PL/SQL?


Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL
statements (statements created at run-time). Look at these examples. Note that the statements within quotes
are NOT semicolon terminated:
EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)';

-- Using bind variables...'


sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';
EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;

-- Returning a cursor...
sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these
examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm);
END;
/

What is PL/SQL collections?


 Index_by Tables
 Nested Tables
 Varrays

How do u know the last executed procedure/function/package?


Select * from dba_audit_trail;

How to avoid using cursors?


Oracle Page 67 of 87

Just use subquery in for clause

ex:For emprec in (select * from emp) loop


dbms_output.put_line(emprec.empno);
end loop;

How to disable multiple triggers of a table at at a time?


ALTER TABLE<TABLE NAME> DISABLE ALL TRIGGER

Recycle Bin in oracle?


Recycle bin is a logical storage to hold the tables that have been dropped from the database, in case it was
dropped in error. Tables in recycle bin can be recovered back into database by the Flashback Drop action.
Oracle database recycle save the same purpose as the recycle bin on your Windows desktop.
Oracle Page 68 of 87

Bulk collect

Best practices for knowing your LIMIT and kicking %NOTFOUND

The most important thing to remember when you learn about and start to take advantage of features such as
BULK COLLECT is that there is no free lunch. There is almost always a trade-off to be made somewhere. The
tradeoff with BULK COLLECT, like so many other performance-enhancing features, is "run faster but consume
more memory."

Specifically, memory for collections is stored in the program global area (PGA), not the system global area
(SGA). SGA memory is shared by all sessions connected to Oracle Database, but PGA memory is allocated for
each session. Thus, if a program requires 5MB of memory to populate a collection and there are 100
simultaneous connections, that program causes the consumption of 500MB of PGA memory, in addition to the
memory allocated to the SGA.

Fortunately, PL/SQL makes it easy for developers to control the amount of memory used in a BULK COLLECT
operation by using the LIMIT clause.

Suppose I need to retrieve all the rows from the employees table and then perform some compensation analysis
on each row. I can use BULK COLLECT as follows:

PROCEDURE process_all_rows
IS
TYPE employees_aat IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER;
l_employees employees_aat;
BEGIN
SELECT * BULK COLLECT INTO l_employees FROM employees;

FOR indx IN 1 .. l_employees.COUNT


LOOP
analyze_compensation (l_employees(indx));
END LOOP;
END process_all_rows;

Very concise, elegant, and efficient code. If, however, my employees table contains tens of thousands of rows,
each of which contains hundreds of columns, this program can cause excessive PGA memory consumption.

Consequently, you should avoid this sort of "unlimited" use of BULK COLLECT. Instead, move the SELECT
statement into an explicit cursor declaration and then use a simple loop to fetch many, but not all, rows from
the table with each execution of the loop body, as shown in Listing 1.

Code Listing 1: Using BULK COLLECT with LIMIT clause

PROCEDURE process_all_rows (limit_in IN PLS_INTEGER DEFAULT 100)


IS
CURSOR employees_cur
IS
SELECT * FROM employees;

TYPE employees_aat IS TABLE OF employees_cur%ROWTYPE


INDEX BY PLS_INTEGER;

l_employees employees_aat;
BEGIN
OPEN employees_cur;
LOOP
FETCH employees_cur
BULK COLLECT INTO l_employees LIMIT limit_in;

FOR indx IN 1 .. l_employees.COUNT


LOOP
analyze_compensation (l_employees(indx));
END LOOP;

EXIT WHEN l_employees.COUNT < limit_in;


Oracle Page 69 of 87

Set Auto Trace On (How to start Auto trace, it is useful execution paln)

SQL> set autotrace on


SP2-0613: Unable to verify PLAN_TABLE format or existence
SP2-0611: Error enabling EXPLAIN report
SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is enabled
SP2-0611: Error enabling STATISTICS report
SQL> conn sys as sysdba
Enter password: ***
Connected.
SQL> @ D:\oracle\ora92\sqlplus\admin\plustrce.sql

SQL> GRANT plustrace TO scott;


SQL> conn scott/tiger@ramesh
Connected.
SQL> @ D:\oracle\ora92\rdbms\admin\utlxplan.sql

Table created.

SQL> SET AUTOTRACE ON


SQL> set timing on
SQL> SELECT region, total_sales FROM
(
SELECT region, NVL(SUM(order_amt),0) AS total_sales
FROM sales
GROUP BY region
) ilv
WHERE total_sales > (SELECT SUM(order_amt)/3 AS one_third_sales
FROM sales)
/

Associative Arrays

Arrays have been available in PL/SQL since its very early versions, when Oracle called them "PL/SQL Tables".

indexing associative arrays


Associative arrays in Oracle 9.2 can be indexed by any of the following types:

 BINARY_INTEGER;
 PLS_INTEGER; and
 VARCHAR2.

PLS_INTEGER is a supposedly faster or equivalent implementation of BINARY_INTEGER but the last of these
indexing methods is more likely to draw our attention. For the first time, we can index arrays by strings in
PL/SQL. This simple fact makes arrays in PL/SQL far more flexible than in previous versions with more practical
use for our program data.

Index by integer

Indexing PL/SQL arrays by integer is as old as the technology itself, so we shall not spend much time on this. The
following example performs a simple timing comparison of loading and accessing two arrays: one indexed by
BINARY_INTEGER and the other by PLS_INTEGER.
Oracle Page 70 of 87

SQL> DECLARE
2
3 TYPE aat_binary IS TABLE OF VARCHAR2(10)
4 INDEX BY BINARY_INTEGER;
5 aa_binary aat_binary;
6
7 TYPE aat_pls IS TABLE OF VARCHAR2(10)
8 INDEX BY PLS_INTEGER;
9 aa_pls aat_pls;
10
11 v_dummy VARCHAR2(10);
12
13 BEGIN
14
15 timer.snap;
16 FOR i IN 1 .. 1000000 LOOP
17 aa_binary(i) := RPAD('X',10);
18 END LOOP;
19 timer.show('Load BINARY');
20
21 timer.snap;
22 FOR i IN 1 .. 1000000 LOOP
23 aa_pls(i) := RPAD('X',10);
24 END LOOP;
25 timer.show('Load PLS');
26
27 timer.snap;
28 FOR i IN 1 .. 1000000 LOOP
29 v_dummy := aa_binary(i);
30 END LOOP;
31 timer.show('Access BINARY');
32
33 timer.snap;
34 FOR i IN 1 .. 1000000 LOOP
35 v_dummy := aa_pls(i);
36 END LOOP;
37 timer.show('Access PLS');
38
39 END;
40 /
[Load BINARY] 1.56 seconds
[Load PLS] 1.81 seconds
[Access BINARY] 0.70 seconds
[Access PLS] 0.71 seconds

PL/SQL procedure successfully completed.

The timings show that there is very little difference between the two indexing types so we should not be too
concerned about converting all of our BINARY_INTEGER arrays to PLS_INTEGER!
Oracle Page 71 of 87

Multilevel collections in oracle 9i

Multilevel collection is one which has arrays within arrays. This means that each element of the outer array is an
array in itself (or even a record that contains one or more arrays). The possibilities for nesting are far beyond
whatever we would reasonably require (for example, the limit on the test database used for this article is 3,638
levels of nesting before hitting the PLS-00123: program too large exception). Therefore, in the following
example we will declare an index-by table type in PL/SQL that has another index-by table type defining its
elements. We will assign one entry to the outer array. This one outer entry will itself be an array of three
elements.

SQL> DECLARE
2
3 TYPE varchar2_array IS TABLE OF VARCHAR2(30)
4 INDEX BY BINARY_INTEGER;
5
6 TYPE varchar2_multi IS TABLE OF varchar2_array
7 INDEX BY BINARY_INTEGER;
8
9 v_multi varchar2_multi;
10
11 BEGIN
12
13 v_multi (1) (1) := 'one and one';
14 v_multi (1) (2) := 'one and two';
15 v_multi (1) (3) := 'one and three';
16
17 DBMS_OUTPUT.PUT_LINE(
18 'Multilevel array v_multi has [' || v_multi.COUNT || '] elements.'
19 );
20
21 DBMS_OUTPUT.PUT_LINE(
22 'The first element in v_multi has [' || v_multi(1).COUNT || '] elements.'
23 );
24
25 DBMS_OUTPUT.PUT_LINE(
26 'The last element in v_multi is [' || v_multi(1)(3) || '].'
27 );
28
29 END;
30 /
Multilevel array v_multi has [1] elements.
The first element in v_multi has [3] elements.
The last element in v_multi is [one and three].

PL/SQL procedure successfully completed.

We can see some reasonably familiar syntax in the above example, albeit with some extensions. Note the
following in particular.

 Lines 3-4: we create a standard index-by table (array) type of VARCHAR2. There is nothing new about
this syntax;
 Lines 6-7: we create another index-by table type, but this time we create an array of our previous array
type (i.e. array_type IS TABLE OF another_array_type). It is still the same declaration syntax, but would
have failed in previous versions because we could not nest arrays within arrays;
 Line 9: we declare an array variable defined by our multilevel array type. Every entry we add to this
array variable will itself be an array;
 Lines 13-15: we assign values to our multilevel array using literal index offsets (in this example). The
outer array has only one element. The array at this index position has three elements. Note the offset
syntax. The second offset is how we address the inner array at the first entry in the outer array;
 Lines 17-26: we can access the array in various ways. Note that every element is an array in its own
right, as is the outer array itself. This means that the standard pseudo-methods such as COUNT, LAST,
DELETE etc will work on both the outer and inner arrays.
Oracle Page 72 of 87

Bulk PL/SQL Enhancements

 BULK COLLECT support for collections of records;


 BULK COLLECT support for Native Dynamic SQL;
 BULK COLLECT support for objects;
 FORALL SAVE EXCEPTIONS clause;
 FORALL support for record-based DML; and
 FORALL support for Native Dynamic SQL.

Oracle 9i Release Two introduces BULK COLLECT support for collections of records. This means that from 9.2.0.1
onwards, we can declare a single associative array (new name for index-by tables in 9i) or collection type based
on one of the following.

table%ROWTYPE;
view%ROWTYPE;
user-defined record type; and
cursor%ROWTYPE (9.2.0.3 onwards only).

An example of this simple, yet powerful new feature is as follows.

SQL> DECLARE
2
3 /*
4 * Declare an associative array type of
5 * USER_TABLES structure...
6 */
7 TYPE typ_aa_tables IS TABLE OF user_tables%ROWTYPE
8 INDEX BY PLS_INTEGER;
9 aa_tables typ_aa_tables;
10
11 BEGIN
12
13 /* Fetch all of my USER_TABLES data in one pass... */
14 SELECT *
15 BULK COLLECT INTO aa_tables
16 FROM user_tables;
17
18 DBMS_OUTPUT.PUT_LINE (
19 'Fetched ' || TO_CHAR ( aa_tables.COUNT ) ||
20 ' records from USER_TABLES.' );
21
22 END;
23 /
Fetched 21 records from USER_TABLES.

PL/SQL procedure successfully completed.

Some points to note are:

 Lines 7-8. Our associative array type is based on a table rowtype. We have indexed the array by
PLS_INTEGER (new in 9i) for even greater efficiency than BINARY_INTEGER (pre-9i).
 Line 9. We only need to declare one associative array variable, irrespective of the number of columns to
be fetched (USER_TABLES in 9.2.0.3 has 46 columns - that's 45 fewer types and 45 fewer variables
required in 9i as opposed to 8i).
 Line 14. We can feel quite comfortable with selecting * from the source table as our associative array
has been defined as being of exactly the same structure.
 Line 15. A simple BULK COLLECT into a single associative array of records is all that is required.
Oracle Page 73 of 87

This feature in 9iR2 dramatically reduces the amount of code required to utilise bulk fetching, which results in
performance gains as well as improved legibility and simpler maintenance.

bulk collect with native dynamic sql

Oracle 9i now enables us to bulk fetch from Native Dynamic SQL statements. Prior to 9i we had DBMS_SQL (with
its reasonably complex, low-level interface) or NDS workarounds using dynamic PL/SQL. However, it is now
much simpler in 9i. In the following example, we will simulate a process whereby we fetch a collection of keys
from a table based on a different set of criteria passed in as a parameter (our parameter in this case will be
represented by a sqlplus variable).

SQL> VAR where_clause VARCHAR2(256)

SQL> exec :where_clause := ' created > TRUNC(SYSDATE) - 150 ';

PL/SQL procedure successfully completed.

SQL> DECLARE
2
3 TYPE typ_aa_object IS TABLE OF user_objects%ROWTYPE
4 INDEX BY PLS_INTEGER;
5 aa_objects typ_aa_object;
6
7 v_predicates VARCHAR2(256) := :where_clause;
8
9 BEGIN
10
11 /* Execute the statement and bulk fetch the results... */
12 EXECUTE IMMEDIATE ' SELECT *
13 FROM user_objects
14 WHERE ' || v_predicates
15 BULK COLLECT INTO aa_objects;
16
17 /* How many did we get ? */
18 DBMS_OUTPUT.PUT_LINE ( aa_objects.COUNT ||
19 ' records fetched.' );
20
21 END;
22 /
54 records fetched.

PL/SQL procedure successfully completed.

Some points to note are:

 Line 7. Our predicates are being assigned from our "parameter" to be appended to a dynamic SQL
statement at runtime.
 Line 15. The BULK COLLECT extension to EXECUTE IMMEDIATE..INTO in 9i, combined with the
enhancement to bulk fetch into an associative array / collection of records.

What command would you use to encrypt a PL/SQL application?


Wrap Utility
Oracle Page 74 of 87

Wrappers are used so that you can encrypt or "hide" the source code for your PL/SQL while you create your
package or procedure. This is useful for companies that do not want to divulge sensitive information, such as
passwords, internal business rules, and intellectual property.

Ex :
Procedure name : proc_1
Copy procedure source to d:\erp\procedure\proc_source.sql
Cmd
C:> Wrap iname = d:\erp\procedure\proc_source.sql
(in the same path proc_source.plb file will be crate)

Sql> @ d:\erp\procedure\proc_source.plb
Sql> exec proc_1

Sql> drop procedure proc_1;

Packaged Procedures versus Normal Procedures


Packaged procedures use some of the OOPs concepts.

One main character is polymorphism. In the same package, we can have different procedures/functions with
the same name but different signatures. Signature is nothing but the parameter list. 2 procedures with same
name could exist in the same package with different number of parameters or different datatypes for
parameters.

Both are stored as P-Code. So both should get loaded and executed in memory fast. But I think standalone
should be faster compared to the packaged one.

And the difference depends on the size of the package. When you call a packaged procedure, the whole package
is loaded into the memory, no matter how many procedures, functions or global variables it has or not.
And standalone is a single procedure getting loaded, so faster.

However if the packaged procedure has got only one procedure which is the same as the standalone procedure, I
guess there should not be any difference.

How to store the image in table? pls give example


Create Table images
(
image BLOB
)
/

Create Or REPLACE Directory my_images As 'C:\ORA';

Declare
v_images Blob;
imgfile Bfile;
Begin
Insert Into images
Values (EMPTY_BLOB ())
Returning image
Into v_images;
imgfile := BFILENAME ('MY_IMAGES', '60029.gif');
DBMS_LOB.fileopen (imgfile);
DBMS_LOB.loadfromfile (v_images, imgfile, DBMS_LOB.getlength (imgfile));
DBMS_LOB.fileclose (imgfile);
End;

MOVE TABLE/VIEW one user to another user


Oracle Page 75 of 87

Create or Replace procedure Ram_proc as


Begin
Execute immediate ‘Create table ram_erp as select * from rol.rol_item_stock_v’;
End;

Conn system/stanza@pl
SQL> grant select on rol.rol_item_stock_v to erpfinal;
SQL> grant create any directory erpfinal;
SQL> grant create table to erpfinal;

Begin
Ram_proc;
End;

Note : Delete records from another user


SQL> Grant delete on Rol.Rol_item_stock to erpfinal;

Interview query - display the date on which I have not taken the interview

create table interview_detail ( interview_Date date);


interview dates : 10-APR-09, 12-APR-09, 13-APR-09, 15-APR-09

select min_dt + level - 1 no_interview_date


from (
select min(interview_date) min_dt,
max(interview_date) max_dt
from interview_detail
)
connect by level <= max_dt - min_dt + 1
minus
select interview_date
from interview_detail;

OUTPUT : 11-APR-09, 14-APR-09


Oracle Page 76 of 87

External tables in Oracle?


In 9i, only read operations were permitted; in 10g, you can also write out data to an external table, but you
can't write to an existing table.

How Are External Tables Created?


External tables are created using the SQL> CREATE TABLE...ORGANIZATION EXTERNAL statement. When you
create an external table, you specify the following attributes:

* TYPE - specifies the type of external table. The two available types are the ORACLE_LOADER type and
the ORACLE_DATAPUMP type. Each type of external table is supported by its own access driver.

* The ORACLE_LOADER access driver is the default. It can perform only data loads, and the data must come
from text datafiles. Loads from external tables to internal tables are done by reading from the external tables'
text-only datafiles.

* The ORACLE_DATAPUMP access driver can perform both loads and unloads. The data must come from
binary dump files. Loads to internal tables from external tables are done by fetching from the binary dump files.
Unloads from internal tables to external tables are done by populating the external tables' binary dump files.

* DEFAULT DIRECTORY - specifies the default location of files that are read or written by external tables.
The location is specified with a directory object, not a directory path. See Location of Datafiles and Output Files
for more information.

* ACCESS PARAMETERS - describe the external data source and implements the type of external table that
was specified. Each type of external table has its own access driver that provides access parameters unique to
that type of external table. See Access Parameters.

* LOCATION - specifies the location of the external data. The location is specified as a list of directory
objects and filenames. If the directory object is not specified, then the default directory object is used as the
file location.

The following example shows the use of each of these attributes:

CREATE TABLE emp_load


(
employee_number CHAR(5),
employee_last_name CHAR(20),
employee_first_name CHAR(15),
employee_middle_name CHAR(15)
)
ORGANIZATION EXTERNAL
(
TYPE ORACLE_LOADER DEFAULT DIRECTORY ext_tab_dir
ACCESS PARAMETERS
(
RECORDS FIXED 62 FIELDS (employee_number CHAR(2),
employee_dob CHAR(20),
employee_last_name CHAR(18),
employee_first_name CHAR(11),
employee_middle_name CHAR(11))
)
LOCATION ('info.dat')
);

What is the difference between clustered Index and Non Clustered Indexes?
Oracle Page 77 of 87

In Oracle , there are two types of data storage methods :


1. Clustered ( also know as Clustered Tables)- used to reduce disk i/o and when space constraints are thr.
2. UnClustered (Default storage mechanism)

for each method index can be defined based on above definitions

Index for Clustered Table and Index for Unclustered table(Default)

For Unclustered
Create INDEX ------Index name ------
on Table-Name ( ----Column Name---)

for Clustered

first create Cluster if not exists


CREATE Cluster ----clustername--(Column Datatype--)
Cluster key is much significant here
Indexing :
Create INDEX ---IndexName---
on CLUSTER --clusterName--;

now add tables to cluster


create table --table name --(field1 datatype, fileld2 datatype)
CLUSTER -clustername created--

Now coming to INDEX structure of Oracle Achitecture (unclustered Tables)


it can be of two types

1 . B* Tree (Default) - subtypes as Unique/Non unique indexes


2. Bitmap ( Can be used to boost up performance if Cardinality ( no of distinct values ) in column is low such as
Gender , Flag(1/2) etc.
3. Reverse Index( Not used much)

Oracle creates B* Tree and using Navigation thru its Leaf Nodes or super leaf nodes it makes retrieval faster
B* Tree should be used :
1. Cardinality in column is high
2. No of rows in table is high
3. Column is used in WHERE and JOIN Conditions

What are oracle utilities? Explain it


IMP, EXP, SQLLDR are major used oracle utilities

How u will make sure that indexes are used or not?


By checking explain plan ,we can know that indexes r used by running queries or not

How do u handle when a query is taking lot of time to execute?


Methods to handle long running quries

1. By checking explain plan


2. By imposing indexes on columns which are used in where clause of qry
3. Writing plsql block instead of single qry using bulk binds
4. Parallel processing
5. Using oracle hints
6.Using minus, intersect operation instead of in ,exist, not exist

How u do performance tuning on procedures?


Oracle Page 78 of 87

Using LIKE clause


◦ WHERE ____ LIKE ‘ste%’ uses indexes.
◦ WHERE ____ LIKE ‘%son’ cannot use an index.

Avoid SELECT * FROM … instead select specific column names

Replace hard coded values with parameters.

Do not use 'SELECT COUNT(*) ...' to test for the existence of a row. Open an explicit cursor, fetch once, and then
check cursor%NOTFOUND.

Or u can use a block with NO_DATA_FOUND exception handling.


-ALWAYS use 'anchored' data type declarations:
name emp.ename%TYPE; as opposed to: name varchar(10);

If the ename column in the emp table is made bigger, the anchored datatype still works (it is recompiled at
runtime).

Do not use the NOT IN construct with SQL sub-queries. Use the NOT EXISTS construct instead. This is much more
efficient, as the NOT IN construct usually forces full table scans.

Whenever we are coding its advisable not to use DBMS_Output statements in the code.

NEVER AND EVER COMMIT inside a loop.

Use JOIN instead of Sub-Query

Use UNION ALL instead of UNION

Use OUTER JOIN, DECODE and GROUP functions to perform multiple operations with single query/statement

Write code so that INDEXes can be used.


For that do not use any function on right right side of where clause.
Insert/ Update/Delete multiple records in each statements (avoid cursors)
Update multiple columns in one UPDATE statement.

Use rollback in exception block if there is commit in the executable block and close the cursors or files in the
exception block if any opened
The use of table DUAL should be avoided as much as possible.

What are the states of a rollback segment?


The various states of a rollback segment are :
ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID.

How to LOCK/UNLOCK a USER account in Oracle?


LOCK
SQL> ALTER USER username ACCOUNT LOCK;
or
alter user user_name identified by password accout lock;

UNLOCK
SQL> ALTER USER username ACCOUNT UNLOCK;
Or
alter user user_name identified by password accout unlock;

How to find what are the privileges are given by a user to another user?
Oracle Page 79 of 87

SQL> connect system/mgr@ramesh

select
lpad(' ', 2*level) || granted_role "User, his roles and privileges"
from
(
/* THE USERS */
select
null grantee,
username granted_role
from
dba_users
where
username like upper('%&enter_username%')
/* THE ROLES TO ROLES RELATIONS */
union
select
grantee,
granted_role
from
dba_role_privs
/* THE ROLES TO PRIVILEGE RELATIONS */
union
select
grantee,
privilege
from
dba_sys_privs
)
start with grantee is null
connect by grantee = prior granted_role;

'Ramesh is a sse, Ramesh lives in mumbai,Ramesh is good developer'


write aquery to find how many times ‘Ramesh’ in the string?

SQL> Select (( Length (Replace ('Ramesh is a sse, Ramesh lives in mumbai,Ramesh is good developer' , ' ', Null))
- Length (Replace (Replace ('Ramesh is a sse, Ramesh lives in mumbai,Ramesh is good developer' , ' ', Null),
'Ramesh'))
)/Length ('Ramesh')) cnt
From DUAL;

Write a query that display 25 years 8months 10 day when we enter birthd?
Select TO_NUMBER (TO_CHAR (SYSDATE, 'rrrr')) - TO_NUMBER (TO_CHAR (To_date ('10-OCT-1985', 'dd-mon-rrrr'),
'rrrr')) - 1
|| 'Years' || (ABS (12 - TO_NUMBER (TO_CHAR (To_date ('10-OCT-1985', 'dd-mon-rrrr'), 'mm')))+
TO_NUMBER (TO_CHAR (To_date (SYSDATE, 'dd-mon-rrrr'), 'mm')))
|| 'Months' || ABS (TO_NUMBER (TO_CHAR (SYSDATE, 'dd'))- TO_NUMBER (TO_CHAR (To_date ('10-OCT-1983', 'dd-
mon-rrrr'), 'dd'))) days
From DUAL

How to Close a session from Oracle Stored procedure?


Oracle Page 80 of 87

create or replace procedure kill_session


( p_sid in varchar2
,p_serial# in varchar2
)
is
cursor_name pls_integer default dbms_sql.open_cursor;
ignore pls_integer;
BEGIN
select count(*) into ignore from V$session where username = USER and sid = p_sid and serial# = p_serial# ;
if ( ignore = 1 )
then
dbms_sql.parse(cursor_name,'alter system kill session ''' ||p_sid||','||p_serial#||'''', dbms_sql.native);
ignore := dbms_sql.execute(cursor_name);
else
raise_application_error( -20001, 'You do not own session ''' ||p_sid || ',' || p_serial# ||'''' );
end if;

END;

Query regarding Oracle Job Scheduling(Oracle 10g)


create or replace package body pkg_date is
procedure your_job_prc is
begin
if to_char(sysdate,'hh am') between '10 am' and '10 pm' then
--run your job here
else
null;
end if;
end prc1;

procedure calling_job_prc
X NUMBER;
BEGIN
sys.DBMS_JOB.SUBMIT
( job => X
,what => your_job_prc
,next_date => sysdate
,interval => 'SYSDATE +30/1440'
,no_parse => FALSE
);
SYS.DBMS_OUTPUT.PUT_LINE('Job Number is: ' || to_char(x));
COMMIT;

END prc2;

end pkg_date;

--now call prc2

sql> exec pkg_date.calling_job_prc;


Oracle Page 81 of 87

Bulk Binds (FORALL)


Bulk binds improve performance by minimizing the number of context switches between the PL/SQL and SQL
engines, it reduces network I/O.

Example without Bulk-Binds:

DECLARE
TYPE Numlist IS VARRAY (100) OF NUMBER;
Id NUMLIST := NUMLIST(7902, 7698, 7839);
BEGIN
FOR i IN Id.FIRST..Id.LAST LOOP
UPDATE emp SET Sal = 1.1 * Sal
WHERE mgr = Id(i);
END LOOP;
END;
/

The same with Bulk Bind (no more looping)

DECLARE
TYPE Numlist IS VARRAY (100) OF NUMBER;
Id NUMLIST := NUMLIST(7902, 7698, 7839);
BEGIN
FORALL i IN Id.FIRST..Id.LAST
UPDATE emp SET Sal = 1.1 * Sal
WHERE mgr = Id(i);
END;
/

Bulk Collects (BULK COLLECT INTO)

In the example above (Bulk Binds), the list with empno's was statically built. With Bulk Collect you can
dynamically build the entire list using BULK COLLECT INTO.

DECLARE
TYPE Numlist IS TABLE OF emp.empno%TYPE;
Id Numlist;
BEGIN
SELECT empno BULK COLLECT INTO Id
FROM emp
WHERE sal < 2000;
FORALL i IN Id.FIRST..Id.LAST
UPDATE emp SET Sal = 1.1 * Sal
WHERE mgr = Id(i);
END;
/

Bulk Collects with RETURNING INTO

You can even use Bulk Collects with DML-Commands to return a value to the calling procedure using RETURNING
without an additional fetch.

DECLARE
TYPE Numlist IS TABLE OF emp.empno%TYPE;
TYPE Bonlist IS TABLE OF emp.sal%TYPE;
Id Numlist;
Bl Bonlist;
BEGIN
SELECT empno BULK COLLECT INTO Id
FROM emp
WHERE deptno = 10;
FORALL i IN Id.FIRST..Id.LAST
Oracle Page 82 of 87

UPDATE emp SET Sal = 1.1 * Sal


WHERE mgr = Id(i)
RETURNING Sal BULK COLLECT INTO Bl;
END;
/

In the PL/SQL table "Bonlist" you can now find the updated salaries.

Drop Column Support

Dropping columns lets you free space in the database by dropping columns you no longer need, or by marking
them to be dropped at a future time when the demand on system resources is less.

Drop a normal column without any Constraints

ALTER TABLE emp DROP COLUMN job;

Drop a Primary Key:

ALTER TABLE emp DROP COLUMN empno CASCADE CONSTRAINT;

Drop a Column in a very big Table, when you get Rollback Segments Problems

ALTER TABLE verybig DROP COLUMN col CHECKPOINT 10000;

Set one or more Colums unused for later Drop

ALTER TABLE emp SET UNUSED COLUMN mgr;


ALTER TABLE emp DROP UNUSED COLUMNS;

Moving Tables to other Tablespaces

The move table clause lets you relocate data of a nonpartitioned table into a new segment, optionally in a
different tablespace, and optionally modify any of its storage attributes.

Sql> conn scott/tiger@pl


Sql> alter table emp
move tablespace ERP_APPAREL
STORAGE (INITIAL 64K NEXT 64K) PCTFREE 0;

Calculate multiple levels of subtotals with ROLLUP

ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified group of
dimensions. It also calculates a grand total. ROLLUP is a simple extension to the GROUP BY clause, so its syntax
is extremely easy to use.

Example

SELECT deptno,job,count(*),sum(sal)
FROM emp
GROUP BY ROLLUP(deptno,job);

DEPTNO JOB COUNT(*) SUM(SAL)


--------- --------- --------- ---------
10 CLERK 1 1300
10 MANAGER 1 2450
10 PRESIDENT 1 5000
10 3 8750
20 ANALYST 2 6000
20 CLERK 2 1900
20 MANAGER 1 2975
20 5 10875
30 CLERK 1 950
30 MANAGER 1 2850
30 SALESMAN 4 5600
Oracle Page 83 of 87

30 6 9400
14 29025

Create cross-tabular reports with CUBE

CUBE enables a SELECT statement to calculate subtotals for all possible combinations of a group of dimensions.
It also calculates a grand total. This is the set of information typically needed for all cross-tabular reports, so
CUBE can calculate a cross-tabular report with a single SELECT statement.

SELECT deptno,job,count(*),sum(sal)
FROM emp
GROUP BY CUBE(deptno,job);

DEPTNO JOB COUNT(*) SUM(SAL)


--------- --------- --------- ---------
10 CLERK 1 1300
10 MANAGER 1 2450
10 PRESIDENT 1 5000
10 3 8750
20 ANALYST 2 6000
20 CLERK 2 1900
20 MANAGER 1 2975
20 5 10875
30 CLERK 1 950
30 MANAGER 1 2850
30 SALESMAN 4 5600
30 6 9400
ANALYST 2 6000
CLERK 4 4150
MANAGER 3 8275
PRESIDENT 1 5000
SALESMAN 4 5600
14 29025

Comments for Table, Column

for Table
SQL> COMMENT ON TABLE Emp IS 'This is a table for Employee.'

Sql> select * from user_tab_comments;

for Column
SQL> COMMENT ON COLUMN jobs.job_id IS 'Primary key of jobs table.';

Sql> select * from user_col_comments;

Uses of Global Temporary Table in SQL?


SQL> CREATE GLOBAL TEMPORARY TABLE supplier
2 ( supplier_id numeric(10) not null,
3 supplier_name varchar2(50) not null,
4 contact_name varchar2(50)
5 )
6 /
SQL> create global temporary table employee_tab
2 on commit preserve rows
3 as select * from employee;

SQL> DROP TABLE Employee_tab; (if drop problem is there, user logout and login, then try it will drop)
 If the TRUNCATE statement is issued against a temporary table, only the session specific data is trucated.
There is no affect on the data of other sessions.
 Data in temporary tables is automatically delete at the end of the database session, even if it ends
abnormally.
 Indexes can be created on temporary tables. The content of the index and the scope of the index is that
same as the database session.
Oracle Page 84 of 87

 Views can be created against temporary tables and combinations of temporary and permanent tables.
 Temporary tables can have triggers associated with them.
 Export and Import utilities can be used to transfer the table definitions, but no data rows are processed.
 There are a number of restrictions related to temporary tables but these are version specific.

Uses of Temporary tables

You can create indexes on temporary tables as you would on permanent tables.

For a session-specific temporary table, a session gets bound to the temporary table with the first insert in the
table in the session. This binding goes away at the end of the session or by issuing a TRUNCATE of the table in
the session.

For a transaction-specific temporary table, a session gets bound to the temporary table with the first insert in
the table in the transaction. The binding goes away at the end of the transaction.

DDL operations (except TRUNCATE) are allowed on an existing temporary table only if no session is currently
bound to that temporary table.

Unlike permanent tables, temporary tables and their indexes do not automatically allocate a segment when they
are created. Instead, segments are allocated when the first INSERT (or CREATE TABLE AS SELECT) is performed.
This means that if a SELECT, UPDATE, or DELETE is performed before the first INSERT, the table appears to be
empty.

Temporary segments are deallocated at the end of the transaction for transaction-specific temporary tables and
at the end of the session for session-specific temporary tables.

If you rollback a transaction, the data you entered is lost, although the table definition persists.

You cannot create a table that is simultaneously both transaction- and session-specific.

A transaction-specific temporary table allows only one transaction at a time. If there are several autonomous
transactions in a single transaction scope, each autonomous transaction can use the table only as soon as the
previous one commits.

Because the data in a temporary table is, by definition, temporary, backup and recovery of a temporary table's
data is not available in the event of a system failure. To prepare for such a failure, you should develop
alternative methods for preserving temporary table data.

Using Sequence in Table

CREATE TABLE departments (


ID NUMBER(10) NOT NULL,
DESCRIPTION VARCHAR2(50) NOT NULL);

ALTER TABLE departments ADD (


CONSTRAINT dept_pk PRIMARY KEY (ID));

CREATE SEQUENCE dept_seq;

CREATE OR REPLACE TRIGGER dept_bir


BEFORE INSERT ON departments
FOR EACH ROW
WHEN (new.id IS NULL)
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/
SQL> INSERT INTO departments (description)
2 VALUES ('Development');

1 row created.
Oracle Page 85 of 87

SQL> SELECT * FROM departments;

ID DESCRIPTION
---------- --------------------------------------------------
1 Development

1 row selected.

SQL> INSERT INTO departments (id, description)


2 VALUES (dept_seq.NEXTVAL, 'Accounting');

1 row created.

SQL> SELECT * FROM departments;

ID DESCRIPTION
---------- --------------------------------------------------
1 Development
2 Accounting

2 rows selected.

What packages (if any) has Oracle provided for use by developers?
Expected answer: 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. If they can mention
a few of these and describe how they used them, even better. If they include the SQL routines provided by
Oracle, great, but not really what was asked.

Where the Pre_defined_exceptions are stored


In the standard package. Procedures, Functions & Packages ;
Give two methods you could use to determine what DDL changes have been made?
You could use Logminer or Streams

What is a package cursor?


A package cursor is a cursor which you declare in the package specification without an SQL statement. The SQL
statement for the cursor is attached dynamically at runtime from calling procedures.

If I have an execute privilege on a procedure in another users schema, can I execute his procedure even
though I do not have privileges on the tables within the procedure?
Yes

What is a forward declaration ? What is its use ?


PL/SQL requires that you declare an identifier before using it. Therefore, you must declare a subprogram before
calling it.This declaration at the start of a subprogram is called forward declaration.A forward declaration
consists of a subprogram specification terminated by a semicolon.

Assume that there are multiple databases running on one machine.How can you switch from one to
another?
Changing the ORACLE_SID

what is difference between foreign key and reference key


A foreign key is a field (or fields) that points to the primary key of another table.
In EMP table Mgr field is the Reference key because it pointing to the Empno field in the same table

What's the length of SQL integer ?


32 bit length

Can you create index on view


No

How can you avoid indexes ?


To make index access path unavailable
 Use FULL hint to optimizer for full table scan
Oracle Page 86 of 87

 Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another.
 Use an expression in the Where Clause of the SQL.

A table has the following data : [[5, Null, 10]].What will the average function return ?
7.5

If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last
record or first record ?
Last Record

Can a trigger written for a view ?


No

How many rows will the following SQL return :


Select * from emp Where rownum = 10;
No rows

B-TREE Index (B-Trees: Balanced Tree Data Structures)


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.

B-tree indexes are created to decrease the amount of I/O required to find and load a set of data. A highly
selective index uses least amount of I/O necessary, poorly selective indices are not much better than a table
scan.

What are Oracle-supplied packages available?


• DBMS_OUTPUT
• DBMS_SQL
• UTL_FILE
• DBMS_PIPE
• DBMS_ALERT
Oracle Page 87 of 87

Different types of Joins


Triggers (row,statement)
http://sharegang.com/oracle-interview-questions-answers/index7.html

The following topics will be covered—Bulk Binds,Sub-Query Factoring,Performance


Tuning,Creating Anonymous PL/SQL block, Analytics Functions,Oracle Data Dictionay,
Dynamic SQL,etc.

http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/
functions001.htm#SQLRF06174

You might also like