Sunteți pe pagina 1din 5

An inline view is a SELECT statement in the FROM-clause of another SELECT statement.

In-line views are commonly used simplify complex queries by


removing join operations and condensing several separate queries into a single query. This feature was introduced in Oracle 7.2.

The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name.

A common use for in-line views in Oracle SQL is to simplify complex queries by removing join operations and condensing several separate queries into a
single query.

Example inline view:

SELECT *
FROM (select deptno, count(*) emp_count
from emp
group by deptno) emp,
dept
WHERE dept.deptno = emp.deptno;

A subquery (sub-query) is a SELECT statement in the WHERE- or HAVING-clause of another SELECT statement.

Example subqueries:

Subquery executes first and feeds output into the main query:

SELECT ename, deptno


FROM emp
WHERE deptno = (SELECT deptno
FROM emp
WHERE ename = 'TAYLOR');

Correlated subquery (both executes simultaneously):

SELECT ename, deptno, sal


FROM emp x
WHERE sal > (SELECT AVG(sal)
FROM emp
WHERE emp.deptno = x.deptno)
ORDER BY deptno;

Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query.
Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row.
For example,
Correlated Subquery:
select e1.empname, e1.basicsal, e1.deptno from emp e1 where e1.basicsal = (select max(basicsal) from emp e2 where e2.deptno = e1.deptno)
Nested Subquery:
select empname, basicsal, deptno from emp where (deptno, basicsal) in (select deptno, max(basicsal) from emp group by deptno)

Co-related Sub-query
A correlated subquery is evaluated once for each row processed by the parent statement. Sub query is one in which inner query is evaluated only once and from
that result outer query is evaluated. Correlated Sub query is one in which Inner query is evaluated for multiple times for getting one row of that outer query.
Co-related query is a query in which sub query depends on execution of main query In this query main query will executes first. Sub-query will depends on the
main query. It fallows top down approach. In normal sub queries sub query will executes first. It follows down to top approach. The main difference between
sub query and co-related sub query is that in sub query child query is executed first n then parent but in co-related sub query main query is executed first(even
though parenthesis are present) and then child query.
Example of co-related sub query
1. Select dname from dept where exists (select deptno from emp where dept.deptno emp.deptno);
2. Select deptno, ename, sal from emp a where sal = (select max(sal) from emp where deptno = a.deptno)
order by deptno
The inner query is executed for each candidate row in the outer statement.
The following statement returns data about employees whose salaries exceed their department average. The following statement assigns an alias to employees,
the table containing the salary information, and then uses the alias in a correlated subquery:
SELECT department_id, last_name, salary
FROM employees x
WHERE salary > (SELECT AVG(salary)
FROM employees
WHERE x.department_id = department_id)
ORDER BY department_id;

What is the main difference between the IN and EXISTS clause in subqueries??
The main difference between the IN and EXISTS predicate in subquery is the way in which the query gets executed.

IN -- The inner query is executed first and the list of values obtained as its result is used by the outer query.The inner query is executed for only once.

EXISTS -- The first row from the outer query is selected ,then the inner query is executed and , the outer query output uses this result for checking.This process
of inner query execution repeats as many no.of times as there are outer query rows. That is, if there are ten rows that can result from outer query, the inner
query is executed that many no.of times.

Indexes:
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns.
By default, Oracle creates B-tree indexes.
Syntax:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, . column_n)
[ COMPUTE STATISTICS ];
Finding n the salary:
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
SELECT SAL,R FROM (SELECT ROWNUM R,SAL FROM (SELECT SAL FROM
EMP ORDER BY SAL DESC)) WHERE R=&N
Rownum:
rownum is a pseudo column. It numbers the records in a result set. The first record that meets the where criteria in a select statement is given rownum=1, and
every subsequent record meeting that same criteria increases rownum.

