Вы находитесь на странице: 1из 134

Oracle 11g

Data :-

Data are facts.

Information :-

processed or organized data is called information.

Database :-

A Database is Collection of interrelated data

Databases are created to store details about


day-to-day events in the form of transactions.

DBs are 2 types

OLTP (ONLINE TRANSACTION PROCESSING)


OLAP (ONLINE ANALYTICAL PROCESSING)

OLTP db is created to run business


OLAP db is created to analyze the business

DBMS :-

DBMS stands for Database Mgmt System.

DBMS is a software system that allows users to create and access data in a database.

The primary purpose of the DBMS is to manage and serve user request. The actual
database users are always unaware of the following.

Where the data is physically located on the storage media. In a multi user
system, who else is accessing such data.

A DBMS

Reduces Redundency
Improves Data consistency
Provides Security at different levels
Ensures Data integrity
Provides transaction support
Provides Concurrency control
Provides Data Recovery methods

-1- Naresh i Technologies


Oracle 11g

Metadata :-

the DBMS provides a Data Dictionary function. The Data Dictionary can be regarded as
a system database rather than user database.

Data Dictionary contains “Data about the Data” called Metadata , that is definitions of
other objects instead of just raw data.

RDBMS :-

RDBMS is based on relational data model.


Relational Data Model is introduced by E.F.Codd.
E.F.CODD had come up with 12 rules are called CODD rules.
A DBMS which satisfies all CODD rules is called perfect RDBMS.
According to E.F.CODD in RDBMS data must be organized in the form of 2D tables as
follows.

EMPNO ENAME SAL

1 AJAY 5000

2 RAJU 6000

3 SATISH 4000

A table is a combination of rows and columns

Columns are also called attributes or fields.

Rows are also called records or tuples.

Intersection of row and column must be atomic (single) .

In tables records are uniquely identified by primary key.

Tables are related using foreign keys.

-2- Naresh i Technologies


Oracle 11g

ER MODEL :-

ENTITY RELATIONSHIP MODEL .

It is a graphical representation of organization data.

In ER MODEL data represented in graphical symbols such as rectangle , ellipse etc.

The basic elements of ER model are

ENTITIES
ENTITY SETS
ATTRIBUTES
RELATIONSHIPS

ENTITY :-

Entity is an object
Example :- employee ,customer, bank a/c etc.

ENTITY SET :-
Collection of entities that share common characterstics.
Example :- EMP

ATTRIBUTES :-
Property of an entity is called attribute.
Example :- empno, ename,job,sal

RELATIONSHIP :-
Relationship is an association between entities of entity sets.

-3- Naresh i Technologies


Oracle 11g

Types of relationships :-
1:1
1:M
M:N

ER MODEL RELATIONAL MODEL


Used in DESIGN phase used in DEVELOPMENT
Phase
ENTITY SETS TABLES
ATTRIBUTES FIELDS
RELATIONSHIP FOREIGN KEY.

VERSIONS OF ORACLE 10G :-

VERSION FEATURES

Oracle 4 read consistency.

Oracle 5 client/server arch.

Oracle 6 financial applns built on


Oracle.

Oracle 7 varchar2 datatype


Procedures
Functions
Triggers

Oracle 8 LOB
User defined datatypes
Table partitioning

Oracle 8i SQLJ ,XML

Oracle 9i multitable insert

-4- Naresh i Technologies


Oracle 11g

MERGE command
ANSI joins

Oracle 10g FLASHBACK


REGULAR EXPRESSIONS
DATA PUMP

Oracle 11g READ ONLY TABLES


VIRTUAL COLUMNS
FOLLOWS CLAUSE
COMPOUND TRIGGERS

SQL

SQL stands for STRUCTURED QUERY LANGUAGE.

It is a language used to communicate with ORACLE SERVER.

User communicate with ORACLE SERVE by submitting Queries.

This language was originally developed by IBM in 1970s.

Initial name of the language was SEQUEL later it is renamed to SQL.

SQL is common for all RDBMS.

Sublanguages of SQL :-

DDL :-

DATA DEFINITION LANGUAGE.

Different DDL commands to define data :-

CREATE
ALTER
DROP
TRUNCATE
RENAME

DML :-

-5- Naresh i Technologies


Oracle 11g

DATA MANIPULATION LANGUAGE

Different DML commands to manipulate data :-

INSERT
UPDATE
DELETE
INSERT ALL
MERGE

DRL :-

DATA RETRIEVAL LANGUAGE

DRL command to retrieve data from db :-

SELECT

TCL :-

TRANSACTION CONTROL LANGUAGE

Different TCL commands to control TRANSACTIONS :-

COMMIT
ROLLBACK
SAVEPOINT

DCL :-

DATA CONTROL LANGUAGE.

Different DCL commands to control DATA :-

GRANT
REVOKE

SQL*PLUS :-

-6- Naresh i Technologies


Oracle 11g

SQL*PLUS is tool or environment from ORACLE CORP, used to execute all the
commands of SQL and SQL*PLUS commands.

SQL SQL*PLUS

Language environment

Commands should terminate ; not required to


With ; terminate command

Commands cannot be commands can be


Abbrivated abbrivated.

Last SQL command is last command is not


Resided in buffer resided in buffer.

Both commands are not case sensitive.

CONNECTING TO ORACLE SERVER :-

To connect to ORACLE SERVER user has to submit

USERNAME :- Name of the user

PASSWORD :- password

HOST STRING :- DB name or Instance name .

Datatypes in Oracle :-

A datatypes specifies type of the data allowed in a column.


Oracle supports following datatypes.

String Datatypes :-

Char Datatype :-

Allows ANSI characters upto 2000 chars


It is a Fixed Length character datatype.
If the entered data is less than the original size, then bytes are filled with blank spaces.

-7- Naresh i Technologies


Oracle 11g

Varchar2 Datatype :-

Allows ANSI characters upto 4000 chars.


It is a variable length character datatype.
It occupies no of bytes equal to the no of chars entered.

Nchar/Nvarchar2 :-

Both Nchar and Nvarchar2 is based on UNICODE.


Allows characters upto 4000 chars
Nchar is fixed length.Nvarchar2 is variable length.

Long Datatype :-

Allows character data upto 2GB.


Only one LONG column allowed per table.
LONG datatype is deprecated.

Number Datatype :-

Number(P,[S])
Allows Numbers.
P is the precision i.e. total no of digits allowed
S is the scale i.e. no of digits allowed after decimal.
Precision can be between 1 to 38.
Scale can be between -84 to 127.

Date & Time Datatypes :-

Allows Date and Time.


Default Date format in ORACLE is DD-MON-YY.
ORACLE allows any Date between
JAN 1 4712 BC TO DEC 31 9999
A Date field occupies 7 bytes of memory.

ORACLE stores

-8- Naresh i Technologies


Oracle 11g

DAY
MONTH
YEAR
HOUR
MINUTE
SECOND

TIMESTAMP DATATYPE:-

TIMESTAMP[(fractional-second)]

Allows Date , Time and also Fractional seconds.


Fractional seconds can be between 0 to 9 default is 6.
Using this we can also specify TIMEZONEs.

INTERVAL YEAR TO MONTH Datatype:-

It is used to store and manipulate the intervals of years and months. The syntax is as
follows:

INTERVAL YEAR[(precision)] TO MONTH

Here precision specifies the number of digits in the years field. The valid values of
precision are between 0 to 4, and the default value is 2.

INTERVAL DAY TO SECOND Datatype:-

It is used to store and manipulate intervals of days, hours, minutes, and seconds. The
syntax is:

INTERVAL DAY [(leading_precision)] TO

SECOND [(fractional_seconds_precision)]

The valid values of precision are in the range 0 to 9. The defaults are 2 and 6,
respectively.

-9- Naresh i Technologies


Oracle 11g

RAW :-

stores binary information upto 2000 bytes


used to store pictures,images and signatures.

LONG RAW :-

Similar to RAW datatype but supports upto 2GB.


When LONG RAW is used we should not specify size.

LOB DATATYPES :-

Allows LARGE OBJECTS


Different LOB types provided by ORACLE
BFILE
BLOB
CLOB

BFILE/BLOB Datatype :-

Both BFILE and BLOB datatypes allows binary data upto 4GB.
If datatype is BFILE then object stored externally ORACLE stores locator.
If datatype is BLOB then object stored internally in ORACLE database.

CLOB Datatype :-
Allows Character data or character objects upto 4GB.

BINARY_FLOAT :-
This Datatype introduced in Oracle 10g.
BINARY_FLOAT is a 32-bit single precision floating point number datatype.
BINARY_FLOAT requires 5 bytes including a length byte.

BINARY_DOUBLE :-
This Datatype also introduced in Oracle 10g.
BINARY_DOUBLE is a 64-bit double precision floating point number datatype.

-10- Naresh i Technologies


Oracle 11g

BINARY_DOUBLE requires 9 bytes including a length byte.

OPERATORS IN ORACLE :-
Operators in ORACLE categorized into following categories

ARTHMETIC OPERATORS :-
+
-
*
/
Operator precedence:-

Operators * , / having higher precedence than operators + , -

Operators of the same priority are evaluated from left to right.

Use parenthesis to control the precedence.

RELATIONAL OPERATORS :-
>
<
>=
<=
=
<>

LOGICAL OPERATORS :-
AND
OR
NOT
SPECIAL OPERATORS :-
||
BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS

-11- Naresh i Technologies


Oracle 11g

PIVOT
SET OPERATORS :-
UNION
UNION ALL
INTERSECT
MINUS

Creating table :-
Syntax:-

Create Table <Table Name>


(colname datatype(size) ,
Colname datatype(size) ,
--------------------)
Example:-

Create Table Emp


(Empno Number(4),
Ename Varchar2(20),
Job Varchar(10),
Hiredate Timestamp,
Sal Number(6,2),
Comm Number(6,2),
Deptno Number(2));

Inserting Data into a Table:-

INSERT command is used to insert record into a table.

Syntax:-

INSERT INTO <table name> VALUES(list of values)

Strings and Dates must be enclosed in single quotes.

Example :-

INSERT INTO EMP

VALUES(1000,’BLAKE’,’MANAGER’,’10-JAN-10’,5000,500,10) ;

-12- Naresh i Technologies


Oracle 11g

The order of the values should be equal to the order of the columns declared in the
table.

To insert values in different order we need to specify the order explicitly.

INSERT INTO EMP(ENAME,JOB,SAL,COMM,HIREDATE,EMPNO,DEPTNO)

VALUES(‘ADAMS’,’CLERK’,3000,200,’11-JAN-10’,1001,10);

Inserting NULL values :-

Null means a value Which is Absent


Which is Unknown
Which is Not Applicable

Neither it is equal to 0 nor it is equal to space

NULL values can be inserted in two ways.


EXPLICIT
IMPLICIT

Inserting NULL values EXPLICITLY:-

to insert Null values into Numeric cols user NULL keyword.


To insert Null values into character & date cols use ‘’ .

Example :-

INSERT INTO EMP


VALUES(1002,’JAMES’,’’,5000,NULL,10);

Inserting NULL values IMPLICITLY :-

Example :-

INSERT INTO EMP(EMPNO,ENAME,SAL,DEPTNO)


VALUES(1005,’SMITH’,2000,10);

-13- Naresh i Technologies


Oracle 11g

Inserting MULTIPLE records :-

One INSERT command can be executed with different values by using substitution
variables.

Substitution variables can be declared by using

Single ampersand ( &)


Double ampersand (&&)

These variables stores data temporarily


Using Single ampersand :-

These variables are prefixed with &

Values assigned to these variables exists upto the execution of INSERT command ,
once command execution is completed the values are erased.

Example :-

INSERT INTO EMP

VALUES(&EMPNO,’&ENAME’,’&JOB’,

’&HIREDATE’,&SAL,&COMM,&DEPTNO);

Using Double Ampersand :-

These variables are prefixed with &&.


Values assigned to these variables not erased after the execution of INSERT command
, exists upto the end of the session.

Example :-

INSERT INTO EMP VALUES(&EMPNO,’&ENAME’,’&&JOB’,’&&HIREDATE’,


&&SAL,&&COMM,&&DEPTNO);

Data Retrieval Languages(DRL):-

SELECT Statement used to retrieve data from one or more tables, views.

SELECT statement is used to do following operations .

SELECT :- selecting particular rows from a table.

-14- Naresh i Technologies


Oracle 11g

PROJECT :- selecting particular columns from a table.

JOIN :- getting data from more than one table.

Syntax:-

SELECT <collist> FROM <tabname>

SELECT →identifies columns

FROM→ identifies table

Retrieving Data from all Columns:-

SELECT * FROM Emp;

‘*’ is a projection operator.

Retrieving Data from Specific Columns:-

SELECT empno, ename, job, sal, FROM Emp;

Date and Character data aligned to LEFT

Numeric data aligned to RIGHT

DECLARING ALIAS :-

An Alias is an another name or alternative name.

Aliases in Oracle are of two types.

Column Alias

Table Alias

Column Alias :-

Alias declared for column is called column alias.

Syntax :-

COLNAME / EXPR [AS] ALIAS

If alias contains spaces or special characters then alias must be enclosed in “ “

Column alias should not be used in SELECT list.

-15- Naresh i Technologies


Oracle 11g

The scope of the alias is upto that query.

Example :-

Display ename,sal,hra,da,tax,totsal ?

SELECT ENAME,SAL,SAL*0.3 AS HRA,SAL*0.2 AS DA,


SAL*0.1 AS TAX ,
SAL+(SAL*0.3)+(SAL*0.2)-(SAL*0.1) AS TOTSAL
FROM EMP;

Concatenation Operator:-

This operator concatenates two strings

represented by two vertical bars(||).

Example :-

SELECT ENAME||’ WORKING AS ‘||JOB FROM EMP;

SELECT ENAME||’ JOINED ON ‘||HIREDATE FROM EMP;

LITERALS IN ORACLE:-

A Literal is a Constant

Typesof Literals :-

String

Number

Date

String constant and Date constants must be enclosed in ‘ ‘.

Literal increases the readability of the output.

SELECT ENAME || ‘ EARNS ‘|| SAL*12 ||’ PER YEAR’


FROM EMP;

CLAUSES IN ORACLE :-

Different clauses in ORACLE 11G

-16- Naresh i Technologies


Oracle 11g

WHERE
ORDER BY
DISTINCT
GROUP BY
HAVING
ON
USING
START WITH
CONNECT BY
WITH
RETURNING
FOLLOWS
MODEL

Data Filtering using WHERE clause :-

WHERE clause is used to get particular records from table based on a condition.

WHERE clause always associated with one or more conditions.

Records that satisfies the WHERE cond are selected and remaining records are
discarded.

Conditions are combined with AND or OR operators.

Syntax:-

SELECT <COLLIST> FROM <TABNAME>


WHERE <COND> [ AND/OR <COND>----------]

CONDITION :-

COLNAME OPERATOR VALUE

Display employee record whose empno=7844 ?

SELECT * FROM EMP WHERE EMPNO=7844 ;

Display employee records whose job=’CLERK’ ?

-17- Naresh i Technologies


Oracle 11g

SELECT * FROM EMP WHERE JOB=’CLERK’ ;

Display employee records working for 10 dept and working as CLERK ?

SELECT * FROM EMP WHERE DEPTNO=10 AND JOB=’CLERK’;

Display employee records working as CLERK OR MANAGER ?

SELECT * FROM EMP WHERE JOB=’CLERK’ OR JOB=’MANAGER’

Display employee records earning between 2000 and 5000 ?

SELECT * FROM EMP WHERE SAL>=2000 AND SAL<=5000;

BETWEEN operator :-

BETWEEN operator is used to compare column value with range of values.

BETWEEN operator includes both lower and upper limits.

Syntax :-

BETWEEN LOWLIMIT AND UPPERLIMIT

NOT BETWEEN LOWLIMIT AND UPPERLIMIT

Example :-

Display employee records who are earning between 2000 and 5000 ?

SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 5000;

Display employee records who are joined between 1981 year?

SELECT * FROM EMP WHERE HIREDATE BETWEEN


’01-JAN-1981’ AND ’31-DEC-1981’ ;

Display employee records who are joined in 2000 year ?

SELECT * FROM EMP WHERE HIREDATE NOT BETWEEN


’01-JAN-2000’ AND ’31-DEC-2000’ ;

IN OPERATOR :-

IN operator used to compare column value with multiple values.

-18- Naresh i Technologies


Oracle 11g

Syntax :-

IN (V1,V2,V3,------)

NOT IN (V1,V2,V3,-----)

List of values can be maximum of 1000.

Display employee records who working as CLERK OR MANAGER ?

SELECT * FROM EMP WHERE JOB IN (‘CLERK’,’MANAGER’) ;

Display employee records who not working for 10 & 20 dept ?

SELECT * FROM EMP WHERE DEPTNO NOT IN (10,20) ;

LIKE Operator:-

LIKE operator used to compare column value with string patterns.

Syntax:-

LIKE ‘pattern’
NOT LIKE ‘pattern’
Pattern consists of alphabets,digits and metacharacters.

The different meta characters in ORACLE

%→it is used to replace none or many chars.

_→it is used to replace exactly one char.

Display employee records whose name starts with S ?

SELECT * FROM EMP WHERE ENAME LIKE ‘S%’ ;

Display employee records whose name ends with S ?

SELECT * FROM EMP WHERE ENAME LIKE ‘%S’ ;

Display employee records whose name doesn’t contain S ?

SELECT * FROM EMP WHERE ENAME NOT LIKE ‘%S%’ ;

-19- Naresh i Technologies


Oracle 11g

Display employee records where A is the second char in their name ?

