Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Monday, December 12, 2022 2:13 PM

Materialized View:
• M.View is a Database Object.
• M.View is not a virtual table. It contains data
physically.
• It holds result of SELECT query.
• It precomputed result.
• It is mainly in Dataware Housing [DWH] to
maintain summarized data physically.
• If apply any changes to base table, it will not
be applied to m.view. That is why m.view must
be refreshed.

3 ways:
• ON DEMAND [Default] =>
○ Ex: SQL> EXEC dbms_mview.refresh('MV1');
• ON COMMIT =>
○ Ex: SQL> COMMIT;

• In a regular interval time:

Sales

weekly_Sales, monthly_sales, yearly_Sales

refreshed refreshed refreshed for


for every for every month every year
7 days

Example:

CREATE MATERIALIZED VIEW mv3


REFRESH
START WITH sysdate
NEXT sysdate+interval '1' day
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

-- m.view refreshed for every 24 hours [1 day]

SELECT * FROM mv3;


ORACLE2PM Page 1
SELECT * FROM mv3;

UPDATE emp SET sal=sal+1000;


COMMIT;

SELECT * FROM mv3;

CREATE MATERIALIZED VIEW mv3


REFRESH
START WITH sysdate
NEXT sysdate+interval '15' minute
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

--for every 15 minutes m.view will be refreshed

Refresh Types [refresh mechanism]:

'REFRESH' clause is used to specify refresh


type

Syntax:

REFRESH complete / fast / force

3 Types:

• COMPLETE [default]
• FAST
• FORCE

COMPLETE:
• In COMPLTE refresh,
○ truncates all records form m.view.
○ then runs SELECT query associated with
M.view.

ORACLE2PM Page 2
M.view.
○ This new result will be filled in m.view.

CREATE MATERIALIZED VIEW mv5


REFRESH complete
ON demand
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

EMP => base table


MV5
EMPNO ENAME DEPTNO SAL
DEPTNO SUM(SAL)
1001 10 10000
10 35000
1002 10 15000
20 40000
1003 20 12000
1004 20 8000
1005 10 10000
1006 20 20000

NOTE:
When large amounts of data is there, performance
will be degraded.

SELECT mview_name, last_refresh_type


FROM user_mviews
WHERE mview_name='MV5';

FAST:

EMP => base table MV6


EMPNO ENAME DEPTNO SAL DEPTNO SUM(SAL)
1001 10 10000 10 35000
1002 10 15000 20 40000
1003 20 12000
1004 20 8000

ORACLE2PM Page 3
1002 10 15000 20 40000
1003 20 12000
1004 20 8000
1005 10 10000
1006 20 20000

1005 10 10000
1006 20 20000

MVIEW LOG FILE

• In FAST refresh, The changes applied on base table will be recorded in


materialized view log file.
• These recent changes will be applied to m.view, when m.view is
refreshed. So performance will be improved.
• After applying changes to m.view, data in m.view log file will be
truncated.
• If m.view log file is not there, REFRESH will be failed.

CREATE MATERIALIZED VIEW mv7


REFRESH fast
ON DEMAND
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

ERROR: materialized view log file not created

ALTER TABLE emp ADD CONSTRAINT mc PRIMARY KEY(empno);

CREATE MATERIALIZED VIEW LOG ON emp


WITH rowid, sequence(deptno,sal)
INCLUDING NEW VALUES;

ROWID, deptno old, new values, sal


old values, new values

mview log file => emp

CREATE MATERIALIZED VIEW mv7


ORACLE2PM Page 4
CREATE MATERIALIZED VIEW mv7
REFRESH fast
ON DEMAND
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

FORCE:
• it gives first priority for FAST refresh. If m.view log file
is not there, it performs COMPLETE refresh.
• Here, refresh will not be failed.

CREATE MATERIALIZED VIEW mv8


REFRESH force
ON DEMAND
AS
SELECT deptno,sum(Sal) FROM emp
GROUP BY deptno;

3 refresh types:

