Thursday, May 10, 2007

Views in Oracle

What is a view ?
Ans :One simple answer is "Views are Virtual Tables".

What is a Virtual Table ?
Ans :One Simple Answer is a Table that does not have a Physical Memory Storage in the database.

If view does not have a physical memory storage, then how the data is retrieved from a view ?
From Where the data is retrieved ? How the data is retrieved ? What really happens when you query a view? How does a view help in performance ?

If you do not have answers to the above questions , do consider the following

A view is simply the representation of a SQL statement that is stored in memory, so
that it can be reused.

SELECT empid FROM emp;

If the above query is most frequently used, then I would like to make it a view.

For creating a view,

CREATE VIEW view_emp
AS
SELECT empid FROM emp;

The above statement will create a view and does not result in anything that is actually
stored in database, except for an entry in the data dictionary entry that defines this view.

For querying this view,

SELECT * FROM emp_view WHERE empid BETWEEN 500 AND 1000;

Oracle will transform this query as

SELECT * FROM (SELECT empid FROM emp) WHERE empid BETWEEN 500 AND 1000;

Oracle stores a view's definition in the data dictionary as the text of the query that defines the view.

When you reference a view in a SQL statement, Oracle:

1. Merges the statement that references the view with the query that defines the view
2. Parses the merged statement in a shared SQL area
3. Executes the statement

Oracle parses a statement that references a view in a new shared SQL area only if no existing shared SQL area contains a similar statement. Therefore, you get the benefit of reduced memory use associated with shared SQL when you use views.

Since view does not have a physical memory storage they are said to be "Virtual Tables".
We are querying the data which is already stored in the database ; rendering data from a view is relatively faster.

Shared SQL Area : A Shared SQL area is required, to process every unique SQL statement submitted to
a database and contains information such as the parse tree and execution plan for the corresponding statement.

This is a basic information regarding views. We will be discussing more interesting concepts.

1 comment:

Kamalesh R S said...

hi ppl,
congrats . Nice initiative.

Hi prabhu, nice topic too.
Just had a couple of questions on this post:

1. In what way does select * from empid scores over select * from emp_view. Since both any ging to make a call to the db. Actually if its a direct qry to the table then its only a single job of querying against the db where as in case of view the view has to be searched from a data dictionary then it internally has a replacement f the query then it queries the db. Looks like this will take more time than directly querying the db with the direct query.

2. Can you share more about shared areas and its advantages.

Thanks and hope to see more posts.