SELECT * FROM EMP WHERE ENAME LIKE ‘_A%’;

Display employee records who are joined in JAN month ?

SELECT * FROM EMP WHERE HIREDATE LIKE ‘%JAN%’ ;

Display employee records who are joined in 1981 year ?

SELECT * FROM EMP WHERE HIREDATE LIKE ‘%81’ ;

Display employee records who are joined in 1st 9 days ?

SELECT * FROM EMP WHERE HIREDATE LIKE ‘0%’ ;

Display employee records who are earning 5 digits salary ?

SELECT * FROM EMP WHERE SAL LIKE ‘_____’ ;

Display employee records whose name contains _ ?

SELECT * FROM EMP WHERE ENAME LIKE ‘%\_%’


ESCAPE ‘\’ ;

IS operator:-

IS operator is used to compare column value with NULL OR NOT NULL value

Syntax :-

IS NULL

IS NOT NULL

Example:-
display employee records whose comm. Is null ?

SELECT * FROM EMP WHERE COMM IS NULL ;

Display employee records whose comm. Is not null ?

SELECT * FROM EMP WHERE COMM IS NOT NULL ;

Data Sorting Using ORDER BY clause :-

-20- Naresh i Technologies


Oracle 11g

The ORDER BY clause is used to sort the rows.


By default ORDER BY clause sorts data in ascending order.
Number 1-99

Dates Earliest-Latest

String A-Z;

NULL last

Syntax:-

SELECT <collist> FROM <tablename>

[WHERE condition]

