Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Global Temporary Tables

Applications often use some form of temporary data store for processes that are to complicated
to complete in a single pass. Often, these temporary stores are defined as database tables or
PL/SQL tables. In Oracle 8i, the maintenance and management of temporary tables can be
delegated to the server by using Global Temporary Tables.

Creation of Global Temporary Tables


The data in a global temporary table is private, such that data inserted by a session can only be
accessed by that session. The session-specific rows in a global temporary table can be preserved
for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause
indicates that the data should be deleted at the end of the transaction.

CREATE GLOBAL TEMPORARY TABLE my_temp_table (


column1 NUMBER,
column2 NUMBER
) ON COMMIT DELETE ROWS;

In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows should be preserved until
the end of the session.

CREATE GLOBAL TEMPORARY TABLE my_temp_table (


column1 NUMBER,
column2 NUMBER
) ON COMMIT PRESERVE ROWS;

Miscellaneous Features
 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 deleted 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.
 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.

What are Cursors?

A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed
by it. This temporary work area is used to store the data retrieved from the database, and
manipulate this data. A cursor can hold more than one row, but can process only one row at a
time. The set of rows the cursor holds is called theactive set.

There are two types of cursors in PL/SQL:

Implicit cursors:

These are created by default when DML statements like, INSERT, UPDATE, and DELETE
statements are executed. They are also created when a SELECT statement that returns just
one row is executed. 

Explicit cursors:

They must be created when you are executing a SELECT statement that returns more than
one row. Even though the cursor stores multiple records, only one record can be processed at
a time, which is called as current row. When you fetch a row the current row position moves
to next row.

Both implicit and explicit cursors have the same functionality, but they differ in the way they
are accessed. 

What is a Stored Procedure?

A stored procedure or in simple a proc is a named PL/SQL block which performs one or more
specific task. This is similar to a procedure in other programming languages. A procedure has
a header and a body. The header consists of the name of the procedure and the parameters
or variables passed to the procedure. The body consists or declaration section, execution
section and exception section similar to a general PL/SQL Block. A procedure is similar to an
anonymous PL/SQL Block but it is named for repeated usage.

How to pass parameters to Procedures and Functions in PL/SQL ?

In PL/SQL, we can pass parameters to procedures and functions in three ways.

1) IN type parameter: These types of parameters are used to send values to stored


procedures. 
2) OUT type parameter: These types of parameters are used to get values from stored
procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values from
stored procedures.
NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN
type parameter.

1) IN parameter:

This parameter is a read only parameter. We can assign the value of IN type parameter to a
variable or use it in a query, but we cannot change its value inside the procedure.

2) OUT Parameter:

This is a write-only parameter i.e, we cannot pass values to OUT paramters while executing
the stored procedure, but we can assign values to OUT parameter inside the stored procedure
and the calling program can recieve this output value.

3) IN OUT Parameter:

The IN OUT parameter allows us to pass values into a procedure and get output values from
the procedure.

What is a Function in PL/SQL?

A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.

What is a Trigger?

A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,
Update is executed on a database table. A trigger is triggered automatically when an
associated DML statement is executed.

 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the
given name or overwrites an existing trigger with the same name.
 {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the
trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used
to create a trigger on a view. before and after cannot be used to create a trigger on a
view.
 {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event.
More than one triggering events can be used together separated by OR keyword. The
trigger gets fired at all the specified triggering event.
 [OF col_name] - This clause is used with update triggers. This clause is used when you
want to trigger an event only when a specific column is updated.
 [ON table_name] - This clause identifies the name of the table or view to which the
trigger is associated.
 [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new
values of the data being changed.
 [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when
each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql
statement is executed(i.e.statement level Trigger).
 WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired
only for rows that satisfy the condition specified.

Types of PL/SQL Triggers


There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted. 
2) Statement level trigger - An event is triggered for each sql statement executed. 

PL/SQL Trigger Execution Hierarchy


The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected. 
3) Then AFTER row level trigger fires once for each affected row. This events will alternates
between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

1) BEFORE UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' before a sql update statement is executed, at the statement level.

2) ) BEFORE UPDATE, Row Level: This trigger will insert a record into the table
'product_check' before each row is updated.

3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' after a sql update statement is executed, at the statement level.
4) AFTER UPDATE, Row Level: This trigger will insert a record into the table
'product_check' after each row is updated.

CYCLIC CASCADING in a TRIGGER


