Oracle Questions
Oracle Questions
Oracle Questions
Unique Constraint
ALTER TABLE SAMP.DEPARTMENT
ADD CONSTRAINT NEW_UNIQUE UNIQUE (DEPTNO);
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
What is a transaction?
Transaction is logical unit between two commits and commit and rollback.
NVL2
NVL2( string1, value_if_NOT_null, value_if_null )
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('BILL ' , 12 , 'CLINTON') FROM DUAL SELECT RPAD('BILL ' , 12 , 'CLINTON') FROM DUAL
ANS : CLINTONBILL ANS : BILL CLINTON
Self : SELECT e1.ename||' works for '||e2.ename "Employees and their Managers"
FROM emp e1, emp e2
WHERE e1.mgr = e2.empno;
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...)
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.
The Oracle equivalent of the inner joins we have seen so far is as follows.
Using Where
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;
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.
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.
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.
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.
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.
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
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''.
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';
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;
What is ROWID?
It is 18-character long, block no, row number are the components of ROWID.
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.
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 is the maximum number of CHECK constraints that can be defined on a column ?
No Limit.
ABSTRACT DATYPES
/
SQL> DESC CUSTOMER
SQL>
ID NUMBER(4)
NAME VARCHAR2(25)
ADDRESS CUST_ADDRESS_TY
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.
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.
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 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
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
Rank :
SELECT deptno, ename,sal,
RANK() OVER (PARTITION BY deptno ORDER BY sal) "rank"
FROM emp
WHERE deptno = 30;
30 BLAKE 2850 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.
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.
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.
8 rows selected.
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.
8 rows selected.
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.
FROM emp
WHERE deptno IN (20, 30)
ORDER BY deptno, DAY_GAP;
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;
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
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:
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.
EX :
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;
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
Memory Savings
– Only one copy of procedure needs to be loaded in memory for execution by multiple users
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;
or
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.
Syntax
Oracle Page 18 of 87
DECLARE
variable_declarations
BEGIN
program_code
EXCEPTION
exception_handlers
END;
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
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
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;
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 > 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.
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?
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
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';
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.
close c_f;
end;
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 cursor attributes used in PL/SQL ? (Both implicit and Explicit)
Explicit :
Implicit :
SQL%ISOPEN, SQL%ROWCOUNT, SQL%FOUND, SQL%NOTFOUND
Ex : UPDATE employee SET salary = salary * 1.1;
Pre-Defined Exception
Declare
N number;
Begin
N:=10/0;
Exception
When Zero_divide then
Dbms_output.put_line (‘Zero Divide Error’);
End;
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;
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
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
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
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.
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.
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;
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.
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.
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.
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
Compound Triggers
A compound trigger is a single trigger on a table that enables you to specify actions for each of four timing points:
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
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)
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.
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.
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
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'
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
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;
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;
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
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.
Advantages of package:
----------------------------
A. Modularity
- Encapsulate related constructs.
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.
- 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.
procedure r_p as
no1 number;
begin
select count(*) into no1 from emp;
dbms_output.put_line(no1);
end r_p;
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.
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.
Index types can we index more than one column and how to find which index is activated?
Use explain plan
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.
The logical structures of an Oracle database include schema objects, data blocks, extents, segments, and
tablespaces.
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 schema?
A schema is collection of database objects of a User.
tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages
anddatabase links.
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 ….
What is a Synonym?
A synonym is an alias for a table, view, sequence or program unit.
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
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.
No.
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.
It stores information about both the logical and physical structure of the database.
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.
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.
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.
Lckn :: We can have upto 10 lock processes for inter instance locking in parallel SQL.
Though a single LCK process is sufficient for most Parallel Server systems upto Ten Locks (LCK0,....LCK9) are
used for inter-instance locking.
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.
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 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 various privileges that a user can grant to another user?
SELECT, CONNECT, RESOURCES
What is Auditing ?
Monitoring of user access to aid in the investigation of database use.
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.
Where would you look for errors from the database engine?
In the alert log.
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.
When creating a user, what permissions must you grant to allow them to connect to the database?
Grant the CONNECT to the user.
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.
How would you determine what sessions are connected and what resources they are waiting for?
Use of V$SESSION and V$SESSION_WAIT
Give two methods you could use to determine what DDL changes have been made?
You could use Logminer or Streams.
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.
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.
DATA BASE
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.
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 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
GENERAL
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.
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.
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.
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 /
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.
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:
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.
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;
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.
FETCH ...;
EXIT WHEN c%NOTFOUND;
INSERT ...;
END LOOP;
ANSI 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
With condition
EXP SCOTT/TIGER FILE= abc.dmp TABLES=emp QUERY=\” WHERE SAL < 2000 \”
IMPORT UTILITY
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
Personal
What r my interests?
Upgrade Technical skills, Learn new things, Playing
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.
What is Parsing ?
Syntax checking, privileges checking and allocating Private SQL Area.
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
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
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;
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;
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
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.
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
COALESCE command
Select coalesce(comm, deptno) from emp;
If comm. is null then deptno otherwise comm.
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
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.
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.
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:
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
-- 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;
/
Bulk collect
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;
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.
l_employees employees_aat;
BEGIN
OPEN employees_cur;
LOOP
FETCH employees_cur
BULK COLLECT INTO l_employees LIMIT limit_in;
Set Auto Trace On (How to start Auto trace, it is useful execution paln)
Table created.
Associative Arrays
Arrays have been available in PL/SQL since its very early versions, when Oracle called them "PL/SQL Tables".
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
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 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].
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
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).
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.
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.
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> 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.
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.
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
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.
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;
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;
Interview query - display the date on which I have not taken the interview
* 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.
What is the difference between clustered Index and Non Clustered Indexes?
Oracle Page 77 of 87
For Unclustered
Create INDEX ------Index name ------
on Table-Name ( ----Column Name---)
for Clustered
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
Do not use 'SELECT COUNT(*) ...' to test for the existence of a row. Open an explicit cursor, fetch once, and then
check cursor%NOTFOUND.
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.
Use OUTER JOIN, DECODE and GROUP functions to perform multiple operations with single query/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.
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
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;
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
END;
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;
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;
/
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;
/
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;
/
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
In the PL/SQL table "Bonlist" you can now find the updated salaries.
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 Column in a very big Table, when you get Rollback Segments Problems
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.
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);
30 6 9400
14 29025
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);
for Table
SQL> COMMENT ON TABLE Emp IS 'This is a table for Employee.'
for Column
SQL> COMMENT ON COLUMN jobs.job_id IS 'Primary key of jobs table.';
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.
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.
1 row created.
Oracle Page 85 of 87
ID DESCRIPTION
---------- --------------------------------------------------
1 Development
1 row selected.
1 row created.
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.
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
Assume that there are multiple databases running on one machine.How can you switch from one to
another?
Changing the ORACLE_SID
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
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.
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/
functions001.htm#SQLRF06174