[ORDER BY <col1> [DESC] [,<col2> [DESC]-----]

[NULLS LAST/FIRST]

By default records are sorted in ascending order to sort records in descending order
use DESC option.

By default NULL values arranged last in ascending order to control NULL value records
use NULLS LAST OR NULLS FIRST option.

Arrange employee records in ascending order of their sal ?

SELECT * FROM EMP ORDER BY SAL ;

Arrange employee records in descending order of their sal ?

SELECT * FROM EMP ORDER BY SAL DESC ;

Display employee records working for 10th dept and arrange the result in ascending
order of their sal ?

SELECT * FROM EMP WHERE DEPTNO=10 ORDER BY SAL ;

Arrange employee records in ascending of their deptno and with in dept arrange
records in descending order of their sal ?

SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC ;

In ORDER BY clause we can use column name or column number .

-21- Naresh i Technologies


Oracle 11g

SELECT * FROM EMP ORDER BY 5 DESC ;

Arrange employee records in descending order of their comm. If comm. Is null then
arrange those records last ?

SELECT * FROM EMP ORDER BY COMM DESC NULLS LAST ;

DISTINCT clause :-

DISTINCT clause is used to eliminate duplicate values.

Syntax :-

DISTINCT colname
DISTINCT col1,col2
DISTINCT *

Select DISTINCT Job From Emp;

Select DISTINCT Deptno, Job From Emp;

DML commands :-

INSERT
UPDATE
DELETE
INSERT ALL
MERGE

Copying Data from one table to another table :-

Syntax:-

INSERT INTO <TARGETTABLE>


SELECT <COLLIST> FROM <SOURCE TABLE>

Example :-

INSERT INTO EMP_TEMP


SELECT * FROM EMP;

-22- Naresh i Technologies


Oracle 11g

UPDATE command :-

Update is used to modify data in a table.

Syntax:-

UPDATE table
SET column = value[, column = value,……]
[WHERE condition];

Example :-

Update all employees commission to 500 ?

UPDATE EMP SET COMM=500 ;

Update employee comm to 500 whose comm. Is null ?

UPDATE EMP SET COMM=500 WHERE COMM IS NULL ;

Increment employee salary by 10% and comm. By 20%


Those who are working as SALESMAN ?

UPDATE EMP SET SAL=SAL*1.1 , COMM=COMM*1.2


WHERE JOB=’SALESMAN’ ;

Update different employees comm. With different values ?

UPDATE EMP SET


COMM = &COMM WHERE EMPNO=&EMPNO;

Update the column value with DEFAULT value ?

UPDATE EMP SET HIREDATE=DEFAULT WHERE EMPNO=7844;

Returning Clause:-

Returning clause is used to return values into variables after update .

To use returning clause declare bind variable as follows.

-23- Naresh i Technologies


Oracle 11g

Bind variables are declared at SQL prompt , and accessed using : operator.

SQL>variable sumsal number ;

Sql>Update Emp

Set Sal=Sal*1.2

Where Deptno=10

Returning SUM(Sal) INTO :sumsal;

DELETE command :-

DELETE command is used to delete record or records from a table.

Syntax:-

DELETE FROM <TABNAME> [WHERE <cond> ----]

Delete all employee records ?

DELETE FROM EMP ;

Delete employee records whose empno=7844 ?

DELETE FROM EMP WHERE EMPNO=7844 ;

Delete employee records having more than 30 yrs expr ?

DELETE FROM EMP WHERE (SYSDATE-HIREDATE)/365 >= 30;

Multi Table Insert

INSERT ALL command used to insert data into multiple tables.

Using INSERT ALL command we can extract data from one or more tables and insert
data into multiple tables.

There are two types of INSERT ALL

1 UNCONDITIONAL INSERT ALL

2 CONDITIONAL INSERT ALL

-24- Naresh i Technologies


Oracle 11g

UNCONDITIONAL INSERT ALL :-

Syntax:-

INSERT ALL
INTO <TAB1> VALUES (VALUE LIST)
INTO <TAB2> VALUES(VALUE LIST)
SELECT STATEMENT ;

Example :-

Create table two tables as follows

Emp1(empno,ename,sal)

Emp2(empno,ename,sal)

INSERT ALL
INTO EMP1 VALUES(EMPNO,ENAME,SAL)
INTO EMP2 VALUES(EMPNO,ENAME,SAL)
SELECT EMPNO,ENAME,SAL FROM EMP ;

CONIDTIONAL INSERT ALL :-

Syntax :-

INSERT ALL
WHEN COND1 THEN
INTO <TAB1> VALUES (VALUE LIST)
WHEN COND2 THEN
INTO <TAB2> VALUES (VALUE LIST)
SELECT STATEMENT ;

Example :-

INSERT ALL
WHEN JOB=’CLERK’ THEN
INTO EMP1 VALUES(EMPNO,ENAME,SAL)

-25- Naresh i Technologies


Oracle 11g

WHEN JOB=’MANAGER’ THEN


INTO EMP2 VALUES(EMPNO,ENAME,SAL)
SELECT EMPNO,ENAME,SAL,JOB FROM EMP;

MERGE Statement:-

MERGE command is used to merge data into a table.

MERGE is the combination of INSERT ,UPDATE OR DELETE.

Syntax :-

MERGE INTO <TARGETTABLE> <ALIAS>


USING <SOURCE TABLE>/QUERY <ALIAS>
ON (CONDITION)
WHEN MATCHED THEN
UPDATE
WHEN NOT MATCHED THEN
INSERT

Example :-

EMPS EMPT

EMPNO ENAME SAL EMPNO ENAME SAL


1 A 5000 1 A 2000
2 B 3000 2 B 3000
3 C 4000 3 C 4000
4 D 6000

Example :-

MERGE INTO EMPT T


USING EMPS S
ON (S.EMPNO=T.EMPNO)
WHEN MATCHED THEN
UPDATE SET T.ENAME=S.ENAME ,
T.SAL =S.SAL
WHEN NOT MATCHED THEN
INSERT VALUES (S.EMPNO,S.ENAME,S.SAL)

-26- Naresh i Technologies


Oracle 11g

DDL commands :-

CREATE
ALTER
DROP
TRUNCATE
RENAME

CREATING A TABLE FROM ANOTHER TABLE :-

Syntax :-

CREATE TABLE <TABNAME>


AS
SELECT STATEMENT ;

Example :-
CREATE TABLE EMPA
AS
SELECT * FROM EMP ;
COPYING ONLY STRUCTURE :-

CREATE TABLE EMPB


AS
SELECT * FROM EMP WHERE 1=2;

ALTER command :-

ALTER command is used to modify data definition of a table.

ALTER command is used to do following operations.

ADD A COLUMN
DROP A COLUMN
MODIFY A COLUMN
INCR/DECR FIELD SIZE
CHANGING DATATYPE

-27- Naresh i Technologies


Oracle 11g

CHANGING FROM NULL TO NOT NULL


CHANGING FROM NOT NULL TO NULL.
TO MAKE TABLE READ ONLY

ADDING A COLUMN:-

Syntax :-

ALTER TABLE <TABNAME>


ADD (COLNAME DATATYPE(SIZE) [ , COLNAME -------])

Example:-

ALTER TABLE EMP


ADD (DOB DATE)

DROPING A COLUMN :-

Syntax :-

ALTER TABLE <TABNAME> DROP COLUMN COLNAME ;

Example :-

ALTER TABLE EMP DROP COLUMN DOB ;

MODIFYING A COLUMN :-
Example :-

ALTER TABLE <TABNAME>


MODIFY(COLNAME DATATYPE(SIZE) ,-----------)

INCR / DECR FIELD SIZE :-

-28- Naresh i Technologies


Oracle 11g

ALTER TABLE EMP


MODIFY (ENAME VARCHAR(20)) ;
NOTE :-

1 char field size can be decremented upto max length.

2 to decrement precision or scale of a numeric field , filed should be empty.

CHANGING DATATYPE :-

ALTER TABLE EMP


MODIFY (ENAME CHAR(20)) ;

NOTE :-
To change datatype of a column the column should be empty.

CHANGING FROM NULL TO NOT NULL :-

ALTER TABLE EMP


MODIFY (ENAME NOT NULL) ;

CHANGING FROM NOT NULL TO NULL :-

ALTER TABLE EMP


MODIFY(ENAME NULL) ;

DROP command :-

DROP command drops a table from database.

Syntax :-

DROP TABLE <TABNAME> ;

Example :-

DROP TABLE CUSTOMER ;

TRUNCATE command :-

-29- Naresh i Technologies


Oracle 11g

TRUNCATE command releases memory allocated for a table.

TRUNCATE deletes all the data from a table.

Syntax :-

TRUNCATE TABLE <TABNAME>

Example :-

TRUNCATE TABLE EMP ;

Difference between DELETE and TRUNCATE :-

DELETE TRUNCATE

Deletes all or particular deletes all records


Records

Data can be restored Data cannot be restored


After delete after Truncate

Recorded in Log file Not recorded in log file.

RENAME command :-

Used to change name of the table.

Syntax :-

RENAME <OLDNAME> TO <NEWNAME> ;

RENAME EMP TO EMPLOYEE ;

Integrity Constraints :-

Integrity constraints are the rules in real life, which are to be imposed on the data. If
the computer data is not satisfying the constraints then it is considered as inconsistent.
These rules are to be enforced on data because of the presence of these rules in real
life. These rules are called integrity constraints. The data, which is not obeying

-30- Naresh i Technologies


Oracle 11g

integrity constraints, is called inconsistent data. Every software must enforce integrity
constraints, otherwise inconsistent data is generated.

Types of Integrity Constraints :-

Domain constraints:-

A domain means a set of permitted values.


Domain constraints are handled by
defining proper data type
specifying not null constraint
specifying check constraint.

Entity Integrity :-

Entity Integrity constraints are two types

Unique Constraint
Primary Constraint

Refrential Integrity :-

A refrential integrity constraint states that the values of the foreign key value should
match with values of primary key/unique Column of another or same table.

Foreign key constraint establishes relationship between tables.


The table holding primary key is called parent table
The table holding foreign key is called child table

Self Refrential Integrity :-

If a foreign key in one table refers primary key/unique column of the same table then
it is called self refrential
Integrity.

Foreig Key relationship imposes the following restrictions:

-31- Naresh i Technologies


Oracle 11g

INSERTION
Parent – No restriction.
Child - restriction

UPDATION
Parent –Restriction
Child - Restriction

DELETION
Parent – Restriction
Child – No Restriction

Types of Constraints in oracle :-

NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY

The above constraints can be declared at

1 Column level
2 Table level

Column level :-

Use column level to declare constraints for single column.


Column level constraints are declaration follows column declaration.

Table level :-

Use table level to declare constraints for combination of columns.


Table constraints are declared after declaring all columns

NOT NULL constraint :-

-32- Naresh i Technologies


Oracle 11g

It ensures that a table column cannot be left empty


Column declared with NOT NULL is a mandatory column
The NOT NULL constraint can only be applied at column level
Syntax :-

Columnname Datatype(size) NOT NULL

Example :-

SQL> CREATE TABLE DEPT


(
DEPTNO NUMBER(2) ,
DNAME VARCHAR2(20) NOT NULL ,
LOC VARCHAR2(20)
);

UNIQUE constraint :-

UNIQUE constraint has the following characterstics

UNIQUE columns do not accept duplicate values


One table can have a number of unique keys
By default UNIQUE columns accept null values unless
NOT NULL constraint is specified.
Oracle automatically creates UNIQUE index on the column
declared with UNIQUE constraint
UNIQUE constraint can be declared at column level and table level.

Declaring UNIQUE constraint at Column Level :-

Syntax :-

Columnname Datatype(size) UNIQUE

-33- Naresh i Technologies


Oracle 11g

Example :-

SQL> CREATE TABLE DEPT


(DEPTNO NUMBER(4)
constraint uq_deptno_dept UNIQUE ,
DNAME VARCHAR2(20) ,
LOC VARCHAR2(20)
)

Declaring UNIQUE constraint Table Level :-

CREATE TABLE <TABNAME>


( COLNAME1 DATATYPE(SIZE) ,
COLNAME2 DATATYPE(SIZE) ,
UNIQUE (COLUMNNAME1,COLUMNNAME2))

SQL> CREATE TABLE DEPT


(DEPTNO NUMBER(4)
DNAME VARCHAR2(20) ,
LOC VARCHAR2(20),
constraint uq_deptno_dept UNIQUE(DEPTNO)
)

PRIMARY KEY constraint :-

PRIMARY KEY is the candidate key which uniquely identifies a record in a table

Characterstics of PRIMARY KEY :-

There should be at the most one PK for a table


PK column do not accept null values
PK coumn do not accept duplicate values
If PK is composite then uniqueness is determined by the combination of columns
It is recommended that PK column should be short and numeric
Oracle automatically creates Unique Index on PK column

-34- Naresh i Technologies


Oracle 11g

Limitations :-

Composite key can contain max of 32 columns

Primary key cannot be declared on columns declared with


LOBS , LONG RAW,VARRAY,NESTED TABLE .

Declaring PRIMARY KEY at Column Level :-

Syntax :-

CREATE TABLE <TABNAME>


(COLNAME DATATYPE(SIZE) PRIMARY KEY ,
COLNAME DATATYPE(SIZE)
)

Example :-

CREATE TABLE ACCOUNTS


(ACCNO NUMBER(10)
CONSTRAINT PK_ACCOUNTS PRIMARY KEY ,
ACNAME VARCHAR2(20) NOT NULL ,
BALANCE NUMBER(11,2)
)

Declaring PRIMARY KEY at Table Level :-

Syntax :-

CREATE TABLE <TABNAME>


(COLNAME DATATYPE(SIZE) ,
COLNAME DATTATYPE(SIZE),
[ CONSTRAINT <NAME> ] PRIMARY KEY(COLUMNLIST)
)
Example :-

-35- Naresh i Technologies


Oracle 11g

CREATE TABLE ORDER_DETAILS


(ORDID NUMBER(4) ,
PRODID NUMBER(4) ,
QTY NUMBER(2) ,
CONSTRAINT PK_ORD_PROD PRIMARY KEY(ORDID,PRODID))

CHECK CONSTRAINT :-

Check constraint validates data based on a condition .


Value entered in the column should not violate the condition.
Check constraint allows null values.
Check constraint can be declared at table level or column level.

Limitations :-

Conditions should not contain pseudo columns like ROWNUM,LEVEL etc

Condition should not access columns of another table

Declaring Check Constraint Column level :-

Syntax :-

COLNAME DATATYPE(SIZE)
[CONSTRAINT <NAME>] CHECK(CONDITION)

Example :-

SQL>CREATE TABLE ACCTS


(ACCNO NUMBER(4) PRIMARY KEY,
ACNAME VARCHAR2(20) NOT NULL ,
BAL NUMER(11,2)
CONSTRAINT CK_BAL CHECK(BAL>1000)) ;

-36- Naresh i Technologies


Oracle 11g

Declaring CHECK constraint at Table level :-

SQL>CREATE TABLE ACCTS


(ACCNO NUMBER(4) PRIMARY KEY,
ACNAME VARCHAR2(20) NOT NULL ,
BAL NUMER(11,2) ,
CONSTRAINT CK_BAL CHECK(BAL>1000)) ;

FOREIGN KEY CONSTRAINT :-

Foreign key is used to establish relationship between tables.


Foreign is a column in one table that refers
primary key/unique columns of another or same table.
Values of foreign key should match with values of
primary key/unique or foreign key can be null.
Foreign key column allows null values unless it is declared with not null.
By default oracle establish 1:M relationship between two tables.
To establish 1:1 relationship between two tables declare foreign key with unique
constraint
Foreign key can be declared at column level or table level.
Composite foreign key must refer composite primary key or
Composite unique key.

Declaring foreign key at column level :-

Syntax :-

Colname datatype(size) [constraint <name>]


References parenttable(colname)

Example :-

SQL> CREATE TABLE DEPT


(Deptno Number(2) Constraint pk_dept PRIMARY KEY,
Dname Varchar2(20)
);

-37- Naresh i Technologies


Oracle 11g

SQL> CREATE TABLE EMP


(Empno Number(4) constraint pk_emp PRIMARY KEY,
Ename Varchar2(20) NOT NULL ,
Sal Number(7,2)
constraint ck_sal_emp CHECK(sal>3000),
Deptno Number(2) constraint fk_deptno_emp
References DEPT(Deptno)
)

Declaring Foreign Key constraint at Table Level :-

SQL>CREATE TABLE STUD_COURSE


(Sid Number(2) ,
Cid Number(2) ,
Doc Date ,
Constraint pk_stud_course PRIMARY KEY(Sid,Cid))

SQL>CREATE TABLE CERTIFICATES


(Certno Number(4) PRIMARY KEY,
Doi Date ,
Sid Number(2),
Cid Number(2) ,
Constraint fk_sid_cid Foreign key(sid,cid)
References STUD_COURSE(Sid,Cid)
);

DEFAULT Option :-

If column Declared with DEFAULT option then oracle inserts


DEFAULT value when value is not provided.
DEFAULT option prevents entering NULL values into the column.

Example :-

SQL>CREATE TABLE EMP


(Empno Number(4) ,

-38- Naresh i Technologies


Oracle 11g

Ename Varchar2(20) ,
Hiredate Date Default Sysdate);

SQL> insert into emp(empno,ename) values(1,’x’) ;

After executing the above command oracle inserts sysdate into Hiredate column.

Adding and Droping Constraints to a table:-

Alter command is used to add or to drop a constraint to an existing table.

Syntax :-

ALTER TABLE <TABNAME>


ADD [CONSTRAINT <NAME>]
CONSTRAINT_TYPE(COL1 [,COL2])

Example :-

SQL>ALTER TABLE EMP


ADD CONSTRAINT PK_EMP PRIMARY KEY(EMPNO);

SQL>ALTER TABLE EMP


ADD CONSTRAINT FK_DNO_EMP
FOREIGN KEY(DNO) REFERENCES DEPT(DEPTNO);

SQL> ALTER TABLE EMP


ADD CONSTRAINT
CK_SAL_EMP CHECK(SAL>3000) NOVALIDATE;

NOVALIDATE :-

If constraint is added with NOVALIDATE option then oracle doesn’t validate existing
data and validates only future
DML operations.

-39- Naresh i Technologies


Oracle 11g

NOVALIDATE option can be used only for CHECK constraint.

Droping Constraint :-

Syntax :-

ALTER TABLE <TABNAME> DROP CONSTRAINT <NAME>

Example :-

SQL>ALTER TABLE EMP DROP CONSTRAINT PK_EMP ;

Note :-

PRIMARY KEY cannot dropped if that PRIMARY KEY is referenced by any FOREIGN KEY.

If PRIMARY KEY is dropped with CASCADE options then


Dependent FOREIGN KEY is also dropped

Enabling/Disabling a Constraint:-

If the constraints are present, then for each DML operation constraints are checked by
executing certain codes internally. It may slow down the DML operation marginally. For
massive DML operations, such as transferring data from one table to another because
of the presence of constraint, the speed will be considered slower. To improve the
speed in such cases, the

following methods are adopted:

Disabling constraint
Performing the DML operation DML operation
Enabling constraint

Disabling Constraint:-

Syntax :-

-40- Naresh i Technologies


Oracle 11g

ALTER TABLE <TABNAME>


DISABLE CONSTRAINT <NAME>

Example :-

SQL>ALTER TABLE EMP DISABLE CONSTRAINT CK_SAL_EMP;

SQL>ALTER TABLE DEPT


DISABLE CONSTRAINT PK_DEPT CASCADE;

If constraint Disabled with CASCADE option then dependent


Foreign Key is also Disabled.

Enabling Constraint :-

Syntax :-

ALTER TABLE <TABNAME> ENABLE CONSTRAINT <NAME>

Example :-

SQL>ALTER TABLE EMP ENABLE CONSTRAINT CK_SAL_EMP ;


SQL>ALTER TABLE EMP
ENABLE VALIDATE CONSTRAINT CK_SAL_EMP;

Initially Immediate Deferrable

Suppose the constraint uses the deferrable clause the enforcement of constraint is
deferred, untill commit is issued by the user. Let us understand it using:

Creating table T2 and inserting data

Create Table T2

(A number(2), B number(2), c number(2),

CONSTRAINT ck_A CHECK (A>1), CONSTRAINT ck_B CHECK (B>1),

CONSTRAINT ck_c CHECK (C>1)

-41- Naresh i Technologies


Oracle 11g

INITIALLY DEFERRED DEFERRABLE);

Suppose table T2 has the following data:

A B C

2 3 4

2 2 5

2 6 0

Committing a transaction

commit;

the clause deffer able causes postponing of the enforcement of constraint checking.
Therefore, no error is issued even though second and third row violates the constraint.
If you issue commit, the whole transaction is rolled back and you will not get all the
rows that are inserted prior to it. If initially deferred is specified then that constraint is
checked at the end of the transaction.

If the rows that are manipulated by the transaction do not satisfy the constraint, then
the whole transaction is rolled back. When initially immediate is specified, which is also
the default setting then the constraints are enforced at the end of every DML
statement.

When the clause deferrable is used, the behavior of constraint can be changed in the
transaction by using the set constraint command.

Enforcing the constraint IMMEDIATE:-

SET CONSTRAINT ck_C IMMEDIATE;

Now the user can issue the following command for deferring it:

Set constraint ck_c DEFERRED;

Changing all constraints to Immediate

SET CONSTRAINT ALL IMMEDIATE;

If the constraint is not deferrable, then it cannot be manipulated using the set
constraint command. These facilities are provided to tackle various situations in the

-42- Naresh i Technologies


Oracle 11g

practical application where data is made according to the constraint at the end of the
transaction.

Delete Rules :-

Delete Rules specifies how a child record is affected if parent record is deleted.
Oracle supports following Delete Rules
ON DELETE NO ACTION (DEFAULT)
ON DELETE CASCADE
ON DELETE SET NULL

ON DELETE NO ACTION :-

If Delete Rule is ON DELETE NO ACTION then parent record cannot be deleted if any
child record present.

ON DELETE CASCADE :-

If foreign key declared with ON DELETE CASCADE then records in child table deleted
automatically when user deletes record
From parent table.

CREATE TABLE EMP (


EMPNO NUMBER(4) PRIMARY KEY,
ENAME VARCHAR2(20) NOT NULL,
SAL NUMBER(7,2) CHECK(SAL>3000) ,
DNO NUMBER(2) REFERENCES DEPT(DNO)
ON DELETE CASCADE);

ON DELETE SET NULL :-

if foreign key declared with ON DELETE SET NULL then


foreign key value in child table is set to NULL if user
deletes record from parent table.

CREATE TABLE EMP (

-43- Naresh i Technologies


Oracle 11g

EMPNO NUMBER(4) PRIMARY KEY,


ENAME VARCHAR2(20) NOT NULL,
SAL NUMBER(7,2) CHECK(SAL>3000) ,
DNO NUMBER(2) REFERENCES DEPT(DNO)
ON DELEETE SET NULL);

BUILT-IN FUNCTIONS

Built-in functions in oracle are mainly divided into two categories.

1 SINGLE ROW FUNCTIONS

2 MULTI ROW FUNCTIONS

1 SINGLE ROW FUNCTIONS :-

These functions process only one row.


Returns one value per row.
SINGLE ROW functions are categorized into following categories.
CHARACTER FUNCTIONS
DATE FUNCTIONS
MATHEMATICAL FUNCTIONS
CONVERSION FUNCTIONS
SPECIAL FUNCTIONS

CHARACTER FUNCTIONS :-

These functions mainly operate on character data.


The functions are listed in the following table:-

FUNCTION DESCRIPTION

-44- Naresh i Technologies


Oracle 11g

ASCII (char) ASCII value of first character

Ex:- ASCII (‘ABC’) =65

CHR (n) The character with ASCII value n

Ex:- CHR (65) =A

CONCAT(STR1,STR2) str2 is concatenated to str1

Ex :- CONCAT(‘oracle’,’ server’)

=oracle server

INITCAP(char) First letter of char is capitalized

Ex:- INTICAP (‘naresh’) =Naresh

INSTR (char1,… It gives mth occuerence of char2 in char1.

char2, n, m) search starts from n. Return value is

numeric

Ex:- INSTR (‘abcabdebd’, ‘bd’, 1, 1) = 5

The first occuerence of bd starts from

Position 5, if m= 1 is provided.

INSTR (‘abcabdbd’, ‘bd’, 1, 2) =8

The second occuerence of bd starts from 8

LENGTH(char) Length of string

Ex:-length (‘abc’) = 3

LOWER (char) Converts all character in starting to lower

case.

Ex:- LOWER (ABC) = abc

-45- Naresh i Technologies


Oracle 11g

LPAD(char1,n, Char 1 left padded to length n by char2

char2 ) Ex:-LPAD(‘Nagpur’, 8, ‘city’) gives

‘cityNagpur’

LTRIM(char, set) Trims character upto the first charcter not

in set from left side.

Ex:- LTRIM (‘Nagpur’, ‘N’) =agpur

RPAD(char1,n, Right pad the char1 to length with

char2) sequence of character in char2

Ex:- RPAD (‘Nagpur’,4, ‘city’)=Nagpurcity

RTRIM(char, set) Trims the character from the right side up

to last character not inset

Ex:-RTRIM (‘Nagpur’, (u,r)) =Nagp

It is trimmed upto p since u are in the set.

REPLACE(string, used to replace one string with another


Search string, string.
Replace with string)
Ex :- REPLACE(‘UTI BANK’,’UTI’,’AXIS’)

AXIS BANK

SOUNDEX(char) A character value representing the sound

of word in char.

Ex:-soundex(‘son’)=soundex(‘sun’)

If you compare the strings son and sun it

-46- Naresh i Technologies


Oracle 11g

will return FALSE; if you compare its

sound, then it will return TRUE, since

both are producing the same sound.

SUBSTR (char, It is a substring of char beginning of

m, n) character m, and n characters long

Ex:- substr (’17-MAY-99’, 4, 3) = MAY

UPPER(char) It produces all letters in uppercase

Ex:- UPPER (‘abc’) = ABC

TRANSLATE( It translates set in from_c to character set

char, from_c, n to_c

to_c) Ex:- Translate (‘Bombay’, ‘M’, ‘A’)=

‘BOMBAY’

DATE FUNCTIONS :-

The following function are used with dates:

FUNCTION DESCRIPTION

ADD_MONTHS It adds n months to date.

(d, n) Ex:-ADD_MONTHS(’17-MAY-99’, 2)=

17-JUL-99

LAST_DAY(d) It is the date of last day of month

containing d.

-47- Naresh i Technologies


Oracle 11g

Ex:- LAST_DAY(‘17-MAY-99’) =31-MAY-99

MONTHS_ It is the number of months between two

BETWEEN(d1,d2) dates d1, d2.

Ex:-MONTHS_BETWEEEN (’17-MAY-99’,

‘19-JUL-99’) =2

NEXT_DAY It is the date of the first day of week

(d, char) named by char equal to or later.

Ex:- NEXT_DAY (‘20-DEC-99’, ‘WED’)=

22-DEC-99

TRUNC( It truncates digits of precision from a value.

Value, precision) Ex:-TRUNC(45.665888,2)=45.66

EXTRACT(FMT It is used to extract time component from

FROM DATE) date expression.

Ex:-EXTRACT(year from date ‘2003-08-02’)

=2003

Displaying date:-

SELECT SYSDATE FROM DUAL;

Extracting day from date:-

SELECT EXTRACT(DAY FROM SYSDATE) FROM DUAL;

Extracting year from date:-

-48- Naresh i Technologies


Oracle 11g

SELECT EXTRACT(YEARFROMSYSDATE) FROM DUAL;

Extracting month from date:-

SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL;

NUMBER FUNCTIONS:-

The functions are used with numeric data.


The argument to the function is a number.

ABS (n) Absolute value of n

EX: ABS (-9)=9

CEIL(n) smallest integer greater than or equal

to n.

EX:-CEIL (9,5) =10

FLOOR (n) Largest integer less than or equal to n

EX:- FLOOR (10,5) =10

MOD (m,n) Remainder of m divided by n

EX:- MOD (17,5) =2

POWER(M,N) m is raised to nth power where n is integer

Ex:- POWER (3,3)

ROUND(N, M) n rounded to m decimal places

EX:-ROUND (10,586,2) =10.59

ROUND(153, 456, -2) =200

-49- Naresh i Technologies


Oracle 11g

TRUNC(n, m) n truncated to m decimal places

EX:- TRUNC (10.586, 2) =10.58

TRUNC (156.56,-2) =100

SIGN (n) Returns -1 if n<0;

1 if n>0;

0 if n=0

EX:- SGN (-5) = -1

SGN (5) = 1

SGN (0) =0

SQRT (n) Square root of n

EX:- SQRT (9) =3

Select mod (salary, 100) from emp_company;

CONVERSION FUNCTIONS :-

TO_CHAR ():-

Aspect Parameter Description Example

Century cc Two-digit century 21

Scc Two-digit century with a -10

Negative sign(-) for B.C.

-50- Naresh i Technologies


Oracle 11g

Quarter Q One-digit quarter of the 1

Year.

Year YYYY All four digits of the year. 2008

IYYY All four digits of the ISO 2008

year.

RRRR All four digits of the rounded 2008

year (governed by the present

year). See the section “How

Oracle Interprets Two-Digit-

Years” later in this chapter for

details .

SYYYY All four digits of the year with a - 1001

negative sign(-) for B.C.

Y,YYY All four digits of the year, with a 2,008

comma after the first digit.

YYY Last three digits of the year 008

IYY Last three digits of the ISO Year 008

YY Last two digits of the year 08

IY Last two digits of the ISO Year 06

RR Last two digits of the rounded 08

-51- Naresh i Technologies


Oracle 11g

Year, which depend on the present

Year. See the section “How Oracle

Interprets Two-Digit Years” later in

This chapter for details.

Y Last digit of the year. 8

I Last digit of the ISO Year. 8

YEAR Name of the year in upper case. TWO THOUSAND

EIGHT

Year Name of the year with the first Two Thousand

Letter in uppercase. Eight.

Month MM Two-digit month of the year. 01

MONTH Full name of the month in upper JANUARY

Case, right-padded with spaces to a

total length of nine characters.

Month Full name of the month with first January

letter in uppercase, right padded

with spaces to a total length of nine

characters.

MON First three letters of the name of the JAN

month in uppercase.

Mon First three letters of the name of the Jan

month with the first letter in upper

case.

-52- Naresh i Technologies


Oracle 11g

RM Roman numeral month. The roman numeral

month for the fourth

month is IV

Week WW Two-digit week of the year. 02

IW two-digit ISO week of the year. 02

W One-digit week of the month. 2

Day DDD Three-digit day of the year. 103

DD Two-digit day of the month. 31

D One-digit day of the week. 5

DAY Full name of the day in upper MONDAY

case.

Day Full name of the day with the Monday

first letter in uppercase.

DY First three letters of the name MON

of the day in uppercase.

Dy First three letters of the name Mon

of the day with the first letter in

uppercase.

J Julian day-the number of days that 2439892

have passed since January1,4713 B.C.

Hour HH24 Two-digit hour in 24-hour format. 23

HH Two-digit hour in 12-format. 11

Minute MI Two-digit minute . 57

Second SS Two-digit second. 45

-53- Naresh i Technologies


Oracle 11g

FF Fractional seconds with an optional when dealing with

[1…9] number of digits to the right of the 0.123456789

decimal point. Only applies timestamp seconds, FF3 would

which you”ll learn about in the section round the seconds

“Using Timestamps” later in this chapter. To 0.123.

SSS Number of seconds past 12 A.M. 46748

MS Millisecond(millimonths of the 100

Second).

CS Centisecond(hunderedths of a sec 10

separator characters that allow you to separate the For the date Dec 13,

-/,.;: aspects of a date and time. You can supply 1969, DD-MM-YYYY

“text” freeform text in quotes as a separator. Would produce

12-13-1969, and

DD/MM/YYYY would

Produce 12/13/1969.

Suffix AM AM or PM as appropriate. AM

or PM

A.M. A.M. or P.M. as appropriate. P.M.

or

P.M.

AD or AD or BC as appropriate. AD

BC

-54- Naresh i Technologies


Oracle 11g

A.D.or A.D. or B.C. as appropriate. B.C.

B.C.

TH Suffix to a number . you can make the For a day number of

Suffix uppercase by specifying the numeric 28, ddTH would

format in uppercase and vice versa for produce 28 th, and

lowercase. DDTH would produce

28TH.

SP Number is spelled out. For a day number of

28, DDSP would

Produce TWENTY-

EIGHT, and ddsp

Would produce

Twenty-eight.

SPTH Combination of TH and SP For a day number of

28, DDSPTH would

Produce TWENTY-

EIGHT, and ddspTH

Would produce

Twenty-eight.

Era EE Full era name for Japanese Imperial, No example

ROC Official, and Thai Buddha calendars.

E Abbreviated era name. No example

Time TZH Time Zone hour. You’ll learn about time 12

zones Zones later in the section “using Time

-55- Naresh i Technologies


Oracle 11g

Zones.”

TZM Time Zone minute. 30

TZR Time Zone region. PST

TZD Time Zone with daylight saving information. No example

TO_CHAR():-

PARAMETER FORMAL EXAMPLE DESCRIPTION

9 999 Returns digits in specified position, with

a leading negative sign if the number is

negative.

0 0999 0999: Returns a number with leading

Zeros .

9900 9900: Returns a number with trailing

Zeros.

. 999.99 Returns a decimal point in the specified

Position.

, 9,999 Returns a comma in the specified

Position.

$ $999 Returns a leading dollar sign.

B B9.99 If the integer part of a fixed point number

is zero, returns spaces for the Zeros.

C C999 Returns the ISO currency symbol in the

Specified position. The symbol comes

-56- Naresh i Technologies


Oracle 11g

from the NLS_ISO_CURRENCY database

parameter set by a DBA.

D 9D99 Returns the decimal point symbol in the

specified position. The symbol comes

from the NLS_NUMERIC_CHARACTER

database parameter (the default is a

period character).

EEEE 9.99EEEE Returns the number using the scientific

notation.

FM FM90.9 Removes leading and trailing spaces from

the number.

G 9G999 Returns the group separator symbol in the

specified position. The symbol comes

from the NLS_NUMERIC_CHARACTER

database parameter.

L L999 Returns the local currency symbol in the

specified position. The symbol comes from

the NLS_NUMERIC_CURRENCY database

parameter.

MI 999MI Returns a negative number with a trailing

minus sign.

PR 999PR Returns a negative number in angle

bracket(<>).

Returns a positive number with leading

-57- Naresh i Technologies


Oracle 11g

and trailing spaces.

RN RN Returns the number as Roman numerals.

RN returns uppercase numerals; rn returns

lower case numerals. The number must be

an integer between 1 and 3999.

S S999 S999: Returns a negative number with a

999S leading negative sign; returns a positive

number with a leading positive sign.

999S: Returns a negative number with a

trailing negative sign; returns a positive

number with a trailing positive sign.

TM TM Returns the number using the minimum

number of characters. The default is TM9,

which returns the number using fixed

notation unless the number of characters is

greater than 64. If greater than 64, the

the number is returned using scientific

notation.

U U999 Returns the dual currency symbol (Euro,for

example )in the specified position. The

symbol comes from the NLS_DUAL_

CURRENCY database parameter.

V 99V99 Returns the number multiplied by

where x is the number of 9 characters

-58- Naresh i Technologies


Oracle 11g

after the V. If necessary, the number is

rounded.

X XXXX Returns the number in hexadecimal. If the

is not an integer, the number is rounded to

an integer.

SPECIAL FUNCTIONS :-
DECODE FUNCTION :-
Decode functions works like if-then-else
Syntax :-
DECODE(EXPR,VALUE1,RETURN EXPR1,
VALUE2, RETURN EXPR2,
-------------------,
DEFAULT EXPR)
If EXPR is equal to VALUE1 then DECODE returns EXPR1
If EXPR is equal to VALUE2 then DECODE returns EXPR2
If EXPR is equal not equal to VALUE1 or VALUE2 then DECODE
Returns DEFAULT EXPR.

Example :-

SELECT ENAME,SAL,
DECODE(JOB,’CLERK’,’WORKER’,
‘MANAGER’,’BOSS’,
‘PRESIDENT’,’BIG BOSS’,
‘EMPLOYEE’) AS JOB
FROM EMP;

UPDATE EMP SET


SAL = DECODE(JOB,’CLERK’,SAL*1.1,
‘SALESMAN’,SAL*1.15,
‘MANAGER’,SAL*1.2

-59- Naresh i Technologies


Oracle 11g

SAL*1.05)

NVL:-
NVL function converts NULL values
Syntax :-
NVL(expr1,expr2)
If expr1 is NULL then NVL function returns expr2
Example :-
SELECT ENAME,SAL,SAL+NVL(COMM,0) AS TOTSAL
FROM EMP;
NVL2 :-
NVL2 function converts NULL values and NOT NULL values.
NVL2(expr1,expr2,expr3)
If expr1 is NOT NULL returns expr2 otherwise returns expr3
Example :-
UPDATE EMP SET
COMM = NVL2(COMM,COMM+200,500)

GREATEST :-
Returns GREATEST number among given numbers
Syntax :-
GREATEST(expr1,expr2,expr4,----)
Example :-
SELECT GREATEST(10,20,30) FROM DUAL ;
LEAST :-
Returns LEAST number among given numbers
Syntax:-
LEAST(expr1,expr2,expr3)
Example:-
SELECT LEAST(10,20,30) FROM DUAL;
NULLIF :-
Syntax:-
NULLIF(expr1,expr2)
Returns NULL if given expressions are equal otherwise returns expr1.
SELECT NULLIF(100,200) FROM DUAL;

-60- Naresh i Technologies


Oracle 11g

MULTI ROW FUNCTIONS:-


These functions will process group of rows.
Returns one value from that group.
These functions are also called as AGGREGATE functions.

MAX :-
Returns maximum value of a given expression

Syntax:-
MAX(expr)

Example :-
SELECT MAX(SAL) FROM EMP;

MIN:-
Returns minimum value of a given expression.
Syntax :-
MIN(expr)
Example:-
SELECT MIN(SAL) FROM EMP;

SUM :-
Returns sum of a given expression.
This function cannot be applied on strings and dates.

Syntax:-
SUM(expr)
Example:-
SELECT SUM(SAL) FROM EMP;
AVG :-
Returns avg value of a given expression.
Syntax:-
AVG(expr)
Example:-
SELECT AVG(SAL) FROM EMP;
COUNT :-
Returns no of values present in a column.

-61- Naresh i Technologies


Oracle 11g

COUNT function ignores NULL values.

Syntax :-

COUNT(expr)

Example:-

SELECT COUNT(EMPNO) FROM EMP;

COUNT(*):-

Returns no of records

Example :-
SELECT COUNT(*) FROM EMP;

CASE Statement :-
The CASE expression performs if-then –else logic .
supported in Oracle Database 9i and above.
The CASE expression works in a similar manner to DECODE. use CASE because
it is ANSI-compliant .
the CASE expression is easier to read.

There are two types of CASE Statements


Simple case.
Searched case .
Simple CASE Statement :-
Simple CASE expressions use expressions to determine the value to return.
Syntax :-
CASE search_expression
WHEN expression1 THEN result1
WHEN expression2 THEN result2
…………………….
WHEN expression THEN result
ELSE default_result

-62- Naresh i Technologies


Oracle 11g

END
Search_expression is the expression to be evaluated.
expression1, expression2, …………,expression are the expressions to be evaluated
against search_expression.
result1, result2,………….., result are the returned results(one for each possible
expression). If expression1 evaluates to search_expression, results is returned, and
similarly for the other expressions.
default_result is returned when no matching expression is found.
Example :-
SELECT ENAME,SAL, CASE JOB
WHEN ‘CLERK’ THEN ‘WORKER’
WHEN ‘MANAGER’ THEN ‘BOSS’
WHEN ‘PRESIDENT’ THEN ‘BIG BOSS’
ELSE
‘EMPLOYEE’
END AS JOB
FROM EMP ;

Searched CASE Statement :_


Searched CASE expressions use conditions to determine the returned value.
Syntax :-
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
………………..
WHEN condition THEN result
ELSE default_result
END
Where,
condition1, condition2,…….. conditionN are expressions to be evaluated.
result1, result2,…………resultN are the returned results(one for each possible condition).
If condition is true, result1 is returned, and similarly for the other expressions.
default_result is returned when there is no condition that returns true

-63- Naresh i Technologies


Oracle 11g

Example :-
SELECT ENAME,SAL,CASE
WHEN SAL>3000 THEN ‘HISAL’
WHEN SAL<3000 THEN ‘LOSAL’
ELSE
‘MODERATE SAL’
END AS SALRANGE
FROM EMP ;

Group By Clause :-
Group by Clause is used to group rows based on one or more columns to get some
information on those groups of rows.
For Example , you might want to get the total salaries paid to each department to do
this the rows must be grouped based on department.

We can pass group of rows to an aggregate function.The aggregate function performs


computation on the each group and returns one value per group.

Using Group by Clause we can get summarized data from detailed data.

Syntax:-
SELECT <COLLIST> FROM <TABNAME>
[WHERE <COND>]
GROUP BY <COL1> [, <COL2>-----]
[HAVING <COND>]
[ORDER BY <COL1> [DESC] [,<COL2>-----]

CAUTION:-
Only GROUP BY column and aggregate function should appear in SELECT list.

Example :-
SELECT DEPTNO,SUM(SAL)

-64- Naresh i Technologies


Oracle 11g

FROM EMP
GROUP BY DEPTNO;

SELECT JOB,MIN(SAL),MAX(SAL),SUM(SAL),COUNT(*)
FROM EMP
GROUP BY JOB
.
SELECT
EXTRACT(YEAR FROM HIREDATE) AS YEAR,COUNT(*) AS EMPS
FROM EMP
GROUP BY EXTRACT(YEAR FROM HIREDATE)

CAUTION :-
You cannot use an aggregation function to limit rows in WHERE clause .

SELECT DEPTNO,SUM(SAL)
FROM EMP
WHERE SUM(SAL)>10000
GROUP BY DEPTNO ;

Error at Line 3 :
ORA-00934 : group function is not allowed here.

HAVING clause to Filter Groups:-

Use HAVING clause to limit the groups returned by GROUP BY clause.

Example :-

SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY DEPTNO
HAVING SUM(SAL)>10000 ;

NOTE :-
GROUP BY can be used without HAVING , but HAVING must be used in conjunction
with GROUP BY.

-65- Naresh i Technologies


Oracle 11g

WHERE VS HAVING :-

Use WHERE clause to filter individual rows.


Use HAVING clause to filter groups returned by GROUP BY.
To filter data before GROUP BY use WHERE clause.
To filter data after GROUP BY use HAVING clause.
In condition if aggregate function appears then use HAVING.

USING WHERE , GROUP BY ,HAVING claused Together :-

You can use WHERE,GROUP BY, and HAVING clauses together in the same query.
When you do this the WHERE clause first filters the rows, the GROUP BY clause then
groups the remaining rows and finally HAVING clause filters the groups.
Example :-

SELECT DEPTNO,SUM(SAL)
FROM EMP
WHERE DEPTNO IN (10,20)
GROUP BY DEPTNO
HAVING SUM(SAL) > 10000

GROUPING ROWS BASED ON MORE THAN ONE COLUMN :-

You can GROUP rows based on more than one column.

Example :-
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY DEPTNO,JOB

Above example , groups records based on department wise and within the department
records are grouped based on job wise.

-66- Naresh i Technologies


Oracle 11g

CROSS TABULATION :-

An example of cross tabulation shown below :-

DEPTNO CLERK MANAGER SALESMAN


10 1300 2450
20 1900 2975
30 95 2850 5600

To produce the above result the following query should be run

SELECT DEPTNO,SUM(DECODE(JOB,'CLERK',SAL)) AS CLERK ,


SUM(DECODE(JOB,'MANAGER',SAL)) AS MANAGER ,
SUM(DECODE(JOB,'SALESMAN',SAL)) AS SALESMAN
FROM EMP
GROUP BY DEPTNO

Cross tabulation is simplified in ORACLE 11G by using PIVOT operator.

SELECT * FROM
(SELECT DEPTNO,SAL,JOB FROM EMP)
PIVOT
(
SUM(SAL) FOR JOB IN (‘CLERK’,’MANAGER’,’SALESMAN’)
)
ORDER BY DEPTNO;

-67- Naresh i Technologies


Oracle 11g

EXTENDING GROUP BY CLAUSES USING ROLLUP & CUBE :-

GROUP BY clause can be extended by using two operators.

ROLLUP
CUBE

ROLLUP :-

ROLLUP returns a row containing a subtotal for each group ,plus a row containing a
grand total for all the groups.

Example : -

Passing single column to ROLLUP :-

SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY ROLLUP(DEPTNO) ;

Passing multiple columns to ROLLUP :-

SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY ROLLUP(DEPTNO,JOB)
ORDER BY DEPTNO,JOB;

CUBE :-

Cube returns rows containing a subtotal for all combinations of columns, plus a row
containing the grand total.

Example : -
Passing single column to CUBE :-

-68- Naresh i Technologies


Oracle 11g

SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY CUBE(DEPTNO) ;

Passing multiple columns to CUBE :-

SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY CUBE(DEPTNO,JOB)
ORDER BY DEPTNO,JOB;

JOINS
There are times, when data has to be retrieved from more than one table. In such
situations JOINS are used.
Tables involved in JOIN operation must share a meaningful relationship.
Oracle performs JOIN operation when more than one table appears in FROM clause.

Types of JOINS :-
Equi Join or Inner Join
Non-Equi Join
Self Join
Outer Join
Cross Join
EQUI JOIN :-
In EQUI JOIN Join operation is performed based on common columns.
To perform EQUI JOIN there should be a common column in joining tables.
To perform EQUI JOIN parent/child relationship between the table is not mandatory.
Syntax :-
SELECT <COLLIST> FROM <TAB1> , <TAB2>

-69- Naresh i Technologies


Oracle 11g

WHERE <JOIN COND>


[AND <JOIN COND> AND <COND>------]
JOIN CONDITION :-
Child.fk = parent.pk ( if relationship exists)
Tab1.commoncolumn = Tab2.commoncolumn
(if there is no relationship)
Oracle performs EQUI JOIN by comparing Foreign key values with Primary key value
by using = operator.
EQUI JOIN returns all rows from both tables that satisfies the JOIN CONDITION.
No of JOIN CONDS depends on number of tables to be joined .
To join N tables , min N-1 JOIN CONDS are required.
Join conditions cannot be based on LOB columns.

Guidelines:-
When writing a SELECT statement that joins tables, precede the column name with the
table name or table alias for clarity and to improve performance.
If the same column name appears in more than one table, the column name must be
prefixed with the table name.
Example:-
Select E.Empno, E. Ename , E.Deptno ,
D. Deptno , D. Dname , D. Loc
From Emp E,Dept D
where E.Deptno = D.deptno;

NON-EQUI JOIN :-
Use NON-EQUI JOIN when there is no common column in joining tables.
Syntax:-
Select col1,col2,…….
From<table 1>,<table 2>
Where <JOIN COND>
[AND <JOIN COND> AND--------]

In NON-EQUI JOIN JOIN COND is not based on = operator. Its based on other
than = operator usually BETWEEN operator.

-70- Naresh i Technologies


Oracle 11g

Example:-
Select E.empno,E.Ename,E.Sal,S.Grade,S.Losal,S.Hisal
From Emp E, Salgrade S
Where E.Sal between S.Losal and S.Hisal;
SELF JOIN :-
Joining a table to itself is called SELF JOIN
SELF JOIN is performed when tables having self refrential integrity.
To perform SELF JOIN same table must be listed twice with different alias.
SELF JOIN is performing EQUI JOIN with in the table.
Syntax :-
Sql>Select Columns
From Table1 T1, Table1 T2
Where T1.Column1=T2.Column2;
Example:-
Sql>Select E.Ename “Employee Name”,
M.Enmae “Manager Name”
From Emp E,Emp M
Where E.Mgr=M.Empno;

OUTER JOIN :-

OUTER JOIN is extension to EQUI JOIN.


EQUI JOIN returns only matching records but not unmatched records.To get
unmatched records also perform OUTER JOIN.
Operator (+) is used to perform OUTER JOIN.
OUTER JOIN is of three types :-
1 LEFT OUTER JOIN
2 RIGHT OUTER JOIN
3 FULL OUTER JOIN
LEFT OUTER JOIN :-
LEFT OUTER JOIN returns all rows from LEFT SIDE table and matching records from
RIGHT SIDE table.
To perform LEFT OUTER JOIN (+) should be on RIGHT SIDE.
Syntax :-
Select Table1.Column,Table2.Column
From Table1,Table2
Where Table1.Column=Table2.Column(+)

-71- Naresh i Technologies


Oracle 11g

Example :-
Select e.ename,d.dname
from emp e,dept d
where e.deptno = d.deptno(+) ;

RIGHT OUTER JOIN:-

RIGHT OUTER JOIN returns all rows from RIGHT SIDE table and matching records from
LEFT SIDE table.

Syntax :-
Select Table1.Column,Table2.Column
From Table1,Table2
Where Table1.Column(+)=Table2.Column
Example :-
Select e.ename,d.dname
from emp e,dept d
where e.deptno(+) = d.deptno ;

FULL OUTER JOIN :-

Returns all rows from both tables.


Prior to oracle 9i doesn’t support FULL OUTER JOIN
To perform FULL OUTER JOIN in prior to ORACLE 9i

Select e.ename,d.dname
from emp e,dept d
where e.deptno(+) = d.deptno ;
UNION ALL
Select e.ename,d.dname
from emp e,dept d
where e.deptno = d.deptno (+);

HINT :-
(+) should not be on both sides.

-72- Naresh i Technologies


Oracle 11g

CROSS JOIN :-
CROSS JOIN returns cross product of two tables.
Each record of one table is combined with each and every record of another table.
If table1 contains 10 records and table2 contains 5 records then CROSS JOIN between
table1 and table2 returns 50 records.
ORACLE performs CROSS JOIN when we submit query without JOIN COND.

Syntax :-

SELECT COL1,COL2
FROM TAB1,TAB2

Example:-
ORDERS DISCOUNT
ORDAMT DIS
100000 5
7
12
15

To get ORDAMT for each and every DISCOUNT percentage

SELECT O.ORDAMT,D.DIS, (O.ORDAMT*D.DIS)/100 AMOUNT


FROM ORDERS O,DISCOUNT D

ANSI STYLE OR SQL/92 STANDARD :-


Prior to ORACLE 9i , ORACLE doesn’t support ANSI style.
These styles are introduced from ORACLE 9i onwards.
In ANSI style JOIN COND is specified by using ON clause or USING clause.

EQUI JOIN :-
in ANSI style to perform EQUI JOIN use keyword JOIN or INNER JOIN.
JOIN COND is specified by using ON clause or USING clause.
Use USING clause if common column name is same.

Example :-

-73- Naresh i Technologies


Oracle 11g

SELECT E.ENAME,D.DNAME
FROM EMP E JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)
Joining more than two tables in ANSI style
SELECT E.ENAME,D.DNAME,M.MNAME MGRNAME
FROM EMP E JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)
JOIN MGR M
ON (M.DEPTNO=D.DEPTNO)
Using USING clause :-
SELECT E.ENAME,D.DNAME
FROM EMP E JOIN DEPT D
USING (DEPTNO)

HINT :-
In USING clause common column name should not be prefixed with table alias.

NON-EQUI JOIN :
in NON-EQUI JOIN to specify the JOIN COND use ON clause
Example :-
SELECT E.ENAME,G.GRADE
FROM EMP E JOIN SALGRDE G
ON (E.SAL BETWEEN G.LOSAL AND G.HISAL)

SELF JOIN :-

SELECT X.ENAME , Y.ENAME MGRNAME


FROM EMP X JOIN EMP Y
ON X.MGR = Y.EMPNO

OUTER JOIN :-

JOIN COND can be specified by using ON clause or USING clause.

LEFT OUTER JOIN :-

-74- Naresh i Technologies


Oracle 11g

To perform LEFT OUTER JOIN use keyword LEFT OUTER JOIN

Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E LEFT OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)