This is an undesirable situation where more than one trigger enter into an infinite loop. while
creating a trigger we should ensure the such a situtation does not exist.

The below example shows how Trigger's can enter into cyclic cascading.
Let's consider we have two tables 'abc' and 'xyz'. Two triggers are created.
1) The INSERT Trigger, triggerA on table 'abc' issues an UPDATE on table 'xyz'.
2) The UPDATE Trigger, triggerB on table 'xyz' issues an INSERT on table 'abc'.

In such a situation, when there is a row inserted in table 'abc', triggerA fires and will update
table 'xyz'. 
When the table 'xyz' is updated, triggerB fires and will insert a row in table 'abc'.
This cyclic situation continues and will enter into a infinite loop, which will crash the
database.

Ref Cursor:

ref cursor is a data structure which points to an object which in turn points to the
memory location.

ex:

type ref_cursor is ref cursor;

open ref_cursor as

select * from table_name;

There are 2 types in this.

1.strong ref cursor:This has a return type defined.

2. weak ref cursor: this doesnt have a return type

normal cursor:Nothing but the named memory location.

it has 2 types

1. explicit cursor:Need to be defined  whenever required.

2.Implicit cursor:need not defined and used by oracle implicitly in DML operation.
Joints
A join is used to combine rows from multiple tables. A join is performed whenever two or more
tables is listed in the FROM clause of an SQL statement.

There are different kinds of joins. Let's take a look at a few examples.

In Oracle we can catogrise joins in following ways -


(1) Equi Join (Query having equal sign for condition)

select empno, ename, dname


from emp join dept
on emp.deptno = dept.deptno;

(2) Non Equi Join: in both table column value is not


directly equal. so, for joining both table can't use
equal
sign. in plce of it use BETWEEN,<=, >= operators.

select ename, sal


from emp join salgrade
on sal between losal and hisal;
(3)Outer Join: to fetch matched or unmatched data from
single or both tables.
- left outer join
- right outer join
- full outer join
(4) self Join or Theta Join : joining one table with
itself
as another table.

select e1.empno, e1.ename employee, e2.empno mgr_number,


e2.ename manager
from emp e1 right outer join emp e2
on e1.mgr = e2.empno

(5) Cross Join : when we avoid to specify the joiing


condition means WHERE clause then it's become CROSS JOIN.

select ename, dname


from emp join dept;
Exception Handling
What is Exception Handling?

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as
exception Handling. Using Exception Handling we can test the code and avoid it from exiting
abruptly. When an exception occurs a messages which explains its cause is recieved. 

Types of Exception.

There are 3 types of Exceptions. 


a) Named System Exceptions 
b) Unnamed System Exceptions 
c) User-defined Exceptions

a) Named System Exceptions

System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
There are some system exceptions which are raised frequently, so they are pre-defined and
given a name in Oracle which are known as Named System Exceptions.

For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.

Named system exceptions are: 


1) Not Declared explicitly, 
2) Raised implicitly when a predefined Oracle error occurs, 
3) caught by referencing the standard name within an exception-handling routine.

Those system exception for which oracle does not provide a name is known as unamed system
exception. These exception do not occur frequently. These Exceptions have a code and an
associated message.

There are two ways to handle unnamed sysyem exceptions: 


1. By using the WHEN OTHERS exception handler, or 
2. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using
a Pragma called EXCEPTION_INIT. 
EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined
exception name.

User-defined Exceptions

Apart from sytem exceptions we can explicity define exceptions based on business rules.
These are known as user-defined exceptions.

Steps to be followed to use user-defined exceptions: 


• They should be explicitly declared in the declaration section. 
• They should be explicitly raised in the Execution Section. 
• They should be handled by referencing the user-defined exception name in the exception
section.

For Example: Lets consider the product table and order_items table from sql joins to explain
user-defined exception. 

Bulk Collect

Executing sql statements in plsql programs causes a context switch between the plsql engine and
the sql engine. Too many context switches may degrade performance dramatically. In order to
reduce the number of these context switches we can use a feature named bulk binding. Bulk
binding lets us to transfer rows between the sql engine and the plsql engine as collections. Bulk
binding is available for select, insert, delete and update statements.

Types of SQL function in Oracle


Oracle functions may be two types SQL functions and user defined functions. SQL functions are built into
oracle database. And user defined functions are created by user.
Based the task performed by oracle functions we can classify oracle functions in the following.