COMPLETE • truncates all records from mv


• again runs SELECT query
• new result will be stored in m.view
FAST • recent changes will be recorded in m.view
log file.
• These recent changes will be applied to
m.view.
• if m.view log file is not there, it will be
failed.
FORCE • it gives first priority to FAST refresh. If
m.view log file not availabe, it performs
COMPLETE refresh

user_mviews:
• "user_mviews" is a system table.
• It maintains all m.views information.

DESC user_mviews;

ORACLE2PM Page 5
SELECT mview_name, query, last_refresh_type
FROm user_mviews;

Dropping materialized view:

Syntax:

DROP MATERIALIZED VIEW <mv_name>;

Ex:
DROP MATERIALIZED VIEW mv1;

Altering m.view:

ALTER MATERIALIZED VIEW mv1 REFRESH force;

ALTER MATERIALIZED VIEW mv1 Enable Query Rewrite;

Enable Query Rewrite:


With this,
even if user submitted normal query, it retrieves data from
m.view.

SELECT * FROM mv10;

JAVA DEVELOPER:

frequently wants to work with dept wise sum of salaries

to see execution plan:

SET AUTOTRACE ON EXPLAIN

SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno; -- from emp table
ORACLE2PM Page 6
GROUP BY deptno; -- from emp table

CREATE MATERIALIZED VIEW mv10


REFRESH FORCE
ON DEMAND ENABLE QUERY REWRITE
AS
SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno;

SELECT deptno,sum(Sal)
FROM emp
GROUP BY deptno; --retrieves from m.view mv10

ORACLE2PM Page 7
Indexes
Tuesday, December 13, 2022 2:13 PM

ORACLE

INDEX

Sno Chapter Name Pg No


Frequent operation is retrieving
data based on sal: 1 DDL commands 10
2 DML 20
20 emp records 3 Built-In Functions 50
4 Joins 70
WHERE sal>3000 5 … .
WHERE sal<5000
WHERE sal<2500
WHERE sal>=5000

To improve the performance of


retrieval , we create index on
"SAL" column

Indexes:
• INDEX is a Database Object.
• INDEX is used to improve the performance of
data retrieval.
• Example: To refer JOINS topic in ORACLE book,
we use INDEX. With the help of INDEX , we can
refer the chapter quickly.
• Index will be created on a column which is
frequently used in WHERE clause.
• If INDEX is created, performance of data
retrieval will be improved.

Syntax to create Index:

CREATE INDEX <index_name>


ON <table_name>(<column/columns>);

When we submit a query to ORACLE, it performs


any of 2 scans:
• Table Scan [Slower]
• Index Scan [Faster]

SET AUTOTRACE ON EXPLAIN

SELECT empno,ename,sal
FROM emp
WHERE sal>3000; --Table Scan => slower

CREATE INDEX i1 ON emp(sal);


ORACLE2PM Page 8
CREATE INDEX i1 ON emp(sal);

SELECT empno,ename,sal
FROM emp
WHERE sal>3000; --Index Scan => faster

WHERE sal>3000 => Table Scan


Sal
----------
4000 no of comparisons = no of records
5000
1800
2500 12 comparisons
4500
3500
3300
4500
2500
1000
1200
1300

WHERE sal>3000
INDEX ON SAL => INDEX SCAN

When we create the INDEX, implicitly


one Binary Tree will be created.

Tree => is a collection of nodes.

Sal
sal>3000 => place it at right side
----------
sa<=3000 => place it at left side
4000
5000
1800 3000
2500
4500
3500 2000 4000
3300
4500
2500
1000 1000 * 2500 ** 3300 * 4500 **
1200 1200 * 3500 * 5000 *
1300 1300 * 4000 *
1800 *

Leaf Node holds values & row ids

ORACLE2PM Page 9
Types of Indexes:

2 Types:
• B-Tree Index / Normal Index
• Bitmap Index

• B-Tree Index / Normal Index:


If Binary tree is created for the index then it is
called "B-Tree Index".