RIGHT OUTER JOIN :-

To perform RIGHT OUTER JOIN use keyword RIGHT OUTER JOIN.


Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
ON (E.DEPTNO=D.DEPTNO)

SELEC E.ENAME,D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
USING(DEPTNO)

FULL OUTER JOIN :-


To perform FULL OUTER JOIN use keyword FULL OUTER JOIN
Keyword.

Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E FULL OUTER JOIN DEPT D
USING(DEPTNO)

NATURAL JOIN :-

NATURAL JOIN is possible in ANSI style.


NATURAL JOIN is similar to EQUI JOIN.
NATURAL JOIN is performed when common column name is same.

-75- Naresh i Technologies


Oracle 11g

Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E NATURAL JOIN DEPT D

Above query performs JOIN operation on DEPTNO.


if table contains more than one common column , to restrict JOIN operation then use
USING clause

SELECT E.ENAME,D.DNAME
FROM EMP E NATURAL JOIN DEPT D
USING(DEPTNO)

CROSS JOIN :-
to perform CROSS JOIN use keyword CROSS JOIN
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E CROSS JOIN DEPT D

SET OPERATORS :-
UNION
UNION ALL
INTERSECT
MINUS

UNION :-
UNION operator
combines data returned by two SELECT statement.
eliminates duplicates.
Sorts result