JOINS
A join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database performs a join whenever multiple tables appear
in the FROM clause of the query. The select list of the query can select any columns from any of these tables. If any two of these tables have a column name in
common, then you must qualify all references to these columns throughout the query with table names to avoid ambiguity.
TYPES OF JOINS :
1) EQUI JOIN(OR) INNER JOIN
2) NON-EQUI JOIN
3)OUTER JOIN
3.1) LEFT OUTER JOIN
3.2) RIGHT OUTER JOIN
3.3) FULL OUTER JOIN
4)SELF join
The INNER JOIN keyword return rows when there is at least one match in both tables.
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).
The FULL JOIN keyword return rows when there is a match in one of the tables.
A SELF JOIN is a type of sql join which is used to join a table to itself, particularly when the table has a FOREIGN KEY that references its own PRIMARY
KEY. It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity.
A CROSS JOIN (or Cartesian Product join) will return a result table where each row from the first table is combined with each row from the second table. The
number of rows in the result table is the product of the number of rows in each table. If the tables involved are large, this join can take a very long time.
A THETA join that links tables based on a relationship other than equality between two columns.

Materialized view
In a database management system following the relational model, a view is a virtual table representing the result of a database query. Whenever an ordinary
view's table is queried or updated, the DBMS converts these into queries or updates against the underlying base tables. A materialized view takes a different
approach in which the query result is cached as a concrete table that may be updated from the original base tables from time to time. This enables much more
efficient access, at the cost of some data being potentially out-of-date. It is most useful in data warehousing scenarios, where frequent queries of the actual base
tables can be extremely expensive.

In addition, because the view is manifested as a real table, anything that can be done to a real table can be done to it, most importantly building indexes on any
column, enabling drastic speedups in query time. In a normal view, it's typically only possible to exploit indexes on columns that come directly from (or have a
mapping to) indexed columns in the base tables; often this functionality is not offered at all.

Materialized Views in Oracle


A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables
based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, know as snapshots.
A materialized view can query tables, views, and other materialized views. Collectively these are called master tables (a replication term) or detail tables (a data
warehouse term). For replication purposes, materialized views allow you to maintain copies of remote data on your local node. These copies are read-only. If
you want to update the local copies, you have to use the Advanced Replication feature. You can select data from a materialized view as you would from a table
or view. For data warehousing purposes, the materialized views commonly created are aggregate views, single-table aggregate views, and join views.
In this article, we shall see how to create a Materialized View and discuss Refresh Option of the view. In replication environments, the materialized views
commonly created are primary key, rowid, and subquery materialized views.
Primary Key Materialized Views
The following statement creates the primary-key materialized view on the table emp located
on a remote database.
SQL> CREATE MATERIALIZED VIEW mv_emp_pk
REFRESH FAST START WITH SYSDATE
NEXT SYSDATE + 1/48
WITH PRIMARY KEY
AS SELECT * FROM emp@remote_db;
Materialized view created.
Note: When you create a materialized view using the FAST option you will need to create a
view log on the master tables(s) as shown below:
SQL> CREATE MATERIALIZED VIEW LOG ON emp;
Materialized view log created.
Rowid Materialized Views
The following statement creates the rowid materialized view on table emp located on a
remote database:
SQL> CREATE MATERIALIZED VIEW mv_emp_rowid
REFRESH WITH ROWID
AS SELECT * FROM emp@remote_db;
Materialized view log created.
Subquery Materialized Views
The following statement creates a subquery materialized view based on the emp and dept
tables located on the remote database:
SQL> CREATE MATERIALIZED VIEW mv_empdept
AS SELECT * FROM emp@remote_db e
WHERE EXISTS
(SELECT * FROM dept@remote_db d
WHERE e.dept_no = d.dept_no)
REFRESH CLAUSE
[refresh [fast|complete|force]
[on demand | commit]
[start with date] [next date]
[with {primary key|rowid}]]
The refresh option specifies:
a. The refresh method used by Oracle to refresh data in materialized view
b. Whether the view is primary key based or row-id based
c. The time and interval at which the view is to be refreshed
Refresh Method - FAST Clause
The FAST refreshes use the materialized view logs (as seen above) to send the rows that have changed from master tables to the materialized view.
You should create a materialized view log for the master tables if you specify the REFRESH FAST clause.
SQL> CREATE MATERIALIZED VIEW LOG ON emp;
Materialized view log created. Materialized views are not eligible for fast refresh if the defined subquery contains an analytic function.
Refresh Method - COMPLETE Clause
The complete refresh re-creates the entire materialized view. If you request a complete refresh, Oracle performs a complete refresh even if a fast refresh is
possible.

NSTEAD OF Triggers

INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML statements (INSERT, UPDATE, and
DELETE). These triggers are called INSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead of executing the triggering
statement.

You can write normal INSERT, UPDATE, and DELETE statements against the view and the INSTEAD OF trigger is fired to update the underlying tables
appropriately. INSTEAD OF triggers are activated for each row of the view that gets modified.
Modify Views

Modifying views can have ambiguous results:

* Deleting a row in a view could either mean deleting it from the base table or updating some values so that it is no longer selected by the view.
* Inserting a row in a view could either mean inserting a new row into the base table or updating an existing row so that it is projected by the view.
* Updating a column in a view that involves joins might change the semantics of other columns that are not projected by the view.

Object views present additional problems. For example, a key use of object views is to represent master/detail relationships. This operation inevitably involves
joins, but modifying joins is inherently ambiguous.

As a result of these ambiguities, there are many restrictions on which views are modifiable. An INSTEAD OF trigger can be used on object views as well as
relational views that are not otherwise modifiable.

Even if the view is inherently modifiable, you might want to perform validations on the values being inserted, updated or deleted. INSTEAD OF triggers can
also be used in this case. Here the trigger code performs the validation on the rows being modified and if valid, propagate the changes to the underlying tables.

INSTEAD OF triggers also enable you to modify object view instances on the client-side through OCI. To modify an object materialized by an object view in
the client-side object cache and flush it back to the persistent store, you must specify INSTEAD OF triggers, unless the object view is inherently modifiable.
However, it is not necessary to define these triggers for just pinning and reading the view object in the object cache.

Views That Are Not Modifiable

A view is inherently modifiable if data can be inserted, updated, or deleted without using INSTEAD OF triggers and if it conforms to the restrictions listed as
follows. If the view query contains any of the following constructs, the view is not inherently modifiable and you therefore cannot perform inserts, updates, or
deletes on the view:

* Set operators
* Aggregate functions
* GROUP BY, CONNECT BY, or START WITH clauses
* The DISTINCT operator
* Joins (however, some join views are updatable)

If a view contains pseudocolumns or expressions, you can only update the view with an UPDATE statement that does not refer to any of the pseudocolumns or
expressions.

PL/SQL Ref Cursors

A ref cursor is a variable, defined as a cursor type, which will point to, or reference a cursor result. The advantage that a ref cursor has over a plain cursor is
that is can be passed as a variable to a procedure or a function. The REF CURSORcan be assigned to other REF CURSOR variables. This is a powerful
capability in that the cursor can be opened, then passed to another block for processing, then returned to the original block to be closed. The cursor variable
can also be returned by a function and assigned to another variable. The REF CURSOR variable is not a cursor, but a variable that points to a cursor.

In case of an normal explict cursor, the SQL query has to be defined at the time of declaring the cursor itself. In case of REF Cursor, the cursor declartion is
not associated with any SQL query, it is associated with a query at a later stage this brings in a lot of flexibility as different SQL queries can be associated with
the cursor (one at a time, offcourse) programatically. REF Cursors also provide the feature of passing parameters. Though there is something dynamic with
REF Cursor when compared to a normal explicit cursor, it is not a truly perfect dynamic cursor. Truly perfect dynamic cursors are the one constructed using
DBMS_SQL package.
A REF CURSOR is basically a data type. A variable created based on such a data type is generally called a cursor variable. A cursor variable can be associated
with different queries at run-time. The primary advantage of using cursor variables is their capability to pass result sets between sub programs (like stored
procedures functions packages etc.).

Example :-

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;
procedure PrintEmployeeDetails is
begin
loop
fetch c_emp into er;
exit when c_emp notfound;
dbms_output.put_line(er.name || ' - ' || er.sal);
end loop;
end;
begin
for i in (select deptno dname from dept)
loop
open c_emp for select ename sal from emp where deptno i.deptno;
dbms_output.put_line(i.dname);
dbms_output.put_line('--------------');
PrintEmployeeDetails;
close c_emp;
end loop;
end;

In the above program the sub-routine is named "PrintEmployeeDetails." You can observe that I am executing (or calling) the sub-routine from within the loop
as follows:

for i in (select deptno dname from dept)


loop
.
.
PrintEmployeeDetails;
.
.
end loop;

S-ar putea să vă placă și