It has sub types:


○ Simple Index
○ Composite Index
○ Unique Index
○ Function-Based Index

• Bitmap Index:
If Binary Tree is not created for the index then it
is called "Bitmap Index".

Simple Index:
If index is created on one column then it is called
"Simple Index".

Ex:
CREATE INDEX i1 ON emp(Sal);

Composite Index:
If index is created on multiple columns then it is called
"Composite Index".

Frequent operation:
deptno and job

deptno=10 job='MANAGER'
deptno=20 job='CLERK'
deptno=30 job='SALESMAN'

Example:
CREATE INDEX i2 ON emp(deptno,job);

According to first column deptno B-Tree will be


created.

SELECT * FROM emp


WHERE deptno=20 AND job='CLERK'; -- Index Scan

SELECT * FROM emp


WHERE deptno=20; --Index Scan

ORACLE2PM Page 10
SELECT * FROM emp
WHERE job='CLERK'; -- Table Scan / Index Scan

Unique Index:
This index will be created on a column which has
unique values.

Syntax:

CREATE UNIQUE INDEX <index_name>


ON <table_name>(<column_name>);

PRIMARY KEY = UNIQUE + NOT NULL + INDEX

NOTE:
We have no need to create index on Primary Key
column.
When we create a table with Primary Key,
implicitly one INDEX will be created on Primary
Key Column.

user_tables
user_views
user_mviews
user_sequences

user_indexes

CREATE TABLE t1
(
f1 NUMBER(4) CONSTRAINT zz PRIMARY KEY,
f2 VARCHAR2(10)
);

We can maintain unique values using 3 concepts:


• Primary Key
• Unique
• Unique Index

Example:
CREATE UNIQUE INDEX i3 ON dept(dname);

Function-Based Index:

ORACLE2PM Page 11
Function-Based Index:
If index is created based on function or expression then it is called
"Function-Based Index".

Example:
Frequent operation is retrieving data based on ename
WHERE ename='SMITH'
WHERE ename IN('ALLEN','BLAKE')

SELECT * FROM emp


WHERE ename='SMITH'; --Table Scan

CREATE INDEX i4 ON emp(ename);

SELECT * FROM emp


WHERE ename='SMITH'; --Index Scan

When we don't know exact case of ename we write as following:

SELECT * FROM emp


WHERE lower(ename) = 'smith'; --Table Scan

CREATE INDEX i5 ON emp(lower(ename)); -- Function based Index

SELECT * FROM emp


WHERE lower(ename) = 'smith'; --Index Scan

Frequent operation is retrieving data based on


annual salary.

WHERE sal*12>30000
WHERE sal*12<50000

SELECT empno,ename,sal,sal*12 as annual_Sal


FROM emp
WHERE sal*12>30000; --Table Scan

CREATE INDEX i6 ON emp(sal*12); --Function-Based Index

SELECT empno,ename,sal,sal*12 as annual_Sal


FROM emp
WHERE sal*12>30000; --Index Scan

B-Tree Index:
When we create the index, If B-Tree is created then it

ORACLE2PM Page 12
• When we create the index, If B-Tree is created then it
is called "B-Tree Index".
• It stores values & Row IDs
• B-Tree Index will be created on High Cardinality
Columns.
• Ex: ename, sal, empno

Bitmap Index:
• It stores bits [0s & 1s]
• Every bit will be associated [mapped] with Row ID.
• In this, bits will be converted row ids, goes to those
records & picks the data.
• Bitmap Index will be created on Low Cardinality
Columns.

Low cardinality Column:


• A column which has less distinct values is
called "Low Cardinality Column"
• Ex: Gender, Deptno

GENDER DEPTNO
--------------- -------------
M 10
M M 30 10
F F 30 20
M 20 30
F 20
F 10
F 10
M 20
F 30

High Cardinality Column:


A column which has more distinct values is called
"High Cardinality Column".

Ex: EMPNO, ENAME