Syntax:-
SELECT <Column1>,……<ColumnN> FROM <DerivedTable>
UNION
SELECT<Column1>,……<ColumnN> FROM <DerivedTable>
To perform UNION the structure of the first query must be equal to structure of the
second query (no of columns & datatype)

-76- Naresh i Technologies


Oracle 11g

ORDER BY clause should be used only for last query but not for each query
Example :-
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION
SELECT JOB FROM EMP WHERE DEPTNO=20

UNION ALL :-
UNION ALL is similar to UNION but it includes duplicates
Example :-
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION ALL
SELECT JOB FROM EMP WHERE DEPTNO=20

UNION vs JOIN :-
UNION combines data but JOIN relates data.
Only Similar structures can be combined with UNION.
Dissimilar structures can also be JOINED.
INTERSECT :-
INTERSECT operator returns common values from the result of two SELECT
statements.
Syntax:-
SELECT <Column1>,…….<ColumnN> FROM <DerivedTable>
INTERSECT
SELECT<Column1>,………<ColumnN> FROM <DerivedTable>
Example:-
SELECT JOB FROM EMP WHERE DEPTNO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20

MINUS:-
MINUS operator returns values present in the result of first SELECT statement and not
present in the result of second SELECT statement.

Syntax:-
SELECT <Column1>,……..<ColumnN> FROM <DerivedTable>
MINUS
SELECT <Column1>,………<ColumnN> FROM <DerivedTable>

-77- Naresh i Technologies


Oracle 11g

Example:-
SELECT JOB FROM EMP WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20

SUBQUERIES
SUBQUERY :-
a query embedded in another query is called subquery.
One query is called inner/child/subquery.
Another query is called outer/parent/main query.
The result of inner query acts as input to outer query.
Outer query can be
INSERT
UPDATE
DELETE
SELECT
Inner query must be always
SELECT
Subqueries appears in WHERE CLAUSE
HAVING CLAUSE
FROM CLAUSE
SELECT CLAUSE

There are two types of subqueries:


Single-row subqueries:-
returns zero rows or one row to the outer SQL statement. There is a special case of a
single-row subquery that contains exactly one column; this type of subquery is called
scalar subquery.
Multiple-row subqueries:-
return one or more rows to the outer SQL statement.
In addition, there are three subtypes of subqueries that may return single or multiple
rows:
Multi column subqueries :-
returns more than one column value to the outer SQL statement.
Nested Queries :-

-78- Naresh i Technologies


Oracle 11g

a subquery embedded in another subquery.


Co-related subquery :- subquery access value of the outer query.

Single Row subqueries:-


if inner query returns only one row then it is called single row subquery.

Syntax :-
SELECT <COLLIST> FROM <TABNAME>
WHERE COLNAME OP (SELECT STATEMENT)
OP can be < > <= >= = <>
Example :-
SUBQUERIES IN WHERE CLAUSE :-
Display employee records whose job equals to job of SMITH?
SELECT * FROM EMP
WHERE JOB = (SELECT JOB FROM EMP WHERE
ENAME=’SMITH’) ;

Display employee name earning maximum salary ?

SELECT ENAME FROM EMP


WHERE SAL = (SELECT MAX(SAL) FROM EMP)

Display all records except last record ?

SELECT * FROM EMP


WHERE ROWID <(SELECT MAX(ROWID) FROM EMP)

Display employee names earning between minimum salary of 10 dept and maximum
salary of 30 dept ?

SELECT * FROM EMP


WHERE SAL BETWEEN (SELECT MIN(SAL) FROM EMP
WHERE DEPTNO=10)
AND
(SELECT MAX(SAL) FROM EMP
WHERE DEPTNO=30)

-79- Naresh i Technologies


Oracle 11g

SUBQUERIES IN HAVING CLAUSE :-

Display deptnos whose avg(sal) geater than avg(sal) of 10 dept?

SELECT DEPTNO FROM EMP


GROUP BY DEPTNO
HAVING AVG(SAL) > (SELECT AVG(SAL) FROM EMP
WHERE DEPTNO=10) ;

SUBQUERIES IN UPDATE COMMAND :-


Update employee salary to maximum salary whose empno=7369 ?

UPDATE EMP SET


SAL = (SELECT MAX(SAL) FROM EMP)
WHERE EMPNO=7369 ;
Swap employee
SUBQUERIES IN DELETE COMMAND : -
Delete employee record whose job equals to job of SMITH ?
DELETE FROM EMP
WHERE JOB= (SELECT JOB FROM EMP WHERE
ENAME=’SMITH’);

MULTI ROW SUBQUERIES :-


if inner query returns more than one row then it is called
MULTI ROW SUBQUERY.

Syntax :-

SELECT <COLLIST> FROM <TABNAME>


WHERE COLNAME OP (SELECT STATEMENT)

OP must be IN
NOT IN
ANY

-80- Naresh i Technologies


Oracle 11g

ALL

Example :-
Display 4th,7th,11th record in EMP table ?
SELECT * FROM EMP
WHERE ROWID IN (SELECT DECODE(ROW,NUM,4,ROWID,
7,ROWID,
11,ROWID)
FROM EMP)
NESTED QUERIES :-
A subquery embedded in another subquery is called NESTED QUERY.
Queries can be nested upto 255 level.
Example :-
Display employee name earning second maximum salary ?
SELECT ENAME FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP))

Update the employee salary to maximum salary of SALES dept ?


UPDATE EMP
SET SAL = (SELECT MAX(SAL) FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPT
WHERE DNAME=’SALES’))
MULTI COLUMN SUBQUERIES :-

If inner query returns more than one column value then it is called MULTI COLUMN
subquery.

Example :-
Display employee names earning maximum salaries in their dept ?
SELECT ENAME FROM EMP
WHERE (DEPTNO,SAL) IN (SELECT DEPTNO,MAX(SAL)
FROM EMP
GROUP BY DEPTNO)
CO-RELATED SUBQUERIES :-
A subquery references one or more columns of parent query
is called CO-RELATED subquery because it is related to outer query.

-81- Naresh i Technologies


Oracle 11g

This subquery executes once for each and every row of main query.

Example :-

Display employee names earning more than avg(sal) of their dept ?


SELECT ENAME FROM EMP X
WHERE SAL > (SELECT AVG(SAL) FROM EMP
WHERE DEPTNO=X.DEPTNO)
Display employee names earning more than their manager ?

SELECT ENAME FROM EMP X


WHERE SAL > (SELECT SAL FROM EMP
WHERE EMPNO = X.MGR) ;
Delete duplicate records in a table ?

DELETE FROM EMP X


WHERE ROWID > (SELECT MIN(ROWID) FROM EMP
WHERE EMPNO=X.EMPNO
AND
ENAME = X.ENAME
AND
SAL = X.SAL );
USING EXISTS and NOT EXISTS operators :-

EXISTS operator returns TRUE or FALSE.


If inner query returns at least one record then EXISTS returns TRUE otherwise returns
FALSE.

ORACLE recommends EXISTS and NOT EXISTS operator instead of IN and NOT IN.

Display dept which not empty ?

SELECT * FROM DEPT D


WHERE EXISTS (SELECT * FROM EMP WHERE
DEPTNO=D.DEPTNO)

Display dept which is empty ?

-82- Naresh i Technologies


Oracle 11g

SELECT * FROM DEPT D


WHERE NOT EXISTS (SELECT * FROM EMP WHERE
DEPTNO=D.DEPTNO)

INLINE VIEWS :-

If subquery follows FROM clause then it is called INLINE VIEW.

Using INLINE VIEWS

Column alias can be used in WHERE clause.


Window functions can be used in WHERE clause.
Result of one process can be used in another process.

Syntax :-
SELECT <COLLIST> FROM (SELECT STATEMENT ) ;
The result of inner query acts as TABLE for outer query.
Example :-
Display top 3 maximum salaries in EMP table ?
SELECT DISTINCT SAL FROM
(SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP)
WHERE RNK<=3 ;

SUBQUERIES FOLLOWS SELECT CLAUSE :-


Subqueries can also follow SELECT clause.
These subqueries are called SCALAR queries.
A SCALAR query returns one value per row.
Syntax :-
SELECT (SELCT STATEMENT) ,---- FROM <TABNAME>
Example :-
SELECT (SELECT COUNT(*) FROM EMP) AS EMP ,
(SELECT COUNT(*) FROM DEPT) AS DEPT
FROM DUAL;

-83- Naresh i Technologies


Oracle 11g

Database Transactions
A database transaction is a group of SQL statements that perform a logical unit of
work. You can think of transaction as an inseparable set of SQL statements whose
results should be made permanent in the database as a whole or undone as a whole .
An example of a database transaction is a transfer of money from one bank account to
another. One UPDATE statement would subtract from the total amount of money from
one account, and another UPDATE would add money to the other account. Both the
subtraction and the addition must be permanently recorded in the database; otherwise,
money will be lost. If there is a problem with the money transfer, then the subtraction
and addition must both be undone. The simple example outlined in this paragraph uses
only two UPDATE statements, but a transaction may consist of many INSERT, UPDATE,
and DELETE statements.

Committing and Rolling Back a Transaction:


To permanently record the results made by SQL statements in a transaction, you
perform a commit, using the SQL COMMIT statement.
If you need to undo the results, you perform a rollback, using the SQL ROLLBACK
statement, which resets all the rows back to what they were originally.
The following example adds a row to the customers table and then makes the change
permanent by performing a COMMIT:
INSERT INTO customers
VALUES (6, ‘FRED’, ‘GREEN’, ’01-JAN-1970’, ‘800-555-1215’);
1 row created.
COMMIT;
Commit complete.
The following example updates customer #1 and then undoes the change by
performing a ROLLBACK:
UPDATE customers
SET first_name = ‘edward’
WHERE customer_id = 1;
1 row created.
ROLLBACK;
Rollback complete.
Starting and Ending a Transaction:

-84- Naresh i Technologies


Oracle 11g

A transaction is a logical unit of work that enables you to spit up your SQL statements.
A transaction has a beginning and an end.
Transaction begins when one of the following events occurs:
You connect to the database and perform a DML statement (an INSERT,UPDATE, OR
DELETE).
A previous transaction ends and you enter another DML statement.

A Transaction ends when one of the following events occurs:


You perform a COMMIT or a ROLLBACK.
You perform a DDL statement, such as a CREATE TABLE statement, in which case a
COMMIT is automatically performed.
You perform a DCL statement, such as a GRANT statement, in which case a COMMIT
is automatically performed. You’ll learn about GRANT in the next chapter.
You disconnect from the database. If you exist SQL*Plus normally, by entering the
EXIT command, a COMMIT is automatically performed for you. If SQL*Plus terminates
abnormally- for example, if the computer on which SQL*Plus was running were to
crash- a ROLLBACK is automatically performed.
You perform a DML statement that fails, in which case a ROLLBACK is automatically
performed for that individual DML statement.
Savepoints:
You can also set a savepoint at any point with in a transaction. These allow you to roll
back changes to that savepoint. Savepoints can be useful to break up very long
transactions, because, if you make a mistake after you’ve set a savepoint, you don’t
have to roll back the transaction all the way to the start. However, you should use
savepoints sparingly: you might be better off restructuring your transaction into
smaller transactions instead.
You’ll see an example of a savepoint shortly, but first let’s see the current price for
products #4 and #5:
SELECT product_id, price
FROM products
WHERE product_id IN (4, 5);
PRODUCT_ID PRICE
4 13.95
5 49.99
The price for product #4 is $13.95, and the price for product #5 is $49.99.The
following UPDATE increases the price of product #4 by 20 percent:
UPDATE products

-85- Naresh i Technologies


Oracle 11g

SET price = price *1.20


WHERE product_id =4;
1 row updated.
The following statement sets a savepoint named save1:
SAVEPOINT save1;
Savepoint created.
Any DML statements run after this point can be rolled back to the savepoint, and the
change made to product #4 will be kept.
The following UPDATE increases the price of product #5 by 30 percent:
UPDATE products
SET price = price *1.30
WHERE product_id = 5;
1 row updated.

ROLLBACK TO save1;
Rollback complete.
This has undone the price change for product #5, but left the price change for product
#4 intact. The following query shows this:

ACID Transaction Properties:


A transaction has four fundamental properties, known as ACID properties
Atomic: Transactions are atomic, meaning that the SQL statements contained in a
transaction make up a single unit of work.
Consistent: Transactions ensure that the database state remains consistent, meaning
that the database is in a consistent state when a transaction begins and that it ends in
another consistent state when the transaction finishes.
Isolated: Separate transactions should not interfere with each other.
Durable: Once a transaction has been committee, the database changes are
preserved, even if the machine on which the database software is running crashes
later.
The Oracle database software handles these ACID properties and has extensive
recovery facilities for restoring databases after system crashes.
Concurrent Transactions:
The Oracle database software supports many users interacting with a databse, and
each user can run their own transaction at the same time. These transactions are
known as concurrent transactions.

-86- Naresh i Technologies


Oracle 11g

If users are running transactions that affect the same table, the effects of those
transactions are separated from each other until a COMMIT is performed. The following
sequence of events, based on two transactions named T1 and T2 that access the
customers table, illustrates the separation of transactions:
1. T1 and T2 perform a SELECT that retrieves all the rows from the customer table.
2. T1 performs an INSERT to add a row in the customers table, but T1 doesn’t perform
a COMMIT.
3.T2 performs another SELECT and retrieves the same rows as those in step1. T2
doesn’t “see” the new row added by T1 in step2.
4. T1 finally performs a COMMIT to permanently record the new row added in step2.
5. T2 performs another SELECT and finally “sees” the new row added by T1.
To summarize: T2 doesn’t see the changes made by T1 until T1 commits its changes.
Transactions Locking:
To support concurrent transactions, the Oracle database software must ensure that the
data in the tables remain valid. It does this through the use of locks. Consider the
following example in which two transactions named T1 and T2 attempt to modify
customer #1 in the customer table:
1. T1 performs an UPDATE to modify customer #1, but T1 doesn’t perform a COMMIT.
T1 is said to have “locked” the row.
2. T2 also attempts to perform an UPDATE to modify customer #1, but since this row is
already locked by T1,T2 is prevented from getting a lock on the row. T2’s UPDATE
statement has to wait until T1 ends and frees the lock on the row.
3. T1 ends by performing a COMMIT, thus freeing the lock on the row.
4. T2 gets the lock on the row and the UPDATE is performed.T2 holds the lock on the
row until T2 ends.
To summarize: A transaction cannot get a lock on a row while another transaction
already holds the lock on that row.
Transaction 1 T1 Transaction 2 T2
(1) SELECT * (2) SELECT *
FROM customers; FROM customers;
(3) INSERT INTO customers
(customers_id, first_name,last_name)
VALUES(7, ‘Jason’, ‘Price’);
(4) UPDATE customers
SET last_name = ‘Orange’
WHERE customer_id = 2;
(5) SELECT * (6)SELECT *

-87- Naresh i Technologies


Oracle 11g

FROM customers; FROM customers;


