You are on page 1of 39

Clusters

Tables that are frequently accessed together may be physically stored


together. Clustering is a method of storing tables that are closely related and are
often joined together, into the same area on the disk.
A cluster is created to hold the tables. A cluster contains the values of a
table according to the column that we define. When ever we insert values into
the table the same values are automatically stored in the database object name
cluster.
Cluster can be created by using create cluster command. To create a cluster
use the following syntax
Syntax :
Create cluster <cluster name> (columns specifications,------)
To create any cluster
1. First create a cluster with the column names that you want
2. Next create an index on that cluster. Otherwise the cluster will not work
properly
3. Next create a table with the cluster specification and list of columns
4. Now insert some values into that table, if you see the cluster the same
values will be available from the cluster also
Note :
1. We can not insert or update or delete any row from the cluster
2. We can not even drop the cluster until the source table is present
3. To drop the cluster, first we have to drop the source table and then we can
drop that particular cluster
Creation of cluster for a table
First create the cluster,
create cluster sampleclust (sno number(3), sname varchar2(10));
Next create the index,
create index idx_sampleclust on cluster sampleclust;
Attaching the cluster to the table,
create table sample2 (sno number(3),sname varchar2(10)) cluster
sampleclust(sno,sname)
Example :
1. To display details of the Table
select * from sample2;
SNO SNAME
--------- ----------
100 Nithya
101 Saloni
102 Aruna
1. To display details of the Table
select * from cluster sampleclust;
SNO SNAME
--------- ----------
100 Nithya
101 Saloni
102 Aruna
1. Even if you delete any row in the table, that will not affected to the
cluster
1. delete from sample2 where sno=100;
2. select * from sample2;
SNO SNAME
--------- ----------
101 Saloni
102 Aruna
3. select * from cluster sampleclust;
SNO SNAME
--------- ----------
100 Nithya
101 Saloni
102 Aruna
4. delete from sampleclust where sno=102
ERROR at line 1:
ORA-00942: table or view does not exist
Note : We can not delete any data from the cluster
Drop cluster
This command is used to drop any cluster
Syntax : drop Cluster <cluster name>
To drop any cluster
Drop table sample2;
Drop cluster sampleclust;
Function
A function is a sub program that executes a set of statements and returns a
value to the main program. The basic difference between Functions and
procedures is, function returns a value to the calling program or main program
where as a procedure does not return any value
Syntax of A Function
Create [ Or Replace ] Function < Function Name > ( Argument1 [Mode] <Data
type>, Argument2 [Mode] <data type>,---) return data type
Is / As
Local Variables Declarations;
------------
Begin
Executable Statements;
---------------
[Exception
Exception Handling; ]
End;
/
Example : 1
Write a program to find sum of two numbers
Sol :
ed function1
Create or replace function addition(x integer, y integer) return integer
is
Begin
Return x+y;
End;
/
mainfunction1
Declare
A integer :=&a;
B integer :=&b;
C integer;
Begin
C:=addition(a,b);
Dbms_output.put_line('sum of two numbers is '|| c );
End;
/
Example : 2
wirte a function which accepts item number and quantity and then return the
total amount by fetching rate from the item table
create or replace function itembill(q in number,r in number) return number
is
begin
return q*r;
end;
/
ed mainfunction2
declare
q1 number:=&quantity;
r1 number;
res number;
begin
select rate into r1 from item where itno=&itno;
res:=itembill(q1,r1);
dbms_output.put_line(' Total Amount is '||res);
exception
when no_data_found then
dbms_output.put_line(' No Such Item Exits');
end;
/
Built In Function in Oracle
Built In Function in Oracle
SQL Functions are of two types, they are
1. Single Rows Functions : These functions will have effect on a single row of the
table
2. Group Functions : These functions will have effect on a group of row's
Single Rows Functions
1. Numerical Functions
2. Character Functions
3. Date and Time Functions
4. Conversion Functions
5. General Functions or Miscellaneous Functions
Numerical Functions
1. Abs :This function is used to convert any negative expression into positive
Syntax : Abs (Numeric Expression)
Example : Select abs(-100) from Dual ; 100
Select abs(300-500) from Dual ; 200
Select abs(-20*30) from Dual ; 600
1. Exp (Exponential) :
This Function is used to find the exponential value for the given number. Ie e to
the power of x value ( e
x
). where e has a constant value ie 2.7182
Syntax : Exp(Numeric Expression)
Example : Select exp(0) from Dual ; 1
Select exp(1) from Dual ; 2.7182
Select exp(2) from Dual ; 7.3890
1. Sqrt (Square Root) :This function is used to find the square root value for
the given number
Syntax : Sqrt ( Number )
Example : select sqrt(2) from dual ; 1.4142
select sqrt(16) from dual ; 4
select sqrt(sal) from emp;
select sqrt(4*sqrt(2)) from dual;
1. Power :This function is used to find the power value ie x to the power of y
value
Syntax : Power(x,y)
Example : select power(2,3) from dual ; 8
select power(5,3) from dual ; 125
select power(sal,2) from emp;
1. Round :This function is used to round off the given numeric expression
according to
specified length or precision
Syntax : Round(Numeric Expression, Length)
Example : select round(98.52) from dual; 99
Select round(65.567,1) from dual ; 65.6
Select round(65.567,2) from dual ; 65.57
1. Ceil :This function returns the nearest integer greater than the given
numeric expression
Syntax : Ceil(Numeric Expression)
Example : Select ceil(-23.567) from dual ; -23
Select ceil(23.567) from dual ; 24
1. Floor :This function returns the nearest integer smaller than the given
numeric expression
Syntax : Floor(Numeric Expression)
Example : Select floor(-23.567) from dual ; -24
Select floor(23.567) from dual ; 23
1. Log :this function is used to find the logarithm value for the given number
and for the given base
Syntax : Log(Number, Base Value)
Example : select log(10,10) from dual; 1
select log(2,10) from dual; 3.3219
Character Functions or Text Functions or String Functions
1. || or Concat :
Glues or concatenates two strings together. The | symbol is called as vertical bar
or pipe
Syntax : string1 || string2 ( for || Function)
Syntax : Concat(string1 , string2) ( for concat Function)
Example : select concat ( city, country) from location;
is same as select city || country from location;
1. ASCII :
This Function Returns The Ascii Code Value Of The Left Most Character From The
Given Character Expression
Syntax : Ascii(Character Expression)
Example : select Ascii(a) from dual ; 97
select Ascii(A) from dual ; 65
1. Chr :
This Function Returns The Ascii Character For The Given Ascii Value
Syntax : Chr(Ascii Value)
Example : select chr(65) from dual ; A
Select chr(97) from dual ; a
1. Length :
This Function Is Used To Find The Length Of The Given Character Expression
Syntax : Length ( character expression )
Example : select length (sairam) from dual; 6
select length (ename) from emp;
1. Upper :
This Function Is Used To Convert All Characters In To Upper Case
Syntax : Upper (Character Expression)
Example : select upper (sairam) from dual; SAIRAM
1. Lower :
This Function Is Used To Convert All Characters In To Lower Case
Syntax : Lower (Character Expression)
Example : select lower (SAIRAM) from dual; sairam
7. Ltrim :
This Function Removes Any Spaces From The Left Side of The String
Syntax : Ltrim(String)
Example : select ' sairam' from dual; --> sairam
select Ltrim(' sairam') from dual; --> sairam
8. Rtrim :
This Function Removes Any Space From The Right Side of The String
Syntax : Rtrim(String)
Example : select 'sairam ' from dual; --> sairam
select Rtrim('sairam ') from dual; --> sairam
9. Trim : (Oracle 9i)
If You Are Trimming The Exact Same Data From Both The Beginning And Then End
Of The String, Then You Can Use The Trim Function In Place Of An Ltrim/Rtrim
Combination
Syntax : Trim(String)
Example: select ' sairam ' from dual; --> sairam
select Trim(' sairam ') from dual; --> sairam
10. Substr : (Sub String)
This function returns a part of the string from the specified Position to the
specified number of characters
Syntax: Substr(String, Start Postion,Number of Characters)
Example : select substr('disk operating system',6,9) from dual; --> operating
11. Lpad :
This function is used to append the given text to the left side of any
column or String or lpad function allows you to pad the left side of a column
with any set of Characters.
Syntax : Lpad (<Expression>,<Size>,<String Expression>)
Example : select lpad(sal,7,'Rs. ') from emp;
output
Rs. 800
Rs.1200
Example : select lpad(sal,10,'Rs. ') from emp;
output
Rs. Rs. 800
Rs. Rs.1200
12. Rpad :
This function is used to append the given text to the right side of any column or
string or lpad function allows you to pad the left side of a column with any set
of characters.
Syntax : Rpad(<Expression>,<Size>,<String Expression>)
Example : select Rpad(sal,7,'Rs. ') from emp;
output
800Rs.
1200Rs.
Example : select Rpad(sal,10,'Rs. ') from emp;
output
800Rs. Rs.
1200Rs. Rs
13. Initcap :
This function takes the initial letter of every word in a string or column and
converts just those letters to upper case.
Syntax : initcap (String)
Example : select Initcap(ename) from emp;
select Initcap(WELCOME TO ALL) from emp; Welcome To All
14. Translate :
This function is used to translate the source expression into target expression
that is present in the main string
Syntax : Translate(Main String, Source Expression, Target Expression)
Example : select Translate ('jack','j','b') from dual; back
select Translate ('back and bill','b','j') from dual; jack and jill
it will translate only one char
Date and Time Functions
1. Sysdate :
This Function Returns The System Date And Time. By default it will show only the
data but not the time. To show time also, we have to user To_Char conversion
function
Syntax : Sysdate
Example : select sysdate from dual;
Output
SYSDATE
14-FEB-05
2. Add_Months :
This function is used to add the number of months to the months part of the
accepted dates. ( we can give positive/negative values )
Syntax : Add_Months(Date, Number)
Example : select sysdate, add_months(sysdate,5) from dual;
Output
SYSDATE ADD_MONTH
------------ ---------------
14-FEB-05 14-JUL-05
3. Last_day :
This Function Is Used To Return The Last Day Of Accepted Date (0r) Last Day Of
the Month
Syntax : Last_day ( date expression )
Example : select sysdate, Last_Day(sysdate) from dual;
Output
SYSDATE LAST_DAY(
----------- --------------
14-FEB-05 28-FEB-05
4. Next_Day
This function is used to find the Next day of the given weekday name
Syntax : Next_Day(Date Expression, Week day name)
Example : select sysdate, next_day(sysdate, 'Monday') from dual;
Output
SYSDATE NEXT_DAY(
--------- ----------------
14-FEB-05 21-FEB-05
5. months_between
This function is used to find number of months between the given two dates
Syntax : months_between(date expression1, date expression2)
Example : 1
select months_between(sysdate,
to_date('20-oct-05','dd-mon-yy')) from dual;
MONTHS_BETWEEN(SYSDATE,TO_DATE('20-OCT-05','DD-MON-YY'))
-------------------------------------------------------------------------------
-2.432654
To eliminate decimal points, give the following form
select round(months_between(sysdate,
to_date('20-oct-05','dd-mon-yy'))) from dual
ROUND(MONTHS_BETWEEN(SYSDATE,TO_DA
----------------------------------------------------
-2
select round(months_between(to_date('20-oct-05','dd-mon-yy'),sysdate))
from dual;
ROUND(MONTHS_BETWEEN(TO_DAT
--------------------------------------------
2
Conversion Functions
1. Nvl : It Is Used To Convert The Null Values Of A Column Into Expression Or
Value.
Syntax : NVL(<Column>, <expression>)
Example : select empno, ename, sal, comm, sal+comm from employee;
Using NVL Functions
select empno, ename, sal, comm, sal+nvl(comm,0) from employee;
2. To_char :
This function is used to change the format of accepted date into any predefind
format.
Syntax : To_char(<Date Expression>, <Format>)
Predefined Formats Are
mm/dd/yy
yy.mm.dd
dd/mm/yy
dd.mm.yy
dd-mm-yy
mon yy
mon dd, yy
hh:mm:ss
mon dd yyyy hh:mi:mm (Am or Pm)
mm-dd-yy
yy mm dd
dd mon yyyy hh:mi:ss:mm (24 hour format)
hh:mi:ss:mmm (24 hour)
dy (to find week day number)
day (week day name)
dd (number of days in month)
yyyy (year in four digits)
yy (year of Last two digits)
year (spelt in terms of words)
month (month name)
w (week number)
Example : 1
select sysdate,to_char(sysdate,'dd mm yy') from dual;
SYSDATE TO_CHAR(S
--------- ---------
15-FEB-05 15 02 05
select sysdate,to_char(sysdate,'month dd day w') from dual;
SYSDATE TO_CHAR(SYSDATE,'MONTHDD
--------- ----------------------------------------
15-FEB-05 february 15 tuesday 3
3. To_Date : this function is used to convert any character expression into a date
expression according to the format you specified
Syntax : To_Date(<date expression>, <format>)
Example :
insert into student(jdate) values('jan-10-05')
ERROR at line 1:
ORA-01858: a non-numeric character was found where a numeric was expected
insert into student(jdate) values(to_date('jan-10-05','mon-dd-yy'));
JDATE
---------
10-JAN-05
General Functions or Miscellaneous functions
1. show user : This function is used to show the current user name
syntax : show user;
Example : show user;
Output : user is "SCOTT"
2. uid : this function is used to show the user id of the currently active user
syntax : uid
Example : select uid from dual;
UID
----
18
3. Greatest : this function is used to find the maximum value from a given list of
values
Syntax : Greatest(Value1,Value2,-----)
Example :
select greatest(10,20,40) from dual;
GREATEST(10,20,40)
------------------
40
4. Least : this function is used to find the minimum value from a given list of
values
Syntax : Least(value1,value2,-----)
Example :
select least(10,20,40) from dual;
LEAST(10,20,40)
------------------
10
Stored Procedure

A procedure is a set of instructions(usually combining sql and plsql commands)
saved for calling and repeated execution
A procedure is a sub program that performs a specific action. A procedure can be
called from any pl/sql block. A procedure has two parts one is Specification and
Other is Body
The procedure specification begins with the keyword procedure followed by
procedure name and an option list of arguments enclosed with in the parenthesis.
The procedure body begins with is or as and ends with an end statement.
It consists of three parts
1. Declarative Part
2. Execution Part
3. Exception Handling Part
Syntax of Procedure
Create [ Or Replace ] Procedure < Procedure Name > ( Argument1 [Mode] <Data
type>, Argument2 [Mode] <data type>,---)
Is / As
Local Variables Declarations;
------------
Begin
Executable Statements;
---------------
[Exception
Exception Handling; ]
End;
/
where Mode refers to the type of arguments such as In , Out or InOut
Modes In Procedures And Functions
1. IN : the In parameter lets the user to pass values to the called sub programs
with in the sub program, the IN parameter acts like a constant. There fore it
cannot be modified.
1. OUT : The Out parameter lets the user returned values to the calling block.
Inside the sub program the out parameter acts like a un initialized variable.
Its value can not be assigned to another variable or itself
1. INOUT : the INOUT parameter lets the user pass initial values to the called
sub program and return updated values to the calling block
Note : the default mode of an argument is "IN"
Show Errors :
This Command is used to show the errors that are occurred during the procedure
creation
Ex : when ever we create a procedure and executed, if it show procedure created
with compilation errors, the we can see those errors using the following
statement
show Errors
Example :1
Write a procedure to show a simple message
Sol. Steps
1. Write the sub Program
Ed subprocedure1
Create or replace procedure disp is
Begin
Dbms_output.put_line('This is a Sub Program');
End;
/
1. Next, Compile the above procedure to find errors in the procedure, with
the following statement
@ subprocedure1
1. Next, Write the main program
Begin
Dbms_output.put_line('This is Main Program');
Disp;
Dbms_output.put_line('Again Continuing the Main Program');
End;
/
1. Next, Run the above main procedure with the following statement
@mainprogram1
output :
SQL> @ mainprogram1
This is Main Program
This is a Sub Program
Again Continuing the Main Program
PL/SQL procedure successfully completed.
Example :2
Write a procedure to show a message when updated any row in a particular
table
Sol. Steps
1. Write the sub Program
Ed subprocedure2
Create or replace procedure upd(d number)
is
Begin
update employee set sal=sal+(sal*0.2) where empno=d;
dbms_output.put_line(sql%rowcount||' Record Updated...');
End;
/
1. Next, Compile the above procedure to find errors in the procedure, with
the following statement
@ subprocedure2
1. Next, Write the main program
Begin
upd(&empno);
End;
/
1. Next, Run the above main procedure with the following statement
@mainprogram2
output :
SQL> @ mainprogram2
Enter value for empno: 7369
old 2: upd(&empno);
new 2: upd(7369);
1 Record Updated...
PL/SQL procedure successfully completed.
Example 3:
Create a procedure which adds the given three numbers using in and out
parameters
Sol. Steps
1. Write the sub Program
Ed subprocedure3
Create or replace procedure sum_numbers(n1 in number, n2 in
number, res out number)
is
Begin
res:=n1+n2;
End;
/
1. Next, Compile the above procedure to find errors in the procedure, with
the following statement
@ subprocedure3
1. Next, Write the main program
Declare
a number;
b number;
c number;
Begin
a:=&a;
b:=&b;
sum_numbers(a,b,c);
dbms_output.put_line('sum of three numbers is '||c);
End;
/
1. Next, Run the above main procedure with the following statement
@mainprogram3
output :
SQL> @ mainprogram3
Enter value for a: 10
old 6: a:=&a;
new 6: a:=10;
Enter value for b: 20
old 7: b:=&b;
new 7: b:=20;
sum of three numbers is30
PL/SQL procedure successfully completed.
Example 4:
Create a procedure which Updates the sal with the increment value that you
give according to the given emp number
Sol. Steps
1. Write the sub Program
Ed subprocedure4
Create or replace procedure incr(eno employee.empno%type,s
out number, i number)
Is
Begin
Update employee set sal=sal+i where empno=eno;
Dbms_output.put_line('Record Updated----');
End;
/
1. Next, Compile the above procedure to find errors in the procedure, with
the following statement
@ subprocedure4
1. Next, Write the main program
Declare
e number:=&empno;
Incr_value number:=&increment;
s employee.sal%type;
Begin
Select sal into s from employee where empno=e;
Incr(e,s,incr_value);
End;
/
1. Next, Run the above main procedure with the following statement
@mainprogram4
output :
SQL> @ mainprogram4
Enter value for empno: 7369
old 2: e number:=&empno;
new 2: e number:=7369;
Enter value for increment: 48
old 3: incr_value number:=&increment;
new 3: incr_value number:=48;
Record Updated----
PL/SQL procedure successfully completed
Trigger
Trigger is a database object ie used to execute an action basing on an even.
Triggers are event-based programs, which are executed when an event occurs or
raises or fires
Types of Triggers
Trigger Type is defined by the type of triggering transaction and by the level at
which the trigger is executed
Triggers Are Of Two Types
1. Row Level Triggers
2. Statement Level Triggers
Row Level Triggers
A row trigger is fired each time a row in the table is affected by the triggering
statement. For example, if an UPDATE statement updates multiple rows of a
table, a row trigger is fired once for each row affected by the update statement. If
the triggering statement affects no rows, the trigger is not executed at all. Row
triggers should be used when some processing is required whenever a triggering
statement affects a single row in a table.
Row level triggers are created using the "For Each Row" Clause in the Create
Trigger Command
Statement triggers
A statement trigger is fried once on behalf of the triggering statement,
independent of the number of rows the triggering statement affects (even if not
rows are affected) statement triggers should be used when a triggering statement
affects rows in a table but the processing required is completely independent of
the number of rows affected
Statement level triggers are the default type of trigger created via Create Trigger
Command
Syntax:
create or replace trigger <trigger_name>
{before/after/instead of}
{insert/update/delete}
[ of <column name> on <table name> ]
[ for each row [when <condition>] ]
Declare
variables declarations
-----------------
begin
Executable statements
-------------
Exception
Exception statements
---------------
end;
/
Syntax Explanation :
or replace : Recreates the trigger if it already exists. this option can be used to
change the definition of an existing trigger without requiring the user to drop the
trigger first
Trigger Name : is the name of the trigger to be created
Before : Indicates that oracle fires the trigger before executing the trigger
statement
After : Indicates that oracle fires the trigger After executing the trigger statement
Insert : Indicates that oracle fires the trigger whenever an INSERT statement adds
a row to a table.
Delete : Indicates that oracle fires the trigger whenever a DELETE statement
removes a row from the table.
Update : Indicates that oracle fires the trigger whenever an UPDATE statement
changes a value in one of the columns specified in the OF clause. if the OF clause
is omitted, the oracle fires the trigger whenever an UPDATE statement changes a
value in any column of the table.
for Each Row : Designates the trigger to be a row trigger. the oracle engine fires a
row trigger once for each row that is affected by the triggering statement and
meets the optional trigger constraint defined in the When clause. if this clause is
omitted the trigger is a statement trigger.
When : specifies the trigger restriction. the trigger restriction contains a SQL
condition that must be satisfied for the oracle to fire the trigger.
Basing on the above 2 types of triggers, they are further classified into 3 types
1. DML Triggers
2. DDL Triggers and
3. Instead of Triggers
1. DML Triggers
These triggers are executed before or after. we apply any dml operations on a
table.
When we create a table. the trigger definition is stored in the database, which is
identified with the trigger name. the code in the trigger is processed when we
apply any command on the database or table
Examples :
Steps for Creating a Trigger
1. First Create a trigger, next set the server on with the following statement (set
Serveroutput on)
2. Run that Trigger with the following statement
@ <trigger name>
3. perform some action (ie either insert or update or delete etc)
Statement Level Triggers
1. Create A Trigger, Which Displays A Message When Ever You Insert A New Row
In To Sample1 Table
Create or replace trigger instrig1 before insert on sample1
Begin
dbms_output.put_line('one record inserted successfully.....');
End;
/
2. Create A Trigger, Which Displays A Message When Ever You Update An
Existing Row In The Table Sample1
Create or replace trigger updtrig1 before update on sample1
Begin
dbms_output.put_line('one record updated successfully.....');
End;
/
1. Create A Trigger, Which Displays A Message When Ever You Delete A Row
From The Table Sample1
Create or replace trigger deltrig1 before delete on sample1
Begin
dbms_output.put_line('record(s) deleted successfully.....');
End;
/
Row Level Triggers
1. Create A Trigger, Which Displays A Message When Ever You Insert A New Row
Into A Table Sample1
Create or replace trigger instrig2 before insert on sample1
for each row
Begin
dbms_output.put_line(:new.sno||' record inserted successfully.....');
End;
/
1. Create a trigger, which displays a message when ever you update a row in
the table sample1
Create or replace trigger updtrig2 before update on sample1 for each row
Begin
dbms_output.put_line(:old.sno||' record updated to '||:new.sno);
End;
/
1. Create A Trigger, Which Displays A Message When Ever You Delete A Row
From The Table Sample1
Create or replace trigger deltrig2 after delete on sample1 for each row
Begin
dbms_output.put_line(:old.sno||' record deleted successfully.....');
End;
/
DDL TRIGGERS
1. Create A Trigger, Which Displays An Error Message When Ever You Create
a New Table which starts with Letter A
Create or replace trigger ctrig1 before create on scott.schema
Begin
if dictionary_obj_name like 'a%' then
raise_application_error(-20001,'object name can not start with a');
End if;
End;
/
1. Create A Trigger, Which Displays An Error Message When Ever You try to
drop any Table
Create or replace trigger prevent_drop after drop on scott.schema
Begin
if ora_dict_obj_type='table' then
raise_application_error(-20001,'object can not be dropped');
End if;
End;
/
1. Create A Trigger, Which Displays An Error Message When Ever You try to
Alter any Table
create or replace trigger prevent_alter before alter on scott.schema
begin
if ora_dict_obj_type='TABLE' then
Raise_Application_Error(-20001,'Object Can not be altered');
end if;
end;
/
INSTEAD OF TRIGGER
Create a trigger, which inserts the given values in to the relevant table through a
Composite view
Create or replace trigger instrig instead of
Insert on empdept for each row
Begin
if :new.deptno is not null and :new.dname is not null then
insert into department(deptno,dname) values (:new.deptno,:new.dname);
end if;
if :new.empno is not null and :new.ename is not null then
insert into employee(empno,ename) values (:new.empno,:new.ename);
end if;
End;
/
Materialized view

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 view and the
Query rewrite feature is added from ORACLE 8i.
A materialized view log is a schema object that records changes to a master
table's data so that a materialized view defined on the master table can be
refreshed incrementally.
If you delete any record from your Materialized view it is goanna impact
your Source table once it is refreshed.
Examples to the Simple Materialized views is given below .
Eg 1 :Create materialized_view MV refresh as select * from emp;
Execute dbms_mview.refresh(MV);
Refresh Complete : To perform a complete refresh of a materialized view, the
server that manages the materialized view executes the materialized view's
defining query, which essentially recreates the materialized view. To refresh the
materialized view, the result set of the query replaces the existing materialized
view data. Oracle can perform a complete refresh for any materialized view.
Depending on the amount of data that satisfies the defining query, a complete
refresh can take a substantially longer amount of time to perform than a fast
refresh.
Create Materialized_view MV Refresh complete as select * from emp;
execute DBMS_mview.refresh(List=>MV,Method=>c);
Refresh Fast :To perform a fast refresh, the master that manages the materialized
view first identifies the changes that occurred in the master since the most recent
refresh of the materialized view and then applies these changes to the
materialized view. Fast refreshes are more efficient than complete refreshes
when there are few changes to the master because the participating server and
network replicate a smaller amount of data.
Create Materialized_view MV Refresh fast as select * from emp;
execute DBMS_mview.refresh(list=>MV,Method=>F);
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;


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.


Creating Materialized Aggregate Views :

CREATE MATERIALIZED VIEW sales_mv BUILD IMMEDIATE REFRESH FAST ON
COMMIT AS SELECT t.calendar_year, p.prod_id, SUM(s.amount_sold) AS
sum_sales FROM times t, products p, sales s WHERE t.time_id = s.time_id AND
p.prod_id = s.prod_id GROUP BY t.calendar_year, p.prod_id;

Creating Materialized Join Views :

CREATE MATERIALIZED VIEW sales_by_month_by_state
TABLESPACE example
PARALLEL 4
BUILD IMMEDIATE
REFRESH COMPLETE
ENABLE QUERY REWRITE
AS SELECT t.calendar_month_desc, c.cust_state_province,
SUM(s.amount_sold) AS sum_sales
FROM times t, sales s, customers c
WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id
GROUP BY t.calendar_month_desc, c.cust_state_province;



Periodic Refresh of Materialized Views:

CREATE MATERIALIZED VIEW emp_data
PCTFREE 5 PCTUSED 60
TABLESPACE example
STORAGE (INITIAL 50K NEXT 50K)
REFRESH FAST NEXT sysdate + 7
AS SELECT * FROM employees;



Automatic Refresh Times for Materialized Views

CREATE MATERIALIZED VIEW all_customers
PCTFREE 5 PCTUSED 60
TABLESPACE example
STORAGE (INITIAL 50K NEXT 50K)
USING INDEX STORAGE (INITIAL 25K NEXT 25K)
REFRESH START WITH ROUND(SYSDATE + 1) + 11/24
NEXT NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 15/24
AS SELECT * FROM sh.customers@remote
UNION
SELECT * FROM sh.customers@local;

You might also like