A)Single-Row Functions: Single row functions return just one row for every row of a queried table or
view. A detail explanation of single row function is found in

B)Aggregate Functions: Aggregate function returns a single row based on a set of rows. A common use
of aggregate function is with the GROUP BY clause in a SELECT statement. A detail explanation of
aggregate function is found in

C)Analytic Functions: Analytic functions compute an aggregate value based on a group of rows. The
difference of analytic function from aggregate functions in that they return multiple rows for each group.
A detail explanation of analytic function is found in

D)Object Reference Functions: Object reference functions manipulate REF values, which are
references to objects of specified object types. A detail explanation of object reference function is found in

E)Model Functions: Model functions can be used only in the model_clause of the SELECT statement.
A details explanation of model functions are discussed in

F)User Defined Functions:

21.  How would you determine the time zone under which a
database was operating?

select DBTIMEZONE from dual;

22.  Explain the use of setting GLOBAL_NAMES equal to TRUE.

Setting GLOBAL_NAMES dictates how you might connect to a database.


This variable is either TRUE or FALSE and if it is set to TRUE it enforces
database links to have the same name as the remote database to which
they are linking.

23.  What command would you use to encrypt a PL/SQL


application?

WRAP

24.  Explain the difference between a FUNCTION, PROCEDURE and


PACKAGE.

A function and procedure are the same in that they are intended to be a
collection of PL/SQL code that carries a single task. While a procedure
does not have to return any values to the calling application, a function will
return a single value. A package on the other hand is a collection of
functions and procedures that are grouped together based on their
commonality to a business function or application.

25.  Explain the use of table functions.

Table functions are designed to return a set of rows through PL/SQL


logic but are intended to be used as a normal table or view in a SQL
statement. They are also used to pipeline information in an ETL
process.
26.  Name three advisory statistics you can collect.

Buffer Cache Advice, Segment Level Statistics, & Timed Statistics

27.  Where in the Oracle directory tree structure are audit traces
placed?

In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer

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

29.  When a user process fails, what background process cleans


up after it?

PMON

30.  What background process refreshes materialized views?

The Job Queue Processes.

31.  How would you determine what sessions are connected and
what resources they are waiting for?

Use of V$SESSION and V$SESSION_WAIT

32.  Describe what redo logs are.

Redo logs are logical and physical structures that are designed to hold all
the changes made to a database and are intended to aid in the recovery
of a database.

33.  How would you force a log switch?

ALTER SYSTEM SWITCH LOGFILE;

34.  Give two methods you could use to determine what DDL
changes have been made.

You could use Logminer or Streams

35.  What does coalescing a tablespace do?

Coalescing is only valid for dictionary-managed tablespaces and de-


fragments space by combining neighboring free extents into large single
extents.
36.  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.

37.  Name a tablespace automatically created when you create a


database.

The SYSTEM tablespace.

38.  When creating a user, what permissions must you grant to


allow them to connect to the database?

Grant the CONNECT to the user.

39.  How do you add a data file to a tablespace?

ALTER TABLESPACE <tablespace_name> ADD DATAFILE <datafile_name> SIZE <size>

40.  How do you resize a data file?

ALTER DATABASE DATAFILE <datafile_name> RESIZE <new_size>;

41.  What view would you use to look at the size of a data file?

DBA_DATA_FILES

42.  What view would you use to determine free space in a


tablespace?

DBA_FREE_SPACE

43.  How would you determine who has added a row to a table?

Turn on fine grain auditing for the table.

44.  How can you rebuild an index?

ALTER INDEX <index_name> REBUILD;

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

46.  You have just compiled a PL/SQL package but got errors, how
would you view the errors?

SHOW ERRORS
47.  How can you gather statistics on a table?

The ANALYZE command.

48.  How can you enable a trace for a session?

Use the DBMS_SESSION.SET_SQL_TRACE or

Use ALTER SESSION SET SQL_TRACE = TRUE;

49.  What is the difference between the SQL*Loader and IMPORT


utilities?

These two Oracle utilities are used for loading data into the database. The
difference is that the import utility relies on the data being produced by
another Oracle utility EXPORT while the SQL*Loader utility allows data to
be loaded that has been produced by other utilities from different data
sources just so long as it conforms to ASCII formatted or delimited files.

50.  Name two files used for network connection to a database.

TNSNAMES.ORA and SQLNET.ORA

You might also like