The returned result set contains The returned results
the new row and the update. Set doesn’t contain
the new row or the
update made by T1.
Instead, the result set
Contains the original
Rows retrieved in step2.
(7) COMMIT; (8)SELECT *
This commits the new row and FROM customers:
the update. The returned result set
contains the new row
and the update made by
T1 in step 3 and 4.
Transactions Isolation Levels:
The transaction isolation level is the degree to which the changes made by one
transaction are separated from other transactions running concurrently. Before you see
the various transaction isolation levels available, you need to understand the types of
problems that may occur when current transactions attempt to access the same rows
in a table.

In the following list, you’ll see examples of two concurrent transactions named T1 and
T2 that are accessing the same rows; listed are the three types of potential transaction
processing problems.

Phantom reads:-
T1 reads a set of rows returned by a specified WHERE clause. T2 then inserts a new
row, which also happens to satisfy the WHERE clause of the query previously used by
T1. T1 then reads the rows again using the same query, but now sees the additional
row just inserted by T2. This new row is known as a “phantom” because to T1 this row
seems to have magically appeared.

Nonrepeatable reads:-
T1 reads a row, and T2 updates the same row just read by T1. T1 then reads the
same row again and discovers that the row is read earlier is now different. This is
known as a “non repeatable” read, because the row originally read by T1 has been
changed.

-88- Naresh i Technologies


Oracle 11g

Dirty reads:-
T1 updates a row, but doesn’t commit the update
T2 then reads the updated row.T1 then performs a rollback,
Undoing the previous update. Now the row just read by T2 is
no longer valid (it’s “dirty”) because the update made by T1
wasn’t committed when the row was read by T2.
To deal with these potential problems, database implement
various levels of transaction isolation to prevent concurrent
transactions from interfering with each other. The SQL
standard defines the following transaction isolation levels,

READ UNCOMMITTED:- Phantom reads, nonrepeatable reads,


and dirty reads are permitted.
READ COMMITTED:- Phantom reads and nonrepeatable reads
are permitted, but dirty reads are not.

REPEATABLE READ:- Phantom reads are permitted, but


Non repeatable and dirty reads are not.
SERIALIZABLE: Phantom reads, non repeatable reads, and
dirty reads are not permitted.

The Oracle database software supports the READ COMMITTED


and SERIALIZABLE transaction isolation levels. It doesn’t
support READ UNCOMMITTED or REPEATABLE READ levels.
The default transaction isolation level defined by the SQL
standard is SERIALIZABLE, but the default used by the Oracle
database is READ COMMITTED, which is acceptable for nearly
all applications.

FLASHBACK QUERIES:-

Most of the times an application crashes only because of


Human errors. A human error could result in data corruption
Due to which the application simply halts.

The mose human errors that causes an application to go down


are

-89- Naresh i Technologies


Oracle 11g

Accidental deletion of valuable data.


Deleting the Data.
Droping the table.

Oracle offers a solution called Flashbacking to recover data


Due to human errors.

Flashback technology allows viewing data back in time.

Flashback technology is introduced in ORACLE 9i

In ORACLE 10g Flashbacking made simple and flexible.

A flashback allows reverting mistakenly committed changes


By viewing the records before the commit was executed.

Flashbacking Data :-

Flashbacking is based on Timestamp


SCN (system change number)

Flashbacking based on Timestamp :-

SELECT * FROM EMP


AS OF TIMESTAMP (SYSDATE-1)

The above query displays data that exists before one day.

Using DBMS_FLASHBACK package :-

EXECUTE DBMS_FLASHBACK.ENABLE_AT_TIME(SYSDATE-2) ;

When the above procedure is executed the ORACLE performs


A flashback .
SYSDATE-2 means two days back.
Any query executed after performing Flashback will display

-90- Naresh i Technologies


Oracle 11g

The rows as they were 2 days back.

Example :-

SELECT * FROM EMP ;

Flashback can be disabled by

EXECUTE DBMS_FLASHBACK.DISABLE() ;

Flashback Table :-

Oracle flashback feature allows recovering a table after drop.


When a table is dropped oracle moves it to the recyclebin
rather than actually droping it.
A Recycle Bin is logical collection of dropped objects.
The contents of Recycle Bin is viewed by using
SHOW RECYCLEBIN command.
Flashback command is introduced in ORACLE 10g , which is
used to restore a table after drop.

Example :-

DROP TABLE EMP ;

To restore the table EMP issue the following command

FLASHBACK TABLE EMP TO BEFORE DROP;

A table can be restored with a new name.

FLASHBACK TABLE EMP TO BEFORE DROP RENAME TO EMPL;

PURGE command :-

-91- Naresh i Technologies


Oracle 11g

PURGE command releases space occupied by the object in


recyclebin .

PURGE TABLE EMP ;

To empty the RECYCLEBIN issue the following command

PURGE RECYCLEBIN ;

The table can be dropped without being sent to the


RECYCLEBIN. To do so issue the following command.

DROP TABLE EMP PURGE ;


ENABLING & DISABLING RECYCLEBIN :-

Recyclebin can be enabled & disabled.


By default recyclebin is enabled.
When it is enabled the dropped objects are placed in
Recyclebin.
When it is disabled the dropped objects are not placed
In Recyclebin.

To disable the Recyclebin issue the following command

ALTER SESSION SET RECYCLEBIN = OFF

To enable the Recyclebin issue the following command

ALTER SESSION SET RECYCLEBIN =ON

Creating a user

To create a user in the database, you use the CREATE USER statement. The simplified
syntax for the CREATE USER statement is as follows:

-92- Naresh i Technologies


Oracle 11g

CREATE USER user_name IDENTIFIED BY password


[DEFAULT TABLESPACE default_tablespace]
[TEMPORARY TABLESPACE temporary_tablespace];
The following example connects ass system and creates a user named Jason with a
password of price:
CONNECT system/manager
CREATE USER Naresh IDENTIFIED BY Oracle ;
The next example creates a user named henry and specifies a default and temporary
tablespace:
CREATE USER Naresh IDENTIFIED BY Oracle
DEFAULT TABLESPACE sers
TEMPORARY TABLESPACE temp;
If you want a user to be able to do things in the database, that must be granted the
necessary permissions to do those things. For example, to connect to the database a
user must be granted the permission to create a session, which is the CREATE
SESSION system privilege. Permissions are granted by a privileged user (system, for
example) using the GRANT statement.
The following example grants the CREATE SESSION permission tojason:
GRANT CREATE SESSION TO Naresh.
Changing a User’s Password:-
You can change a user’s password using the ALTER USER statement. For example, the
following statement changes the password for oracle to oracle11g.
ALTER USER Naresh IDENTIFIED BY Oracle11g ;

Deleting a User:-
You delete a user using the DROP USER statement.
CONNECT system/manager
DROP USER Naresh ;
System Privileges:-
A system privilege allows a user to perform certain actions within the database, such
as executing DDL statements. For example, CREATE TABLE allows a user to create a
table in their schema. Some of the commonly used system privileges are shown in the
table:
Granting System Privileges to a user:-
You use GRANT to grant system privilege to a user. The following example grants some
system privilege to steve (assuming you’re still connected to the database as system):
GRANT CREATE SESSION, CREATE USER,

-93- Naresh i Technologies


Oracle 11g

CREATE TABLE TO Naresh ;

SYSTEM PRIVILEGE ALLOWS YOU TO……


CREATE SESSION Connect to a database.
CREATE SEQUENCE Create a sequence, which is a
series of numbers that are
typically used to automatically
populate a primary key column.
you’ll learn about sequence in
the next chapter.
CREATE SYNONYM Create a synonym. A synonym
allows schema.
CRETAE TABLE Create a table in the user’s
schema.
CREATE ANY TABLE Create a table in any schema.
DROP TABLE Drop a table from the user’s
schema.
DROP ANY TABLE Drop a table from any schema.
CREATE PROCEDURE Create a stored procedure.
EXECUTE ANY PROCEDURE Execute a procedure in any
schema.
CREATE USER Create a user.
DROP USER Drop a user.
CREATE VIEW Create a view. A view is a
stored query that allows you to
access multiple tables and
columns. You may then query
the view as you would a table.
You’ll learn about views in the
next chapter.

You can also use WITH ADMIN OPTION to allow a user to grant a privilege to another
user. The following example grants the EXECUTE ANY PROCEDURE privilege with the
ADMIN option to Naresh.
GRANT EXECUTE ANY PROCEDURE TO Naresh WITH ADMIN OPTION;
EXECUTE ANY PROCEDURE can then be granted to another user by Naresh. The
following example connects as Naresh and grants EXECUTE ANY PROCEDURE to vijay

-94- Naresh i Technologies


Oracle 11g

CONNECT Naresh/oracle11g
GRANT EXECUTE ANY PROCEDURE TO vijay ;
You can grant a privilege to all users by granting to PUBLIC.
EXECUTE ANY PROCEDURE to PUBLIC:
CONNECT system/manager
GRANT EXECUTE ANY PROCEDURE TO PUBLIC;
Every user in the database now has the EXECUTE ANY PROCEDURE privilege.

Checking System Privilege Granted to a User:-


You can check which system privileges a user has by querying user_sys_privs.

Revoking System Privileges from a User:-


You revoke system privileges from a user using REVOKE. The following example
connects as system and revokes the CREATE TABLE privilege from Naresh.
CONNECT system/manager
REVOKE CREATE TABLE FROM Naresh ;
The next example revokes EXECUTE ANY PROCEDURE from steve:
REVOKE EXECUTE ANY PROCEDURE FROM Naresh ;
Object Privileges:-
An object privilege allows a user to perform certain actions on database objects, such
as executing DML statements on tables. For example, INSERT ON store.products allows
a user to insert rows into the products table of the store schema. some of the
commonly used objects privileges are shown in the table:

Object Privilege Allows a user to…….


SELECT Performs a select.
INSERT Perform an insert.
UPDATE Perform an update.
DELETE Perform a delete.
EXECUTE Execute a stored procedure.

Granting Object Privileges to a User:-


You use GRANT to grant an object privilege to a user. The following example connects
as store and grants the SELECT, INSERT, and UPDATE object privilege on the products
table to steve with the SELECT privilege on the employees table:

-95- Naresh i Technologies


Oracle 11g

CONNECT store/store_password
GRANT SELECT, INSERT, UPDATE ON store.products TO steve;
GRANT SELECT ON store.employees TO steve;
The next example grants the UPDATE privilege on the last_name and salary columns to
steve:
GRANT UPDATE (last_name, salary) ON store.employees TO steve;

You can also use the GRANT option to enable a user to grant a privilege to another
user. The following example grants the SELECT privilege on the customers table with
the GRANT option to steve:

GRANT SELECT ON store.customers TO steve WITH GRANT OPTOIN;

The SELECT ON store.customers privilege can then be granted to another user by


steve. The following example connects as steve and grants this privilege to gail:

CONNECT steve/button
GRANT SELECT ON store.customers TO gail;

Checking Object Privileges Made:-


You can check which table object privileges a user has made to other users by querying
user_tab_privs_made.
CONNECT store/store_password
SELECT *
FROM user_tab_privs_made
WHERE table_name = ‘PRODUCTS’;

Checking Object Privileges Retrieved:-


You can check which object privileges on a table a user has retrieved by querying the
user_tab_privs_recd table.
Revoking Object Privileges:-
You revoke object privileges using REVOKE. The following example connects as store
and revokes the INSERT privilege on the products table from steve:
CONNECT store/store_password
REVOKE INSERT ON products FROM steve;

-96- Naresh i Technologies


Oracle 11g

The next example revokes the SELECT privilege on the customers table from steve:

REVOKE SELECT ON store.customers FROM steve;


When you revoke SELECT ON STORE.customers from steve-who has already passed
this privilege to gail – gail also loses the privilege.

Roles
A role is a group of privileges that you can assign to a user or to another role. The
following points summarize the benefits and features of roles:
Rather than assigning privileges one at a time directly to a user, you can create a role,
assign privileges to that role, and then grant that role to multiple users and roles.
When you add or delete a privilege from a role, all users and roles assigned that role
automatically receive or lose that privilege.
You can assign multiple roles to a user or role.
You can assign a password to a role.
As you can see from these points, roles can help you manage multiple privileges
assigned to multiple users.

Creating Roles:-
To create a role, you must have the CREATE ROLE system privilege.
CONNECT system/manager
GRANT CREATE ROLE TO store;
GRANT CREATE USER TO store WITH ADMIN OPTION;
You create a role using the CREATE ROLE statement. The following statements
connects as store and create the three roles shown in table:

CONNECT store/store_password
CREATE ROLE product_manager;
CREATE ROLE hr_manager;
CREATE ROLE overall_manager IDENTIFIED by manager_password;

Notice overall_manager has a password of manager_password.

Role Name Has Permissions to…..


Product_manager Perform SELECT, INSERT,UPDATE,

-97- Naresh i Technologies


Oracle 11g

and DELETE operations on the


product_types and products tables.
hr_manager perform SELECT,INSERT,UPDATE,
and DELETE operations on the
salary_grades and employees
tables. Also, hr_manager is able to
create users.
overall_manager perform SELECT, INSERT,UPDATE,
and DELETE operations on all the
tables shown in the previous roles;
overall_manager will be granted
the previous roles.

Granting Privileges To Roles:-


You grant privileges to a role using the GRANT statement. You can grant both system
and object privileges to a role as well as grant another role to role.
The following example grants the required privileges to the product_manager and
hr_manager roles and grants these two roles to overall_manager:
GRANT SELECT, INSERT, UPDATE, DELETE ON product_types TO product_manager;
GRANT SELECT, INSERT, UPDATE, DELETE ON products TO product_manager;
GRANT SELECT, INSERT, UPDATE, DELETE ON salary_grades TO hr_manager;
GRANT SELECT, INSETR, UPDATE, DELETE ON employees TO hr_manager;
GRANT CREATE USER TO hr_manager;
GRANT product_manager, hr_manager TO overall_manager;

Granting Roles to a User:-


You grant a role to the user using GRANT. The following example grants the
overall_manager role to steve:
GRANT overall_manager TO steve;

Checking Roles Granted to a User:-


you can check which roles have been granted to a user querying user_role_prives.
CONNECT steve/button
SELECT *
FROM user_role_privs;

Checking System Privileges Granted to a Role:-

-98- Naresh i Technologies


Oracle 11g

You can check which system privileges have been granted to a role by querying
role_sys_privs.
The following example retrieves the rows from role_sys_privs (assuming you’re still
connected as store):

SELECT *
FROM role_sys_privs
ORDER BY privilege;

Checking Object privileges Granted to a Role:-


You can check which object privileges have been granted to a role by querying
role_tab_privs.
The following example queries role_tab_privs where roel equals HR_MANAGER:
SELECT *
FROM role_tab_privs
WHERE role= ‘HR_MANAGER’
ORDER BY table_name;

Revoking a Role:-
You revoke a role using REVOKE. The following example connects as store and revokes
the overall_manager role from steve:
CONNECT store/store_password
REVOKE overall_manager FROM steve;

Revoking Privileges from a Role:-


You revoke a privilege from a role using REVOKE. The following example connects as
store and revokes all privileges on the products an dproduct_types tables from
product_manager .

REVOKE ALL ON products FROM product_manager;


REVOKE ALL ON product_types FROM product_manager;

Dropping a Role:-
You drop a role using DROP ROLE. The following example drops the overall_manager,
product_manager, and hr_manager roles.
DROP ROLE overall_manager;
DROP ROLE product_manager;

-99- Naresh i Technologies


Oracle 11g

DROP ROLE hr_manager;

Hierarchical Queries :-
 A hierarchical query presents data in a inverted tree structure.
 The tree comprises of interconnected nodes.
 Each node may be connected to none,one or more childnodes.
 Each node is connected to one parent node. The top most
 node is the Root Node that has no parent.
 Nodes that do not have child nodes are called Leaf Nodes.

Syntax :-
SELECT [LEVEL] , <COLUMNNAME> -------
FROM <TABNAME>
[WHERE <COND>]
[START WITH <COND>]
[CONNECT BY PRIOR <COND>]

LEVEL :- LEVEL is a pseudo column that returns level of the tree.


START CONDITION :- used to specify root of the tree.

CONNECT BY PRIOR :- used to specify relationship between


Parent and child rows. This clause cannot be used to perform
Join operation.

The result of hierarchical query is shown below :-

KING
JONES
SCOTT
ADAMS
FORD
SMITH
BLAKE
ALLEN
WARD
MARTIN

-100- Naresh i Technologies


Oracle 11g

TURNER
JAMES
CLARK
MILLER

Example :-

Display employee names and their manager name in tree structure ?

SELECT RPAD(' ',LEVEL*2,' ')||ENAME


FROM EMP
START WITH ENAME='KING'
CONNECT BY PRIOR EMPNO=MGR

To sort siblings use ORDER SIBLINGS clause.

Example :-

SELECT RPAD(' ',LEVEL*2,' ')||ENAME


FROM EMP
START WITH ENAME='KING'
CONNECT BY PRIOR EMPNO=MGR
ORDER SIBLINGS BY ENAM ;

SYS_CONNECT_BY_PATH :-

Returns child node along with path

Example :-