EMPNO ENAME
-------------- ---------
1001 SRINU
1002 ARUN
1003 20 distinct values VIJAY
1004 SRINU
. .
. .
1020

Syntax to create Bitmap Index:

CREATE BITMAP INDEX <index_name>


ON <table_name>(<column>);

ORACLE2PM Page 13
CREATE BITMAP INDEX <index_name>
ON <table_name>(<column>);

CREATE TABLE employee


(
empno NUMBER(4),
ename VARCHAR2(10),
GENDER CHAR(1)
);

INSERT INTO employee VALUES(1,'A','M');


INSERT INTO employee VALUES(2,'B','M');
INSERT INTO employee VALUES(3,'C','F');
INSERT INTO employee VALUES(4,'D','M');
INSERT INTO employee VALUES(5,'E','F');
INSERT INTO employee VALUES(6,'F','F');
COMMIT;

COLUMN gender FORMAT A6

SELECT * FROM employee;

frequent operation is retrieving data based on GENDER

WHERE gender='M'
WHERE gender='F'

SELECT * FROM employee


WHERE gender='M'; --Table Scan

CREATE BITMAP INDEX bi1


ON employee(gender); --Bitmap Index

SELECT * FROM employee


WHERE gender='M'; --Index Scan

WHERE
GENDER gender='M'
--------------- BI1 => Bitmap Index
M
M M F
F 1 0
M 1 0
F 0 1
F
1 0
F
0 1
M
F 0 1
0 1

ORACLE2PM Page 14
0 1
M
F 0 1
0 1
1 0
0 1

B-Tree Index Bitmap Index

• in this, B-Tree will be • In this, B-Tree will not be


created created

• It is created on high cardinality • It is created on low cardinality


columns columns
Ex: ename, sal, empno Ex: gender, deptno

• It stores values & Row IDs • It stores bits [0s & 1s]

USER_INDEXES:
• It is a system table / built-in table
• It maintains all Indexes Information

DESC user_indexes;

SELECT index_name, index_type


FROM user_indexes;

Dropping Index:

Syntax:
DROP INDEX <index_name>;

Ex:
DROP INDEX i1;

If we drop a base table does it drop the views


created on base table?
NO. But, those views will not work

If we drop a base table does it drop the indexes


created on base table?
ORACLE2PM Page 15
created on base table?
YES.

deptno 10 20 30
------------ 1 0 0
10 0 0 1
30
30
20
10
20

ORACLE2PM Page 16
Synonyms
Thursday, December 15, 2022 2:20 PM

SYNONYM:
• SYNONYM is a DB Object.
SELECT ename as A, sal as B
• It is used to give alias name [alternative name] for the
FROM emp;
DB objects like tables.
• Table alias is temporary. Its scope will be limited to
A B
that query only. To give permanent alias name we use
------- -----------
SYNONYM.
• Table alias is Temporary. SYNONYM is permanent.
Column alias is temporary

Advantages:
SELECT e.ename,d.dname
• It makes table name short.
FROM emp e, dept d …
○ Ex: EMPLOYEE_SALARY_DETAILS => e
…….;

• It can be used to avoid of writing schema name.


e, d are table alias
○ Ex:
c##oracle2pm
Table alias is temporary
emp
GRANT all on emp

c##userA
SELECT * FROM c##oracle2pm.emp

creates a synonym
c##oracle2pm.emp => e

Types of Synonyms:

2 Types:

• Private Synonym
• Public Synonym

Private Synonym:
• It is created by the user

Syntax to define private synonym:

CREATE SYNONYM <synonym_name>


FOR <db_object>;

Example:

Log in as DBA:
username: system
password: nareshit

ORACLE2PM Page 17
GRANT CREATE SYNONYM TO c##oracle2pm;

Log in as c##oracle2pm:

CREATE SYNONYM e FOR emp;

SELECT * FROM e;

--display emp table data


--e is synonym [alias name of emp]

Public Synonym:
• It is created by DBA

Syntax to create public synonym:

CREATE PUBLIC SYNONYM <synonym_name>


FOR <DB_Object>;

c##oracle2pm => owner


emp

c##userA, c##userB, c##userC

Log in as DBA:

CREATE PUBLIC SYNONYM e FOR c##oracle2pm.emp;

GRANT select ON e TO c##userA, c##userB, c##userC;

log in as c##userA:

SELECT * FROM e;

log in as c##userB:

SELECT * FROM e;

log in as c##userC:

SELECT * FROM e;

ORACLE2PM Page 18
Dropping Private Synonym:

Syntax:

DROP SYNONYM <synonym_name>;

Ex:
DROP SYNONYM e;

Dropping public synonym:

Syntax:

DROP PUBLIC SYNONYM <synonym_name>;

Ex:
DROP public synonym e;

user_synonyms:
• It is a system table / built-in table
• It maintains all synonyms information.

DESC user_synonyms;

SELECT synonym_name,table_name
FROM user_synonyms;

ORACLE
SQL Database
PL/SQL Tables
Rows & COlumns

SQL:
• Non-Procedural Language.
• Non-Procedural means, we will not write any set
of statements or programs.

ORACLE2PM Page 19
of statements or programs.
• Just we write queries
• Query => is a request i.e. sent to DB SERVER

5 Sub Languages:

DDL CREATE
ALTER
DROP
FLASHBACK
PURGE
TRUNCATE
RENAME
DRL / DQL SELECT
DML INSERT => emp joined
UPDATE => emp promoted
DELETE => emp resigned

INSERT ALL
MERGE
DCL GRANT
REVOKE
TCL COMMIT [save]
ROLLBACK [undo all]
SAVEPOINT

Built-In Functions:

String Functions lower() upper() Lpad()


Aggregate Max() Min() Count() Sum()
Conversion to_Char() to_date()
Date Add_Months()
last_day()
next_day()
months_between()
sysdate
systimestamp
Number Trunc()
Round()
Ceil()
Floor()
Mod()
Miscellaneous Rank()
Dense_Rank()

NVL()
NVL2()

Clauses in SELECT:

ORACLE2PM Page 20
FROM FROM emp
WHERE WHERE sal>3000

GROUP BY GROUP BY deptno

HAVING HAVING count(*)>5

SELECT SELECT ename,sal


DISTINCT DISTINCT job
ORDER BY ORDER BY sal DESC

Sub Queries:
writing query in another query

Types:
Single Row Sub Query Sub query returns 1 row
Multi Row Sub query returns multiple
rows
Correlated Outer query passes value to
inner query
Inline View We write Sub Query in FROM
clause
Scalar We write sub query in
SELECT clause

Joins:

Goal: used to retrieve data from multiple tables

Types:

Equi based on equality condition


Non-Equi based on other than equality condn
Self a table will be joined to itself
Cross each record in table will be joined every
record in another
Left matched + unmatched from left table
Outer
Right matched + unmatched from right rable
Outer
Full Outer matched + unmatched from left & right

SET OPERATORS:

UNION
UNION ALL
INTERSECT

ORACLE2PM Page 21
INTERSECT
MINUS

VIEWS:
View => virtual table
no physical data
holds SELECT query

Advantages:
• Security
• simplifies queries

Disadvantage:
• Less performance

Sequences:
generate sequential integers

cid
-------- NEXTVAL
123456 CURRVAL
123457
123458

Materialized View:
• it is not virtual table
• it holds data physically
• it is used to maintain summary of detailed
tables physically
• it must be refreshed

Advantages:
• It improves the performance
• can maintain local copy of remote database

Indexes:
Index is used to improve the performance of
data retrieval
Index will be created on column which is
frequently used in WHERE clause

B-Tree Index => values & row ids


Simple Index
Composite Index
Unique Index
Function-Based

ORACLE2PM Page 22
Bitmap Index => stores 0s and 1s

Synonym:
to give permanent alias name for DB object
use SYNONYM

ORACLE2PM Page 23

You might also like