SELECT ENAME,SYS_CONNECT_BY_PATH(ENAME,'\')
FROM EMP

-101- Naresh i Technologies


Oracle 11g

START WITH ENAME='KING'


CONNECT BY PRIOR EMPNO=MGR
ORDER SIBLINGS BY ENAME ;

CONNECT_BY_ISLEAF :-

Returns whether the node is leaf node or not


If node is leaf node then it returns 1 otherwise returns 0.

Example :-

SELECT ENAME,CONNECT_BY_ISLEAF
FROM EMP
START WITH ENAME='KING'
CONNECT BY PRIOR EMPNO=MGR
ORDER SIBLINGS BY ENAME

-102- Naresh i Technologies


Oracle 11g

DB OBJECT OR SCHEMA OBJECTS

TABLES
SEQUENCES
VIEWS
MATERIALIZED VIEWS
SYNONYMS
INDEXES
CLUSTERS
PROCEDURES
FUNCTIONS
PACKAGE
DB TRIGGER

SEQUENCE
A SEQUENCE is a schema object that can generate unique sequential values.
The SEQUENCE Values are often user for PRIMARY KEY’S and UNIQUE KEY’S.
CREATING SEQUENCES:-
Syntax:-
CREATE SEQUENCE sequenceName
[INCREMENT BY n]
[START WITH n]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NORDER;
INCREMENT BY:-
Specifies the interval between the Sequence Numbers.
Value can be Positive or Negative, but can not be 0.

If the value is positive it is Incremental Sequence else it Decremental Sequence.


MINVALUE:-
Specifies the sequence’s Minimum Value.

-103- Naresh i Technologies


Oracle 11g

NOMINVALUE:-
Specifies a minimum value of 1 for an ascending sequence and –(10)^26) for a
descending sequence.

MAXVALUE:-
Specifies the maximum value that sequence can generate.
NOMAXVALUE:-
Specifies a maximum value of 10^27 for an ascending sequence and -1 for a
descending sequence.

START WITH:-
Specifies the first sequence number to be generated.
For ascending sequence the default value is SEQUENCES’S MINIMUM value.

CYCLE:-
Specifies whether the sequence contains to generate values after reaching its
maximum or minimum value.

NOCYCLE:-
Specifies the SEQUENCE cannot general more values after the targeted limit.

CACHE:-
Specifies how many values the Oracle Server Preallocates and keep in memory.

NOCACHE:-
Specifies the values of a SEQUENCE are not preallocated.
If the above parameters are not specified by default 20 values are cached.

ORDER:-
Gurantee the sequence numbers to be generated in the order of request.

NOORDER:-
Does not generate the sequence Number with Order.

-104- Naresh i Technologies


Oracle 11g

NOTE:-
If the above parameters are not specified by default
START WITH Will be 1.
INCREMENT BY Will be positive 1.
SEQUENCE is NOCYCLE.
The CACHE Value Will be 20
SEQUENCE is ORDER.

Test Table:-
CREATE TABLE TDEPT
( DEPTNO NUMBER(4) Constraint Tdeptno_PK PrimaryKey,
DNAME VARCHAR2(14),
LOC VARCHAR2(13)
);

CREATION OF INCREMENTAL SEQUENCE:-


CREATE SEQUENCE SEQ1
INCREMENT BY 10
START WITH 10
MINVALUE 0
MAXVALUE 9999
NOCACHE
NOCYCLE;

USING SEQUENCE GENERATE VALUE :-


Every sequence has two psuedo columns
1 CURRVAL
2 NEXTVAL
CURRVAL returns current value of the sequence .
NEXTVAL returns next value of the sequence.

Both values are accessed by using sequence name as follows


SEQ.CURRVAL
SEQ.NEXTVAL

Example :-

-105- Naresh i Technologies


Oracle 11g

Insert into TDept


Values(SEQ1.Nextval,’SOFTWARE’,’HYD’);

Creating A Sequence with CYCLE:-


CREATE SEQUENCE SEQ2
INCREMENT BY 10
START WITH 10
MINVALUE 0
MAXVALUE 9999
NOCACHE
CYCLE;

Creation of Decremental Sequence:-


CREATE SEQUENCE SEQ3
INCREMENT BY-1
START WITH 10
MINVALUE 0
MAXVALUE 10
NOCACHE
NOCYCLE;

Modifying a Sequence:-
The ALTER command can be used to change the present status of a SEQUENCE.
The ALTER SEQUENCE command can be used to change………
Increment Value
Maximum Value
Minimum Value
Cycle Option
Cache Option

Syntax:-
ALTER SEQUENCE sequence
[INCREMENT BY n]
[{MAXVALUE n| NOMAXVALUE}]
[{MINVALUE n| NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n |NOCACHE}];

-106- Naresh i Technologies


Oracle 11g

EXAMPLE:-
Alter SEQUENCE TDept_DeptNo_Seq
INCREMENT BY10
MAXVALUE 500
NOCACHE
NOCYCLE;

Guidelines for Modifying a Sequence:-


You must be the owner or have the ALTER privilege for the sequence modify it.
Only future sequence numbers are affected by the ALTER SEQUENCE statement.
The START WITH option cannot be changed using ALTER SEQUENCE.
The sequence must be dropped and re-created in order to restart the sequence at a
different number.

Viewing the Current value of a Sequence:-


Select SEQ1.Currval from Dual;

Removing a Sequence:-
Remove a sequence from the data dictionary by using the DROP SEQUENCE statement.
Once removed, the sequence can no longer be referenced.

DROP SEQUENCE TDept_DeptNo_Seq;

Remember:-
The owner of the sequence or have the DROP ANY SEQUENCE privilege to remove it.
Once removed, the sequence can no longer be referenced.
The Data Dictionary in which the information of SEQUENCES are stored is
USER_OBJECTS.

Select Object_Name From User_Objects


Where Object_Name Like ‘SEQ1’
The setting of the SEQUENCE can be confirmed by selecting on USER_SEQUENCES
catalog.

-107- Naresh i Technologies


Oracle 11g

Select Sequence_Name,Min_Value,Max_Value,Increment_By,
Last_Number From User_Sequences
Where Sequence_Name= ‘SEQ1’;

VIEWS

Data abstraction is usually required after a table is created and populated with data.
Data held by some tables might require restricted access to prevent all users from
accessing all columns of a table, for data security reasons.

Such a security issue can be solved by creating several tables with appropriate columns
and assigning specific users to each such table, as required. This answers data security
requirements very well but gives rise to a great deal of redundant data being resident
in tables, in the database.To reduce redundant data to the minimum possible, Oracle
provides using Virtual tables which are Views.

VIEW DEFINITION:-

A View is a virtual table based on the result returned by a SELECT query. The content
of which is taken from table with the help of a query.

The most basic purpose of a view is restricting access to specific column/rows from a
table thus allowing different users to see only certain rows or columns of a table.

Composition Of View:-

A view is composed of rows and columns, very similar to table. The fields in a view are
fields from one or more database tables in the database.

SQL functions, WHERE clauses and JOIN statements can be applied to a view in the
same manner as they are applied to a table.

-108- Naresh i Technologies


Oracle 11g

View storage:-

A view is not a part of the physical schema like other ordinary tables, it is a dynamic,
virtual table computed or collated from the data available in the database. Changing
the data in a base table alters the data shown by the view.

Oracle does not store the view data. It recreates the data, using the view’s SELECT
statement, every time a user queries a view.
A view is stored only as a definition in Oracle’s system catalog.

When a reference is made to a view, its definition is scanned, the base table is opened
and the view is created on top of the base table.This, therefore, means that a view
never holds data, until a specific call to the view is made. This reduces redundant data
on the HDD to a very large extent.

Advantages Of View:-

Security:- Each user can be given permission to access only a set of views that
contain specific data.

Query simplicity:- A view can draw from several different tables and present it as a
single table turning multiple table queries into single table queries against the view.

Data Integrity:- If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets specified integrity constraints.

Disadvantage of View:-

Performance:- Views only create the appearance of the table but the RDBMS must
still translate queries against the views into the queries against the underlined source
tables. If the view is defined on a complex multiple table query then even a simple
query against the view becomes a complicated join and takes a long time to execute.

Types of Views :-

Simple Views

-109- Naresh i Technologies


Oracle 11g

Complex Views

Simple Views :-

a View based on single table is called simple view.

Syntax:-

CREATE VIEW <View Name> AS


SELECT<ColumnName1>,<ColumnName2>
FROM <TableName>
[WHERE <COND>]
[WITH CHECK OPTION]
[WITH READ ONLY]

CREATE VIEW V1
AS
SELECT EMPNO,ENAME,SAL,COMM FROM EMP ;

Views can also be used for manipulating the data that is available in the base
tables[i.e. the user can perform the Insert, Update and Delete operations].

Views on which data manipulation can be done are called Updateable Views.
If an Insert, Update or Delete SQL statement is fired on a view, modifications to data in
the view are passed to the underlying base table.

For a view to be updatable,it should meet the following criteria:

Views defined from Single table.

If the user wants to INSERT records with the help of a view, then the PRIMARY KEY
column(s) and all the NOT NULL columns must be included in the view.

INSERTING RECORD INTO BASE TABLE THROUGH VIEW :-

INSERT INTO V1 VALUES(1,’A’,5000,200) ;

-110- Naresh i Technologies


Oracle 11g

UPDATING RECORD IN BASE TABLE THROUGH VIEW :-

UPDATE V1 SET SAL=2000 WHERE EMPNO=1;

DELETING RECORD FROM BASE TABLE THROUGH VIEW:-

DELETE FROM V1 WHERE EMPNO=1;

WITH CHECK OPTION :-

If VIEW created with WITH CHECK OPTION then any DML operation through that view
violates where condition then that DML operation returns error.
CREATE VIEW V2
As
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP
WHERE DEPTNO=10
WITH CHECK OPTION ;

INSERT INTO V2 VALUES(2323,’RAJU’,4000,20) ;

The above INSERT returns error because view based 10 th dept but employee joined in
20th dept.

COMPLEX VIEWS :-

A view is said to complex view

If it based on more than one table


Query contains
aggregate functions
DISTINCT,GROUP BY or HAVING clause

-111- Naresh i Technologies


Oracle 11g

Sub-queries
Constants,Strings or Values Expressions
UNION,INTERSECT,MINUS operators.

Example :-

CREATE VIEW V3
AS
SELECT E.EMPNO,E.ENAME,E.SAL,D.DEPTNO,D.DNAME,D.LOC
FROM EMP E JOIN DEPT D
USING(DEPTNO) ;
CREATE VIEW V2
AS
SELECT DEPTNO,SUM(SAL) SUMSAL FROM EMP
GROUP BY DEPTNO;

Destroying a View:-

The DROP VIEW command is used to destroy a view from the database.

Syntax:-

DROP VIEW<viewName>

Example :-

DROP VIEW V1;

Querying VIEWS information :-

USER_VIEWS :- maintains information about views created by user.

SYNONYMS

-112- Naresh i Technologies


Oracle 11g

A synonym is another name or alternative name for a table.


Synonyms are created
If tablename if lengthy
To provide local transparency for remote objects

Syntax:-
CREATE SYNONYM <NAME> FOR <TABLENAME>;
Example :-
CREATE SYNONYM EMP FOR EMPLOYEE_INFORMATION;

Public Synonyms:-
You can also create a public synonym for a table. When you do this , all users see the
synonym.

CONNECT system/manager
GRANT CREATE PUBLIC SYNONYM TO store;
CONNECT store/store_password
CREATE PUBLIC SYNONYM products FOR store.products;
If you connect as steve, who has the SELECT privilege on store.products, you can now
retrieve rows from store.products through the products public synonym:

CONNECT steve/button
SELECT *
FROM products;

Indexes
When looking for a particular topic in a book, you either scan the whole book, or you
can use the index to find the location. An index for a database table is similar in
concept to a book index, except that database indexes are used to find specific rows in
a table.
Oracle server uses following methods to locate the desired information
1 Table Scan2 Index Scan

-113- Naresh i Technologies


Oracle 11g

In table scan oracle scans the entire table to locate the desired information.
In index scan oracle uses index to locate the place that holds the required data and
then jumps to that place to get required data. This is much faster than table scan.
How Does Indexing Work :-
When an index is created on a table, oracle internally forms a two dimensional matrix
that contains
1 Data extracted from the column on which index is created
2 Physical Address of the record (rowid)
When an SQL query that has a WHERE clause based on the column on which index is
fired , oracle finds the value in index and locates the record in the table using ROWID .
TYPES OF INDEXES :-
B-tree Indexes
Bitmap Indexes
B-TREE INDEXES :-

Types of B-TREE indexes :-


Simple Index
Composite Index
Unique Index
Function Based Index
WHEN TO USE B-TREE INDEXES :-
1 if table contains huge amount of data
2 when a query retrieves <=10 percent of the total rows in a table.
3 if column for the index contains a wide range of values.
4 A good candidate for B-tree indexing would be a column containing a unique value
for each row ex:- SSN
5 on the common columns that used in JOIN operation.

Simple B-tree Index:-


If index is created on single column then it is called simple index.
Syntax:-
CREATE [UNIQUE] INDEX index_name ON
table_ name (column_name )
Ex :- CREATE INDEX I1 ON EMP(SAL)
WHEN ORACLE INVOKES INDEX
A SELECT query with a WHERE clause spceicifed on column on which index is created
A SELECT query with ORDER BY clause specified on column on which index is created

-114- Naresh i Technologies


Oracle 11g

WHEN ORACLE DOESN’T INVOKE INDEX :-


SELECT query is fired without a WHERE clause
SELECT query is fired with WHERE clause specified on the column on which index is
not defined
SELECT query is fired with ORDER BY clause specified on the column on which index is
not defined.
SELECT query is fired with a WHERE clause with a != condition.
SELECT query is fired with IS NULL or IS NOT NULL operators
COMPOSITE B-TREE INDEX :-
If an index is created on multiple columns then it is called composite index.
Ex :- CREATE INDEX I2 ON EMP(DEPTNO,JOB)
Oracle server uses above index when SELECT query with WHERE is based on leading
column of index is fired.

UNIQUE INDEX :-
UNIQUE index doesn’t allow duplicate values into the column on which INDEX is
created.
Example :-
CREATE UNIQUE INDEX I3 ON DEPT(DNAME)
NOTE:-
PRIMARY KEY columns and UNIQUE columns are automatically indexed by ORACLE.
ORACLE automatically creates UNIQUE index on PRIMARY KEY and UNIQUE columns.

FUNCTION BASED INDEXES :-


There are times when even though an index exists, oracle doesn’t use it and instead
follows table scan. This is usually happens when index created on a column, but the
SQL query reference that column with a function or arithmetic expression.
For example , an index is created on the City column of the Customers table and the
following query is fired to retrieve all those row who belong to MUMBAI
SELECT * FROM CUSTOMER WHERE UPPER(city)=’MUMBAI’;
Above query reference the City column along with UPPER function and hence oracle
doesn’t use the index.
To overcome such issue, oracle provides function based index
CREATE INDEX I4 ON CUSTOMER (UPPER(CITY));

-115- Naresh i Technologies


Oracle 11g

In addition, the database administrator must set the initialization parameter


QUERY_REWRITE_ENABLED to true (the default is false) in order to take advantage of
function – based indexes.
The following query example sets QUERY_REWRITE_ENABLED to true:
CONNECT system/manager
ALTER SYSTEM SET QUERY_REWRITE_ENABLED=TRUE;
REVERSE INDEXES :-
In the index leaf block , Oracle stores the index key value and ROWID.
Assume that there is an unique index on custid , suppose 3 individuals concurrently hit
the database to insert rows with customer numbers 101,102,103 then index entries
are stored in same leaft block , which causes buffer busy waits.
If the index is reverse unique index then the entries will be stored in different leaft
block
Example :-
CREATE INDEX I7 ON CUSTOMER(CUSTID) REVERSE ;
NOTE :-
A normal index cannot be rebuild as a reverse key index. The same can be achieved
using CREATE INDEX command.

BITMAP INDEXES :-
Bitmap indexes are typically used in Data Warehouse.
Bitmap indexes are created on low cardinality columns.
Bitmap indexes are useful when data is not modified by concurrent transactions.
Bitmap is used for each key value, the bitmap enables the database to locate a row.
A mapping function converts bitmaps to rowids

Ex ample :-

CREATE BITMAP INDEX I6 ON EMP(JOB);

Modifying an Index:-
ALTER command is used to Modify an INDEX.
Example :-
ALTER INDEX I1 RENAME TO I10
Dropping an Index:-

-116- Naresh i Technologies


Oracle 11g

SYNTAX :-
DROP INDEX <NAME>
EXAMPLE :-
DROP INDEX I1
Retrieving index information :-
USER_INDEXES :-
Maintains information about indexes .

USER_IND_COLUMNS :-
Maintains information about on which columns indexes are created.
MATERIALIZED VIEWS

A materialized view is a database object that contains the results of a query unlike
normal views that only contains the query definition and not the results.

Materialized views are usually a choice when creating summary tables on aggregate of
a table’s data.

A materialized view can query tables, view’s and other materialized views.

A materialized 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.

Since Materialized view does not contain up-to-the –minute information. When an
ordinary view is queried, the data retrieved includes changes made up to the last
committed transaction.However, when an materialized view is queried the data
retrieved would be at a state when the view was created or last refreshed.

The commonly created materialized views are:


Primary Key
Row ID
Syntax:-
CREATE MATERIAIZED VIEW <schema.Name>
REFRESH [FAST|COMPLETE|FORCE][ON DEMAND|COMMIT]

-117- Naresh i Technologies


Oracle 11g

START WITH DATE


NEXT DATE
WITH [PRIMARY KEY|RowID]

REFRESH:-
Since the materialized view is built on underlying data that is periodically changed,
specify how and when to refresh the data in the view. The following keywords in the
REFRESH clause can also be used to create a schedule for recurring refresh operations:

FAST: - Updates only the values in the materialized view, assuming that some
preconditions are met.

COMPLETE:- Recreates the view completely

FORCE: - Does a FAST refresh if possible and a COMPLETE refresh if the preconditions
for a FAST refresh are not available.

ON COMMIT:- Causes a refresh to occur whenever the underlying data is changed and
the change is committed.

ON DEMAND:- Performs a refresh when it is scheduled or explicitly called.

START WITH DATE:- Indicates the date and interval at which the materialized view is
to be refreshed

NEXT DATE:- Indicates the time and interval at which the materialized view is to be
refreshed next

WITH PRIMARY KEY: - Indicates whether the materialized view is based on Primary
Key

WITH ROWID:- Indicates whether the materialized view is based on RowID.

Primary Key Materialized Views:-

Primary key materialized views allow materialized view master tables to be reorganized
without affecting the eligibility of the materialized view for fast refresh.

-118- Naresh i Technologies


Oracle 11g

Such materialized view is based on the primary key of the master table instead of
RowID.

PRIMARY KEY is the default option.

Example :-

CREATE MATERIALIZED VIEW MV1


REFRESH ON COMMIT
START WITH SYSDATE
NEXT SYSDATE+7
AS
SELECT DEPTO,SUM(SAL) SUMSAL FROM EMP
GROUP BY DEPTNO ;

RowID Materialized Views:-

RowID materialized views should have a single master table and cannot contain any of
the following:
Distinct or aggregate functions
GROUP BY
Subqueries
Joins and Set operations

The following statement creates the RowID materialized view on table Empoyees:
Example:-
CREATE MATERIALIZED VIEW mv_rowid_Employees
REFRESH ON COMMIT
WITH RowID
AS SELECT *FROM Employees;

TABLE PARTITIONING :-

-119- Naresh i Technologies


Oracle 11g

As the number of rows in your table grows, the meanagement and performance
impacts will increase. Backups will take longer, recoveries will take longer and queries
on that will take longer.
Administrative and performance issues can be simplified by seperating rows of a single
table into multiple parts.

Dividing a table’s data in this manner is called partitioning the table, and table is called
partitioned table and parts are called partitions.

Partitioning is useful for very large tables.

Partitioning is based on particular column , the column on which table is partitioned is


called partition key.

Advantages :-

 The performance of queries against the table may improve.


 The tables may be easier to manage.
 Backup and recover operations may perform better.
 Improves availability.

a table can be partitioned in different ways

1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION

RANGE PARTITION:-

which record assinged to which partition depends on range of the partition key.

Example :-

CREATE TABLE EMP_RANGE


(EMPNO NUMBER(4) ,

-120- Naresh i Technologies


Oracle 11g

ENAME VARCHAR2(20) ,
SAL NUMBER(7,2)
)
PARTITION BY RANGE(SAL)
(
PARTITION P1 VALUES LESS THAN(2000) ,
PARTITION P2 VALUES LESS THAN(4000),
PARTITION P3 VALUES LESS THAN(MAXVALUE)
);

Employee whose salaries less than 2000 all those records are assinged to partition P1.

Employee whose salaries less than 2000 all those records are assinged to partition P2 .

MAXVALUE is a keyword , any data that could not be stored in earlier partitions are
assigned to partition P3.

LIST PARTITION :-
Which record is assinged to which partition depends on value of partition key value.

CREATE TABLE EMP_LIST


(EMPNO NUMBER(4) ,
ENAME VARCHAR2(20),
JOB VARCHAR2(20)
)
PARTITION BY LIST(JOB)
(
PARTITION P1 VALUES (‘CLERK’) ,
PARTITION P2 VALUES(‘MANAGER’) ,
PARTITION P3 VALUES (DEFAULT)
);

HASH PARTITION :-

-121- Naresh i Technologies


Oracle 11g

A Hash paritition determines the physical placement of data by applying hash function
on partition key .

CREATE TABLE EMP_HASH


(EMPNO NUMBER(4) ,
ENAME VARCHAR2(20) ,
SAL NUMBER(7,2) ,
DEPTNO NUMBER(2)
)
PARTITION BY HASH(DEPTNO)
PARTITIONS 4;

CREATING SUBPARTITIONS :-

We can create subpartitions that is, paritions of partitions. You can use subpartitions to
combine all types of partitions like range partitions, hash partitions,list partitions.

Example :-

CREATE TABLE EMP_RANGE_HASH


(EMPNO NUMBER(4) ,
ENAME VARCHAR2(20) ,
SAL NUMBER(7,2) ,
DEPTNO NUMBER(2)
)
PARTITION BY RANGE(SAL)
SUBPARTITION BY HASH(DEPTNO)
SUBPARTITIONS 4
(PARTITION P1 VALUES LESS THAN(2000) ,
PARTITION P2 VALUES LESS THAN(4000) ,
PARTITION P3 VALUES LESS THAN(MAXVALUE)
)

MANAGING PARTITIONS :-

-122- Naresh i Technologies


Oracle 11g

Partitions can be dropped , new partitions can be added , and two partitions can be
merged.

DROPING PARTITION :-

ALTER TABLE EMP_RANGE DROP PARTITION P3;


ADDING NEW PARTITION :-

ALTER TABLE EMP_RANGE


ADD PARTITION P3 VALUES LESS THAN(6000) ;

MERGING TWO PARTITIONS INTO ONE PARTITION :-

ALTER TABLE EMP_RANGE


MERGE PARTITION P2,PARTITION P3 INTO PARTITION P3;

USER DEFINED TYPES :-

“ TYPE “ keyword is used to create user defined datatype.

Table contains user defined types are called OBJECT TABLES.

Syntax :-

CREATE TYPE <NAME> AS OBJECT


(COLNAME DATATYPE(SIZE) ,
COLNAME DATATYPE(SIZE) ,
-----------------
);

Example :-

-123- Naresh i Technologies


Oracle 11g

CREATE OR REPLACE TYPE ADDR AS OBJECT


(HNO VARCHAR2(20) ,
STREET VARCHAR2(20) ,
CITY VARCHAR2(20),
STATE CHAR(2));

CREATING OBJECT TABLE :-

CREATE TABLE CUST


(CID NUMBER(2) ,
CNAME VARCHAR2(20) ,
CADDR ADDR
);

INSERTING RECORD INTO OBJECT TABLE :-

INSERT INTO CUST VALUES(1,’RAJU’,


ADDR(‘102A’,’AMEERPET’,’HYD’,’AP’)) ;

VARRAYS :-

A VARYING ARRAY allows you to store array of values of a


record
you can create varray based on object type or Oracle standard datatype such as
NUMBER .

Example :-

CREATE OR REPLACE TYPE PHONE_ARRAY AS VARRAY(2) OF NUMBER(10) ;

CREATING TABLE BASED ON VARRAY :-

CREATE TABLE CUST


(CID NUMBER(2) ,
CNAME VARCHAR2(20) ,

-124- Naresh i Technologies


Oracle 11g

CPHONE PHONE_ARRAY
);

INSERTING VALUES INTO VARRAY :-

INSERT INTO CUST VALUES(1,’JAMES’,


PHONE_ARRAY(9878787877,6767673663));

NESTED TABLE :-

Whereas varying array have a limited number of entries , a


Second type called NESTED TABLE has no limit on the number
Of entries per row.

A nested table as its name implies a table within a table.It is a


table that is represented as a column within in another table.

Example :-

CREATE TYPE NEST_TYPE AS TABLE OF ADDR ;

Using NESTED TABLE :-

CREATE TABLE CUST


(CID NUMBER(2) ,
CNAME VARCHAR2(20) ,
CADDR NEST_TYPE)
NESTED TABLE CADDR STORE AS NEST_TYPE_TAB ;

INSERTING VALUES INTO NESTED TABLE :-

INSERT INTO CUST VALUES(1,’VIJAY’,


NEST_TYPE(ADDR(‘100A’,’SRNAGAR’,’HYD’,’AP’) ,
ADDR(‘200B’,’SRNAGAR’,’HYD’,’AP’)));

USER_TYPES :-

-125- Naresh i Technologies


Oracle 11g

Which maintains information about TYPES created by user.

-126- Naresh i Technologies


Oracle 11g

Analytic Functions

Analytic Functions are commonly used to compute cumulative, moving, centered and
reporting aggregates.
Oracle provides several analytic functions that help compute an aggregate value based
on a group of rows.
Analytic Functions provided by Oracle open up a whole new way of looking at the data.
It helps remove a lot of procedural code and complex code spec that would have taken
a long time to develop, to achieve the same result.
Whatever an analytic function does, can be done by using SQL, with the help of joins
and subqueries. However, an analytic function always does it faster, when compared to
native SQL.
Example:-
The OrderDetails table holds the order details of all the products that were sold. It is
desired to display the total Order Value against each OrderNo. Every Order in this table
is broken down into Products for that order.
SELECT OrderNo, SUM(Cost) “Order Value” FROM
OrderDetails
GROUP BY OrderNo ORDER BY OrderNo;

Example:-
It is desired to display the total Order Value against each OrderNo along with product
details.
SELECT OrderNo, ProductName, Cost, SUM(Cost)
OVER (PARTITION BY OrderNo) “Order Value”
FROM OrderDetails ORDER BY OrderNo,Cost;

Example:-
It is desired to display the total Order Value against each OrderNo along with product
details for all the products except Products named TV and AC.

SELECT OrderNo, productName, Cost, SUM(Cost)


OVER(PARTITION BY OrderNo) “Order Value”
FROM OrderDetails
WHERE ProductName NOT IN (‘TV’, ‘AC’)
ORDER BY OrderNo, Cost;

-127- Naresh i Technologies


Oracle 11g

Getting Started With Analytic Functions:-


Oracle provides the following Analytic Functions.
AVG
CORR
COVAR_POP
COVAR_SAMP
COUNT
CUME_DIST
DENSE_RANK
FIRST
FIRST_VALUE
LAG
LAST
LAST_VALUE
LEAD
MAX
MIN
NTILE
PERCENT_RANK
PERCENTILE_CONT
PERCENTILE_DISC
RANK
RATIO_TO_REPORT
STDDEV
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
VAR_SAMP
VARIANCE
Syntax:-
<AnalyticFunctionName>(<Argument1>,<Argument2>,….)
OVER(<Query Partition Clause>
<Order By Clause>
<Windowing Clause>
Where,
Arguments:

-128- Naresh i Technologies


Oracle 11g

Analytic functions accept 0 to 3 arguments.


Query Partition Clause:

The PARTITION BY clause logically breaks a single result set into N groups, according
to the criteria set by the partition expressions.
The words partition and group are used synonymously here.
The analytic functions are applied to each group independently.
Order By Clause:
The ORDER BY clause specifies how the data is sorted within each group [partition].
This will definitely affects the outcome of any analytic function.

Windowing Clause:
The windowing clause allows defining a sliding or anchored window of data, on which
the analytic function will operate, within a group.

Partition By, Over, Order By Clauses:


The data available in the OrderDetails table need to be reported in the following
format:
ProductName OrderNo Cost Orderwise Running Total
Product wise Running Total

This report displays a row by row cumulative order-wise total [Order Wise Running
Total], with each such row including a summation of the previous row’s price [Product
Wise Running Total].

SELECT ProductName, OrderNo, Cost


SUM (Cost)
OVER (ORDER BY OrderNo, productName)
“Order Wise Running Total”, SUM(Cost)
OVER(PARTITION BY OrderNo ORDER BY ProductName)
“Product Wise Running Total”
FROM OrderDetails
ORDER BY OrderNo, ProductName;

Row_Number:-

-129- Naresh i Technologies


Oracle 11g

Example:-
A customer can buy multiple products. An order can therefore be made up of a set of
products.
The organization wants to know the top two expensive products that a customer
bought on order basis.
SELECT * FROM (SELECT OrderNo, ProductName, Cost,
ROW_NUMBER()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts<=2;

Dense_Rank:-
The organization wants to rank the top four expensive products that a customer bought
on order basis.
SELECT * FROM (SELECT OrderNo, ProductName, Cost,
DENSE_RANK()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts <=4
ORDER BY OrderNo, Cost DESC;

Rank:-
The same query is fired using RANK function retrieve a different output.
SELECT * FROM (SELECT OrderNo, ProductName, Cost, RANK()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts <=4
ORDER BY OrderNo, Cost DESC;

Windowing Clause Using Rows:-


Example:-
Create a report that displays sliding total computed as the sum of the current product’s
price with the preceding two product’s prices within an Order.

-130- Naresh i Technologies


Oracle 11g

To achieve this,
Create a sliding window within a group. In this case the group would be OrderNo
Compute the sum of the current row’s Cost column plus the Cost of the previous 2
rows in that group
The windowing clause allows doing exactly this. It allows defining a sliding or anchored
window of data, on which the analytic function operates, within a group.
The default window is anchored window that simply begins at the very first row of a
group and continues to the current row.
Windows can be used for:
RANGES of data values
ROWS offset from the current row
An ORDER BY clause in an analytic function adds a default window clause of RANGE
UNBOUNDED PRECEDING which means all the previous rows available in a partition are
considered.

SELECT OrderNo, ProductName, Cost,


SUM(Cost) OVER (PARTITION BY OrderNo
ORDER BY ProductName ROWS 2PRECEDING)
“Sliding Product Price”
FROM OrderDetails
ORDER BY OrderNo, ProductName;

Windowing Clause Using Range:-


Create a report that computes the average of product prices which have been ordered
within 50 days preceding the current product’s OrderDate.
This can be achieved using Range windows.
Go 50 days back from the current row’s OrderDate
Count this rows within this rangw
SELECT ProductName, OrderDate, OrderDate-50 “Prior50Days”,
AVG(Cost)OVER
(ORDER BY OrderDate ASC RANGE 100 PRECEDING) “Average”
FROM OrderDetails
ORDER BY OrderDate ASC;

Example:-
Suppose it is desired to determine the average of product prices of 5 products ordered
prior to the current product including the current product in the average.

-131- Naresh i Technologies


Oracle 11g

This can be achieved using Row windows. Row windows allow including physical
number of rows in the window.
SELECT ProductName, OrderDate, Cost, AVG(Cost)
OVER (ORDER BY OrderDate
ROWS 5 PRECEDING) “Avg5ProductsAbove”
FROM OrderDetails
ORDER BY OrderDate;

Lag And Lead:-


Create a report that displays order-wise products, their OrderDate, the last time [date
and number of days] when a product was ordered before the current OrderDate and
the next time [date and number of days] the product was ordered after the current
OrderDate.
SELECT OrderNo, ProductNmae,OrderDate, LAG(OrderDate, 1)
OVER(PARTITION BY ProductName
ORDER BY OrderDate, ProductName) “Last Order Date”,
OrderDate – LAG(OrderDate, 1)
OVER(PARTITON BY ProductName
ORDER BY OrderDate, ProductName) “Last No Of Days”,
LEAD(OrderDate, 1)
OVER(PARTITON BY ProductName
ORDER BY OrderDate, ProductName) “Next Order Date”,
LEAD(OrderDate, 1)
OVER(PARTITION BY ProductName
ORDER BY OrderDate, ProductName) – OrderDate
“Next No Of Days”
FROM OrderDetails
ORDER BY OrderNo, OrderDate;

First_value And Last_value:-


Example:-
Display order wise products ordered by customers along with the product price and the
product names of the products that had lowest and the highest prices within that order.
This can be achieved using the FIRST_VALUE and LAST_VALUE functions. These
functions allow selecting the first and last rows from a group.
SELECT OrderNo, ProductName, Cost,
FIRST_VALUE(ProductName)

-132- Naresh i Technologies


Oracle 11g

OVER(PARTITON BY OrderNo
ORDER BY Cost ASC) AS “LOW Priced Product”,
FIRST_VALUE(ProductName)
OVER(PARTITION BY OrderNo
ORDER BY Cost DESC) AS “High Priced Product”
FROM OrderDetails
ORDER BY OrderNo, ProductName;

First And Last:-


Display order wise products ordered by customers along with the product price and the
lowest and the highest priced products within that order.
This can be achieved by using the FIRST and LAST functions.
SELECT OrderNo, ProductName, Cost,
MIN(Cost) KEEP (DENSE_RANK FIRST ORDER BY Cost)
OVER(PARTITION BY OrderNo)“Lowest Priced Product”,
MAX(Cost) KEEP (DENSE_RANK LAST ORDER BY Cost)
OVER(PARTITION BY OrderNo) “Highest Priced Product”
FROM OrderDetails
ORDER BY OrderNo, Cost;

De-duplicate Table Data:-


To resolve such an issue, analytic functions can be used
This will be done as follows:
1.Write an analytic query that partitions the records on the basis of the CustomerNo
column
2.Use the ROW_NUMBER() function to allot numbers to the rows in each partition
If no duplicates are encountered, the partition will have only one row that is numbered
1
If duplicates are encountered, the duplicate rows will be numbered 2, 3 and so on
SELECT RowID, ROW_NUMBER()
OVER (PARTITION BY CustomerNo ORDER BY CustomerNo) RN
FROM Customers;
This query returns RowIDs that can be used to uniquely identify rows whilst deleting
them later.
3.Use this query as an inline view in another SQL query that uses a WHERE clause to
avoid all rows that are numbered 1 and thus return only the duplicates
SELECT RowID, RN FROM

-133- Naresh i Technologies


Oracle 11g

(SELECT RowID, ROW_NUMBER()


OVER(PARTITION BY CustomerNo ORDER BY
CustomerNo) RN
FROM Customers) WHERE RN >1;
4.Use DELETE query that uses the IN operator with the above SQL query as the source
to delete all the such duplicates
DELETE FROM Customers WHERE RowID IN
(SELECT RowID FROM (SELECT RowID, ROW_NUMBER() OVER(PARTITION BY
CustomerNo ORDER BY CustomerNo) RN
FROM Customers) WHERE RN>1);

-134- Naresh i Technologies

Вам также может понравиться