Oracle SQL Final

You might also like

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

ORACLE 11g

LOHIT MITRA
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

FRONT END:
It is nothing but an application through which data of a database is represented in a customized manner.
BACKEND:
It is nothing but a database where data is stored as well as processed.
DATA:
Data is nothing but a raw fact or figure through which an object cannot be identified.
Ex: - employee no, name, salary of an employee individually known as one-one data or attributes.
INFORMATION:
Organised collection of related data is known as information through which an object is clearly identified.
DATA-FILE:
Organised collection of related information is known as Data-File
Ex: - sales department, purchase department, admin department individually maintains their data files.
DATABASE:
“Organized collection of related data-files or information is known as a DATABASE.”

NOTE: Though data is a raw fact or figure through which an object can’t be identified but it is the minimum
requirement for building a database.

DATA – Attribute/ Column


INFORMATION – Row/ Tuple/ Record
DATAFILE – Table (Collection of ROWS and COLUMNS)
DATABASE – Data-warehouse/ Databank (Collection of DATAFILES/TABLES)

WHY DATABASE?
Database is basically maintained to keep track on day to day activities.
ADVANTAGES:
To know the asset, liability and profit of an organization.
Database has no scope (no limitations). It can be implemented on small scale industries to large scale
corporate houses.
MEDIAS TO MAINTAIN DATABASE:
 Database can be maintained using 3 different medias
o Paper/ cabinet file
o Spreadsheet (Excel)
o Database Management Systems (DBMS)
 DBMS or Database Management System is simply a software responsible to store, retrieve and
modify the data of a database on user’s request.

Page | 1 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

TYPES OF DATABASES:
 Till date computer world has seen 4 types of databases namely
1. NETWORK DATABASE
2. HIERARCHICAL DATABASE
3. RELATIONAL DATABASE
4. OBJECT RELATIONAL DATABASE
 The primary job of above databases is same i.e. to store data. But they are divided in 4 different
categories depending on their mechanism or architecture.
 So, above databases are pronounced as data architecture or data-models.
 Depending on support to the databases DBMS is also categorised in 4 types
1. N-DBMS (Network)
2. H-DBMS (Hierarchical)
3. R-DBMS (Relational)
4. OR-DBMS (Object Relational)

~o~

RELATIONAL DATABASE
 R-DBMS is not a software typically, rather than it is a concept or a theory developed by a scientist
JOHN EF. CODD.
 He prescribed 12 different rules to define a relational architecture.
 According to CODD any database supports 6 or more than 6 rules will be pronounced as “Relational
Database” and to manipulate the database R-DBMS type of software are required.
 If any database supports less than 6 rules will be pronounced as “General Database” and to
manipulate the database DBMS type of software are required.
 The software belonging to DBMS & R-DBMS are: -
1. RDBMS (>= 6) :- Oracle 6, 7.3 ; ACCESS ; SQL Server ; DB2 ; SYBASE ; INFORMIX
2. DBMS (<=6) :- FOXPRO ; D-BASE ; FOXBASE ; PARADOX.

NOTE: The rules prescribed by CODD was published in June, 1970 and the books name was “A RELATIONAL
MODEL OF DATA FOR LARGE SHARED DATABANKS.”
 The concept was taken from the hard-disk data storage mechanism.

Page | 2 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

RELATIONAL DATABASE:
 “Relational database is nothing but the organised collection of 2-dimentional tables or relations.”
 Consider the following example :-

EMPLOYEE TABLE
EMP NO. NAME SALARY DEPT. LOCALITY ADDRESS STATE
1 A 5200 Sales Cuttack 444,BD ODISHA
2 B 7300 Sales Cuttack 444,BD ODISHA
3 C 8000 Sales Cuttack 444,BD ODISHA
4 D 10000 Purchase Bhubaneswar 466,SN ODISHA
5 E 4500 Admin Rourkela SEC-2 ODISHA
6 F 6200 Purchase Bhubaneswar 466,SN ODISHA
7 G 7500 Purchase Bhubaneswar 466,SN ODISHA
8 H 8000 Admin Rourkela SEC-2 ODISHA
9 I 9000 Admin Rourkela SEC-2 ODISHA
(NON-RELATIONAL DATABASE)

 The above graphics shows a non-relational model of database architecture.


 In this type, data is present in only one module. So, data redundancy is very much high whereas
data security is less.
 To overcome this problem Relational data model is produced where the data are present in
different-different modules and among them a common attribute is found which is the relation
among the module.
 Let’s consider this example:
DEPT. CODE DEPT.NAME LOCALITY ADDRESS STATE
1A SALES CUTTACK 444,BD ODISHA
1B PURCHASE BHUBANESWAR 466,SN ODISHA
2C ADMIN ROURKELA SEC-2 ODISHA

COMMON ATTRIBUTE (LINKING COLUMN)

EMP NO. NAME SALARY DEPT. CODE


1 A 5200 1A
2 B 7300 1A
3 C 8000 1A
4 D 10000 1B
5 E 4500 2C
6 F 6200 1B
7 G 7500 1B
8 H 8000 2C
9 I 9000 2C
(RELATIONAL DATABASE)

Page | 3 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Above graphics shows the relational model of architecture.


 In relational model of architecture data is always present in different-different modules.
 Each module is known as a TABLE and each table has a relationship with another one which leads to less
data redundancy and high data security.
 Thus, many tables can be created and linked with each other by the common attribute and form a data-bank
or data-warehouse.
 Example : -

(RELATIONAL DATA MODULES/ DATA WAREHOUSES)

Page | 4 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

ORDBMS
 ORDBMS is basically a concept which is treated as the extended version of Relational Database.
Extra concept has been put that is “Object Concept”.
 Anything stored inside the Object Relational Database is treated as one-one objects.
 The primary advantage of OR-DB over R-DB is its memory management is proper.
 Object Relational Database supports the following features
o Class
o Object
o Abstraction
o Encapsulation
o Polymorphism
o Inheritance
o Exception handling
1. CLASS:
Class is nothing but a template, style or blueprint which doesn’t have any physical existence and it is
a collection of properties and behaviour of similar type of objects.
(Ex: Fan is a class whereas Khaitaan/bajaj/orpat are different-different objects.)
2. Object:
It is nothing but has its physical existence having its own property and behaviour. Object is
otherwise known as an instance of a class.
3. Abstraction:
Abstraction is a concept or mechanism through which the essential part of an object will be
represented hiding the background detail. Abstraction leads to data hiding which leads to data
security.
4. Encapsulation:
Wrapping of data members and member functions under one module is known as encapsulation
where each module known as class. Encapsulation leads to modularity.
5. Polymorphism:
It is a concept through which one object behaves differently in different circumstances depending
upon the requirement. It leads to flexibility.
6. Inheritance:
This is a concept through which data members and member functions of one object can be reused in
another. It leads to reusability and reusability leads to less amount of coding.
7. Exception handling:
This is a concept through which the user can handle the abnormal behaviours of a program.
Whenever an exception occurs during runtime; system control will move to exception block, user
handles the exception and exits out of the program normally.
 As because the ORDBMS supports the above features of OOPS its memory management is proper
and flexibility is more.
 The software belong to ORDBMS are ORACLE 8, 8i, 9i, 10g, 11g, 12c (latest)
o i -> for internet g -> grid
o I -> for intranet c -> cloud
 Features or advantages are
o Support for i-SQL + / SQL developers & TOAD (Tool for Oracle for Advance Development)
(GUI based) (SQL*PLUS is the CUI based)
o Support for OJAD (Oracle Java Developer) / J-Server
o Flashback table / User / Database.

Page | 5 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

ORACLE 11g
 When oracle is loaded, it is going to load 2 different languages
o SQL (Structured Query Language)
o PL/SQL (Procedural Language – an extension of SQL)
 The primary job of the above languages is same i.e. to manipulate the database. But they are categorized
in 2 different types depending upon their mechanism.
 SQL is an ANSI standard language responsible for manipulating the database interactively.
 Interactive means one command can be executed at one point of time.
 As because it is an ANSI standard language it is not only responsible to manipulate Oracle database but
also meant to manipulate any type of database currently available.

PL/SQL:
 Though PL/SQL is pronounced as a language but it is not a language typically rather than it is a
PROGRAM TECHNIQUE implemented on Oracle server to manipulate the database
programmatically using SQL commands.
 NOTE: To become a typical language a language must follow the following features
o IDENTIFIER
o LITERAL
o CONSTANT
o DELIMETER
o STATEMENTS

1. IDENTIFIER:
It is nothing but the naming convention of a memory location which holds a value for a
temporary period which value changes time to time.
2. LITERAL:
Any value assigned to an Identifier is known as a Literal. A literal may be anything such as
character, number, date, string etc.
3. CONSTANT:
It is basically a concept through which a value is assigned to an identifier in such a manner which
can’t be changed during runtime. In other words, it is said that “ALL CONSTANTS ARE LITERALS
BUT ALL LITERALS CAN NEVER BE CONSTANTS.”
4. DELIMETER:
These are nothing but some special symbols having special meaning inside the language
EX: { } ; ( ) etc.
5. STATEMENT:
Apart from above features a language must have its special statements or commands to
accomplish the specific job.

 PL/SQL is not treated as a typical language because it doesn’t have its own statements to
manipulate the database.
 It uses the statement of SQL to do so.

Page | 6 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SQL
 SQL is not a single language of its own rather than it is a combination of 5 different sub-languages.
1. Data Query Language (DQL)
2. Data Definition Language (DDL)
3. Data Manipulation Language (DML)
4. Transaction Control Language (TCL)
5. Data Control Language (DCL)
1. DQL:

 It is a sub language of SQL otherwise known as Data Retrieval Language (DRL) responsible for
extracting data from a table and display to the end-user.
 To do so DQL provides a statement called “select”.

2. DDL:

 It is otherwise known as Object Manipulation Language (OML) which is responsible for


manipulating the objects in ORACLE database
 ORACLE provides several different objects for customized database management such as
o Table
o View
o Synonym
o Sequence
o Index
o Type
 To create and manipulate above objects DDL provides the following statements
1. Create
2. Alter
3. Drop
4. Truncate
5. Rename
3. DML:

 DML is also known as Record Manipulation Language (RML) responsible to manipulate the
records of a table. To do so DML provides the following statements
1. Insert
2. Update
3. Delete

NOTE: The basic difference between ‘alter’ & ‘update’ is alter is meant for structural change whereas
update is meant for data change. Similarly, the difference between ‘truncate’ & ‘delete’ are truncate is
non-conditional physical deletion whereas delete is conditional logical deletion.
4. TCL:

 TCL is a sublanguage of SQL responsible to control the transactions (insert, update, delete)
made by the user in ORACLE database. Whenever any transaction is made, the transactions are
never saved unless a “save” command is issued or “discard” command is issued.

Page | 7 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 To do so TCL provides the following statements


o Commit
o Rollback
o Save point
5. DCL:

 ORACLE not only facilitate the user to create and manipulate objects in the ORACLE database
but also protects those objects from invalid users by creating or by allowing the user to create
‘schema’.
 To create and manipulate those schemas DCL provides 2 commands i.e.
o Grant
o Revoke

~O~

SELECT
 To perform select command or selection operation, ORACLE provides 3 different tables by default
o EMP
o DEPT
o SALGRADE
 These tables are available in a general user called SCOTT user.

NOTE: Apart from the SCOTT user another user is provided by the ORACLE called SYSTEM. System is a
SUPER-USER or a DBA USER responsible to control the database.

 To interact with the database from the client side, ORACLE provides an interface called SQL*PLUS.
Any command issued from the SQL*PLUS will navigate to the database. Then database will process
the command and send the output back to SQL*PLUS.
 Whenever ORACLE is invoked for the 1st time it shows a log in window having 3 options
o USER NAME
o PASSWORD
o HOST STRING

NOTE: HOST-STRING is optional but it becomes compulsory whenever user is working under multiple
database server architecture.

 ‘select’ is a powerful query statement responsible to extract data from one table or more than one
table; condition wise or non-condition wise.
 SYNTAX:

SELECT [DISTINCT] < * | COL1, COL2, COL3 ….. N >


FROM <TABLE NAME> ;

[ ] - optional
< > - compulsory
| - or

Page | 8 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Ex: select * from emp; or select ename, sal, job from emp;
 Select statement can perform 2 types of jobs
1. Selection
2. Projection
 Projection ca be possible in 2 different ways
1. Column wise projection or Column restriction
2. Row wise projection or Row Restriction
 Column restriction means those many columns are displayed which are commanded in the select
list
 Ex: select empno, ename, sal, job from emp;
o/p ->
EMPNO ENAME SAL JOB

 Whereas Row restriction means those many records are shown when a condition is satisfied.

NOTE : ‘ * ’ represents all the columns in the table.

WORKING WITH COLUMN ALIAS


 ALIAS – Duplicate name
 Column alias is basically a concept through which user can provide duplicate names to an existing
column to get a readable output.
 Column alias is basically imposed using 3 different methods
1. Select empno number, ename name, sal salary from emp;
2. Select empno as number, ename as name, sal as salary from emp;
3. (for multiple words)
Select empno as “employee number”, ename as “employee name” from emp;
NOTE: Whenever a column alias is represented in multiple words, it has to be kept in double quotes (“ ”).
Thus, it is not mandatory to give column name a valid name while creating a table and we can give any names like
col a, col b, col 1, col 2 etc.

 In ORACLE Double quote (“ ”) – column alias


Single quote (‘ ’) – character, string, date etc.

WORKING WITH COLUMN CONCATENATION


 Column Concatenation is a concept or a mechanism which can concatenate 2 or more than 2
columns to get a readable output.
 To do so SQL provides an operator “Double pipeline” ( || )
 Ex:
Select ename || ‘is working as’ || job || ‘and getting salary’ || sal as “manager info” from emp;

NOTE: In ORACLE characters, strings and date type of values always represented through single quotes whereas
column alias is represented in double quotes.

Page | 9 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

ARITHMATIC OPERATIONS THROUGH ‘SELECT’ STATEMENT (WORKING WITH


VIRTUAL COLUMN)

 ‘select’ statement supports the concept of formula which leads to a “virtual column”.
 Virtual column is such type of column which doesn’t have any physical existence and only meant for
display purpose.
 Ex: Suppose we want to add TA, DA, HRA columns to the existing emp table the following command
is given :- Select empno, ename, sal, sal*.1, sal*.11, sal*.12 from emp;
o/p -
EMPNO ENAME SAL SAL*.1 SAL*.11 SAL*.12

 Again for making the columns readable we use the column alias commands :-
Select empno, ename, sal, sal*.1 as ta, sal*.11 as da, sal*.12 as hra from emp;
o/p –

EMPNO ENAME SAL TA DA HRA

 Again if we want to add a ‘total’ column we can use the following commands :-
Select empno, ename, sal, sal*.1 as ta, sal*.11 as da, sal*.12 as hra, sal + (sal*.1) +(sal*.11) +
(sal*.12) as “total salary” from emp;
o/p –

TOTAL
EMPNO ENAME SAL TA DA HRA
SALARY

ROW–RESTRICTION THROUGH ‘SELECT’ STATEMENT


 Row restriction is a concept or a mechanism which can display those many records when a
condition is satisfied.
 To do so ‘select’ statement provides a clause called “WHERE”.
 Syntax of ‘select’ using where :-
SELECT <EXP>
FROM <TAB_NAME>
[WHERE <CONDITION>];

 < , >, <=, >=, <>/ != – Relational Operator


AND, OR, NOT – Logical operator
+ - * / – Arithmetic operator
 Ex:-
o Select * from emp
where sal<2000 AND sal>3000;
o Select * from emp
where job = ‘ANALYST’
o Select * from emp
where job = ‘MANAGER’ OR job = ‘SALESMAN’

Page | 10 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

o Select empno as no, sal as salary, ename as Name


where job = ‘MANAGER’
(where with column alias)
o Select * from emp
where deptno <> 20

NOTE: SQL statements are case insensitive but a character value or string value compared with a column is always
case sensitive. Ex: Select * from emp where job = ‘ANALYST’ (job = ‘analyst’ ERROR)

 Above examples are the examples of conventional operators. Apart from that some exclusive
operators are provided by SQL
o BETWEEN
o IN
o IS NULL
o LIKE

EXCLUSIVE OPERATORS:
 BETWEEN: (both inclusive) this operator is responsible for displaying the o/p between a given range
of value. This operator can be operated on any type of values i.e. number and date.
Ex select * from emp where sal BETWEEN 2000 AND 3000;
select * from emp where sal not BETWEEN 2000 AND 3000;
date(dd-mmm-yy): - select * from emp where hiredate BETWEEN ’01-jan-81’ AND ’31-dec-81’
select * from emp where hiredate not BETWEEN ’01-jan-81’ AND ’31-dec-81’

 IN-LIST (IN): (Extended version of ‘OR’) IN operator is otherwise known as “in-list” operator. It is
treated as the extended version of OR. This operator can be operated on any type of value i.e.
number, date, string etc.
Ex: - select * from emp where job IN (‘MANAGER’, ‘SALESMAN’, ‘CLERK’);
select * from emp where job not IN (‘MANAGER’, ‘SALESMAN’, ‘CLERK’);
select * from emp where sal IN (2000, 3000, 5000);

 IS NULL:
NULL: - “ NULL is a special type of value which is unassigned or inapplicable.”
To extract data depending upon NULL value user can use “IS NULL” operator.
Ex: - select * from emp where COMM is NULL;
select * from emp where COMM is not NULL;

 LIKE: LIKE operator is a powerful query operator responsible to extract data depending on the
character position.
To do so it provides 2 wildcard (special) characters
o % (Percentile)
o _ (Underscore)
Examples:
i. Select * from emp where ENAME like ‘s%’;
ii. Select * from emp where ENAME like ‘_ _i%h’;
iii. Select * from emp where ENAME like ‘%a%’;
iv. Select * from emp where ENAME not like ‘%a%’;

Page | 11 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

a. For displaying the records who are hired in the year 82 –


Select * from emp where HIREDATE like ‘%82’;
b. For displaying the records whose name doesn’t contain ‘s’
Select * from emp where ENAME not like ‘%s%’;
c. For displaying the records whose hiredate in February and December
Select * from emp where HIREDATE like ‘%FEB%’ or ‘%DEC%’;

~o~

Built-in (Predefined) functions in SQL


 Difference between PROCEDURES and FUNCTIONS: - Procedure and functions are block of
executable statements which may or may not accept arguments but Procedure never returns a
value, whereas functions always return value. ORACLE provides a series of built-in functions to
enhance the capability of SQL statements. The following is the built in function hierarchy :-

Page | 12 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SINGLE ROW FUNCTION: - These are the functions which accepts one value as an argument and returns
one value per row.
MULTI ROW FUNCTION: - Whereas multi row functions are those functions which accept multiple values
as arguments but returns one value per group.
CASE CONVERSION: - These functions are to convert case of a character or string and the functions are
1. Lower ()
2. Upper ()
3. Initcap ()
Ex:
SELECT LOWER (ENAME) FROM EMP;
SELECT LOWER (ENAME) AS NAME, INITCAP (JOB) FROM EMP;
NOTE: A single row function can accept 2 types of values as an argument
1. Column name
2. Static value [ select upper (‘odisha’) from dual; ] (‘odisha’ is a static value)

DUAL TABLE: - Whenever a static value is passed into a single row function, the output is supposed to be
displayed that many no. of times the no. of records available inside a table.
Ex : select LOWER (‘ODISHA’) from emp; will result 14 rows of the output.
But select UPPER (‘odisha’) from dual; will display the output only once.
The dual table is created for testing purpose.

CHARACTER MANIPULATION FUNCTIONS:


 These functions are required to manipulate character or string type, date type data. And the
functions are
1. CONCAT ( )
2. SUBSTR ( )
3. INSTR ( )
4. LTRIM ( )
5. RTRIM ( )
6. TRIM ( )
7. LENGTH ( )
8. SOUNDEX ( )

1. CONCAT ( ) : this function is required to concatenate 2 string values or 2 column values

Ex : select concat (ENAME, JOB) from emp;


select concat (concat (concat (concat (ename,' is getting '), sal),' and working as '), job) from emp;

2. SUBSTR ( ) : This function is required to extract specific number of characters from the specified
position of a string.
Syntax:
SELECT SUBSTR ( STRING / COLUMN, POSITION, [NO. OF CHARARCTERS] )
FROM TAB_NAME;

Page | 13 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Ex:
select substr (‘odisha’, 2)
Select substr (‘odisha’, 4,1)
Select substr (ENAME, 2,3) from emp;
3. LENGTH ( ): This function is required to return the length of a string including blank space.

Ex : select length (‘odisha’) from dual;


o/p – 6

4. 5. 6. LTRIM ( ) / RTRIM ( )/ TRIM ( ) : These functions are required to eliminate blank spaces from left
side or right side or both side of a specific string.

Ex: select LENGTH (LTRIM (‘ ODISHA )) from dual;


o/p – 7
select LENGTH (TRIM (‘ ODISHA ’)) from dual;
o/p – 6
7. SOUNDEX ( ) : This function is required to extract data from a table based on the pronunciation.
Soundex is called as ‘Sound by example’
Ex: select * from emp where SOUNDEX (ENAME) = SOUNDEX (‘SCOT’);
8. INSTR ( ) : This function is pronounced as “inside the string”. It is responsible to check whether a
character is available within the specified string or not and shows the position of that character in the
string. It returns numerical value.
Ex: select INSTR (‘ORRISSA’, ‘R’ ) from dual;
o/p – 2

NUMBER MANIPULATION FUNCTIONS:


These functions are required to manipulate number type of value and the functions are
1. ROUND ( )

2. TRUNC ( )

3. MOD ( )

4. NVL ( )

1. ROUND ( ) : This function is required to round a floating value integer wise or decimal type.
Ex: select round (76.568) from dual
o/p – 77
select round (76.568, 2) from dual
o/p – 76.57
select round (50.762, -2) from dual
o/p – 100
*-1 = 10 interval, -2 = 100 interval, -3 = 1000 interval and so on

Page | 14 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

2. TRUNC ( ) : This function required to truncate a floating no., integer wise or decimal wise.
Ex:
Trunc (45.678) o/p – 45
Trunc ( 45.678, 2) o/p - 45.67
Trunc (45.678, -1) o/p – 40
Trunc ( 99.678, -2) o/p – 0
Trunc (199.678, -2) o/p – 100
Trunc (199.888, -3) o/p – 0
3. MOD ( ) : This function is required to return the remainder of division
Ex: MOD(1600,300) o/p – 100
4. NVL ( ) : This function is required to convert a null value to a not null value. This is basically required to
perform any arithmetic operation with null value.
Ex: select EMPNO, ENAME, SAL, COMM, SAL+NVL (COMM,0) as “TOTAL SALARY” from emp;

DATE MANIPULATION FUNCTIONS


These are required to manipulate date type of values and the functions are : -

1. SYSDATE
2. CURRENT_DATE ( THESE THREE TAKES NO ARGUMENTS ONLY RETURNS )
3. SYSTIMESTAMP
4. ADD_MONTHS ( )
5. MONTHS_BETWEEN ( )
6. LAST_DAY ( )
7. NEXT_DAY ( )
8. ROUND ( )
9. TRUNC ( )

1. SYSDATE / CURRENT_DATE:
These functions are required to display the current date.
Ex: select sysdate/ current_date from dual; o/p – 25-MAR-17

2. SYSTIMESTAMP:
This function is required to display date and time simultaneously.
Ex: select systimestamp from dual;

3. ADD_MONTHS ( ) :
This function is required to add a specified no. of months in a pre-specified date. This function can also
add year in month format.
Ex: select add_months ( ’22-FEB-08’,6 )
O/P – 22-AUG-08

Page | 15 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

4. MONTHS_BETWEEN ( ) :
This function is required to return the months between 2 specified dates. It can also return year
difference.
Ex: select months_between ( ‘28-JAN-09’, ’22-JAN-08’)
O/P – 12.1935484

To convert into a round value, apply ‘TRUNC’


Select trunc (months_between ( ‘28-JAN-09’, ’22-JAN-08’)) from dual;
O/P – 12
5. LAST_DAY ( ) :
This function is going to return the last day of the month of a specified date.
Ex : select last_day ( sysdate ) from dual;
O/P – 31-MAR-17

6. NEXT_DAY ( ) :
This function is required to return the next day of a week’s specific date.
Ex : select next_day (sysdate, ‘Sunday’) from dual;

Q. Write a query which will display the date of ‘Monday’ after 6 months of a specified date.
Ans. Select next_day (add_months (sysdate, 6), ‘Monday’) from dual;

7. ROUND ( ) :
Round is a function responsible to round a date, month-wise or year-wise. If the date is rounded by
month we will check the day path and if the date is rounded by year we will check the month path.
Ex : SELECT ROUND (TO_DATE (’15-MAR-08’), ‘YEAR’) FROM DUAL;
O/P – 01-JAN-08
SELECT ROUND (TO_DATE (’15-MAR-08’), ‘MONTH’) FROM DUAL;
O/P – 01-MAR-08

8. TRUNC ( ):
This function is required to truncate a date month-wise or year-wise (BACKWARDS ONLY).
EX : SELECT TRUNC (TO_DATE(’31-DEC-17’),’YEAR’) FROM DUAL;

CONVERSION FUNCTIONS
 Conversion functions are those functions require to convert a value from one type to another type.
These are otherwise known as TYPECASTING functions.
 To know the conversion functions user must have the idea about the datatypes.
 ORACLE provides following datatypes either to declare a variable in PL/SQL or to declare column of a
table.
 These datatypes are :
1. CHAR (5)  LO*** (TAKES 5b OF MEMORY AS DECLARED 5 )
2. VARCHAR2 (4000)  LO (ALTHOUGH DECLARED 4000 BUT TAKES 2b MEMORY )
3. VARCHAR (2000)  LO (SUPPORTS UPTO 2000 LETTERS BUT VARCHAR2 SUPPORTS 4000)
4. NUMBER (3)  999
NUMBER (7,2)  99999.99
5. DATE

Page | 16 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Depending upon the above datatypes functions are


o TO_CHAR ( )
o TO_DATE ( )
o TO_NUMBER ( )

(LIFE CYCLE OF CONVERSION DATATYPES)

DATE TO CHARACTER (to _char):


This function is required to convert date to character or number to character.
SYNTAX: - TO_CHAR (DATE / NUMBER, ‘format’)

To convert date to character ORACLE provides a series of formatting strings and those are as follows:

DY  MON, TUE etc.


DAY  MONDAY

DD  22
DDTH  22ND
DDTHSP  TWENTY SECOND

MM  01
MON  JAN
MONTH  JANUARY

YY  92
YYYY  1992
YEAR  TWO THOUSAND EIGHT

EX: select initcap ( to_char ( hiredate ) ‘day ddth mon yyyy’) from emp;

Page | 17 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

NUMBER TO CHARACTER (to_char):


To convert number to character the formatting strings are
‘$99,999.99’ / ‘L99,999.99’

$  To prefix or suffix a dollar symbol


L  to prefix or suffix local currency
9  to represent a no. in character format.
,  thousand separator
.  decimal notation.
* NUMBER  RIGHT ALLIGN
DATE  CENTER ALLIGN
STRING  LEFT ALLIGN
Ex: select to_char (10000, '$99,999') from dual;

CHARACTER TO NUMBER (to_number):


This function is required to convert string type number to actual number.
Ex: select to_number (‘100’) from dual;
o/p - TO_NUMBER(‘100’)
100
Select ‘100’ from dual;

o/p - ‘100’
100  as 100 is a string here.

CHARACTER / NUMBER TO DATE (to_date):


The Oracle/PLSQL TO_DATE function converts a string to a date.
EX:
TO_DATE('2003/07/09', 'yyyy/mm/dd')
Result: date value of July 9, 2003

TO_DATE('070903', 'MMDDYY')
Result: date value of July 9, 2003

TO_DATE('20020315', 'yyyymmdd')
Result: date value of Mar 15, 2002

~O~

Page | 18 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

MULTI-ROW FUNCTIONS
 These are otherwise known as “Group functions” which are responsible to accept multiple values as an
argument but return one value per group.
 These functions are :
o MAX ( )
o MIN ( )
o AVG ( )
o SUM ( )
o COUNT ( )

 EX: SELECT SUM(SAL), MAX (SAL), MIN (SAL), AVG (SAL) FROM EMP;

 In the above example ‘EMP TABLE’ is treated as a group which will display SUM, MAX, MIN, AVERAGE of EMP
table.

WORKING WITH “GROUP BY” CLAUSE


 “Group by” is a clause of select statement which is responsible to segregate (divide) the table data in different-
different groups.

 This clause is basically meant for multiplication functions.

 SYNTAX:

SELECT < EXP > FROM < TAB_NAME >


[WHERE < CONDITION >]
[ GROUP BY < COL_NAME > [, COL_NAME,…. COL_N]];
 Ex:
SELECT DEPTNO, SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP
GROUP BY DEPT NO.
 Above example will display the department number wise sum, min, max, average of salaries. Above
example is an example of single column wise grouping.

WORKING WITH “COUNT ( )”


 COUNT ( ) is a multirow function which is responsible for counting the number of records of a group or counting
the no of values of a column.
 It accepts 2 arguments :-

o *  For counting all the no of records. (COUNTS NULL VALUES)


o Column_name  For counting the values of a column. (DOES NOT COUNT NULL VALUES)
 Ex:
SELECT DEPTNO, SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) COUNT ( * ) AS ‘’ NO OF RECORD(S)’’ FROM EMP
GROUP BY DEPT NO, JOB ;
 COUNT (*) FROM EMP; / COUNT (MGR) FROM EMP;
 Above example shows the department number wise sum, max, min, and average of salaries as well as number
of employees working in each group.

Page | 19 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “HAVING” CLAUSE


 Having clause is a clause of select statement responsible to restrict a group depending on a condition.
 The basic difference between ‘where’ and ‘having’ is where is meant for row restriction where as
having is meant for group restriction.
 SYNTAX:
SELECT <EXP>
FROM < TAB_NAME>
[ WHERE <CONDITION> ]
[ GROUP BY <COL_ NAME> ]
[ HAVING <GROUP_CONDITION> ];

 EX :
SELECT DEPTNO, JOB, SUM(SAL), MIN(SAL), MAX(SAL), AVG(SAL)
COUNT (*) AS “NO OF RECORD(S)”
FROM EMP
HAVING MAX (SAL) > 2000;

// FOR DISPLAYING DEPT. WISE, JOB WISE, SUM, MAX, MIN, AVERAGE SALARY AND NUMBER OF
EMPLOYEES OF THOSE TABLES WHOSE MAX (SAL) > 2000 //
Q. Write a query which will display dept. wise sum(sal), max(sal), etc. as well as no. of employees of those groups
whose max (sal) > 2000 and dept. no. <> 30.

Ans. SELECT DEPTNO, JOB, MAX(SAL), MIN(SAL), AVG(SAL), SUM(SAL)


FROM EMP
WHERE DEPTNO <> 30
GROUP BY DEPTNO, JOB
HAVING MAX (SAL) > 2000;

WORKING WITH “ORDER BY” CLAUSE


 “ORDER BY” clause is the last clause of ‘select’ statement responsible to arrange the records in a
proper order either in ascending order or in descending order.
 Ex:
Select EMPNO, SAL, JOB, FROM EMP
ORDER BY DEPTNO, SAL DESC;
SYNTAX OF FULL FLEDGED ‘SELECT’ STATEMENT:

SELECT <EXP>
FROM < TAB_NAME>
[WHERE <CONDITION>]
[ GROUP BY <COL_ NAME> ]
[ HAVING <GROUP_CONDITION> ]
[ ORDER BY <COL_NAME>[ASC/DESC] ];

~O~

Page | 20 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SUBQUERY
 “Subquery” is a concept or a mechanism implemented on ‘select’ statement, whenever a condition
value is unknown to the user.
 Subquery is otherwise known as NESTED QUERY.
 Subquery has 2 different parts
 INNER QUERY
 OUTER QUERY
 Inner query is a query which will evaluate the condition value and provide the output to outer
query for processing purpose.
 Whereas outer query is a query which will accept the value from inner query and display the
output.

TYPES OF SUBQUERY
 Depending on the value return from inner query to outer query, subquery is broadly categorized in
2 different types
1. SINGLE ROW SUBQUERY (Returns 1 value)
2. MULTI ROW SUBQUERY (Returns multiple value)
1. Single-row subquery is a type of subquery where inner query returns 1 value to the outer query for
processing.
Ex : display those records where Sal > BLAKE’S salary.

2. Multi-row subquery is a type of subquery where inner query returns more than 1 value to the outer
query for processing.
Ex : Display those records whose sal > all salaries of dept no. 20.

 SYNTAX:
SELECT < EXP >
FROM < TAB_NAME >
WHERE COL_NAME < OPERATOR >
(SELECT < COL_NAME > FROM < TAB_NAME > WHERE < CONDITION >);

 OPERATORS:

< , > , <= , >= , <> , =  SINGLE ROW OPERATORS

<ALL  Less than the minimum


>ALL  Greater than the maximum
<ANY  Less than the maximum  MULTIROW OPERATORS
>ANY  Greater than the minimum
=ANY  Also equals to the ‘IN’ operator
IN

Page | 21 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

EXAMPLES OF SINGLE ROW SUBQUERY: -


Q. Display those records whose salary > ‘ALLEN’
Ans. select * from emp where SAL > (select SAL from emp where ENAME = ‘ALLEN’);
Q. Display those records whose job is same as BLAKE but it should not display BLAKE’S record.
Ans. Select * from emp where JOB = (select JOB from emp where ENAME = ‘BLAKE’) and ENAME <>
‘BLAKE’;
Q. Display those records whose salary > ‘SMITH’ and < ‘ALLEN’.
Ans. Select * from emp where SAL > (select SAL from emp where ENAME = ‘SMITH’) and SAL < (select SAL
FROM EMP where ENAME = ‘ALLEN’);
OR
Select * from emp where SAL between (select SAL from emp where ENAME = ‘SMITH’) and (select SAL
from emp where ENAME = ‘ALLEN’);
Q. Display those records who are hired after JAMES.
Ans. Select * from emp where HIREDATE > (select HIREDATE from emp where ENAME = ‘JAMES’);
EXAMPLES OF MULTI ROW SUBQUERY: -
Q. Display those records whose salary > all salary of deptno 30.
Ans. Select * from emp where SAL >ALL (select SAL from emp where DEPTNO = 30);
Q. Display those records whose JOB is same as any job of deptno 30 but it should not display deptno 30’s
job.
Ans. Select * from emp where JOB =ANY (select JOB from emp where DEPTNO = 30) and DEPTNO <> 30;
Q. Display those records whose salary > ANY salary of deptno 20.
Ans. Select * from emp where SAL >ANY (select SAL from emp where DEPTNO = 20)
Q. Display those records whose salary > any salary of deptno 30 and job must be same as BLAKE.
Ans. Select * from emp where SAL >ANY (select SAL from emp where DEPTNO = 30) and JOB = (select JOB
from emp where ENAME = ‘BLAKE’);

NOTE: Though inner query is a select statement it can use any clause except ORDER BY clause.
Example: SELECT * FROM EMP WHERE SAL > ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30 ORDER BY
SAL DESC); will be false whereas SELECT * FROM EMP WHERE SAL > ANY (SELECT SAL FROM EMP WHERE
DEPTNO = 30) ORDER BY SAL DESC; will be true.

~O~

Page | 22 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SQL PLUS COMMANDS


 SQL PLUS is an environment which acts like an interface between the user and the database.
 As because it is an environment it has its own commands to manipulate itself.
 Whenever a valid SQL statement is issued from the SQL prompt; it never goes to the database directly rather
than it passes through a temporary memory called BUFFER.
 “BUFFER is an active temporary memory in client side which holds a SQL statement for a temporary period,
unless and until another statement is issued or the memory is explicitly cleared.”

(BUFFER MECHANISM)

1. ED/ EDIT: Above command is required to open the buffer memory in notepad editor.
2. RUN or “/”: To run the buffer memory.
3. SAVE: Above command is to save a statement in form of SQL file which is otherwise known as a script file.
The default path for the file is C:\app\computer name\product\11.2.0\dbhome_1\bin. User can also save a
file in user defined path also like C:\desktop\Newfolder\filename. To run the saved script-file, the command
is SQL> START <FILE_NAME> | @ <FILE_NAME>
4. CL BUFF / CLEAR BUFFER: Above command is to clear the buffer explicitly.
5. L / ; : To display the buffer content. L2  represents content at line 2.
6. SHOW USER : To show the current user.
7. CONNECT / CONN: For switching the users.

Page | 23 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DIFFERENCE BETWEEN SQL AND SQL*PLUS:


SQL SQL * PLUS
1. It is basically an ANSI standard language required to 1. It is basically an environment proprietary of ORACLE.
manipulate ORACLE DATABASE.
2. These commands can’t be abbreviated 2. These commands can be abbreviated.
3. These commands pass through buffer memory to 3. These commands never pass through buffer
database. memory.
4. These commands terminated by a semicolon (;) 4. No special symbols are used to terminate these
commands.
~O~

SUBSTITUTION VARIABLES
 It is a special type of variable automatically declared and automatically destroyed by the system.
 Advantage of substitution variables is it makes a statement dynamic.
 As because it is automatically declared it can store any type of value at the runtime.
 Types:
o Statement type
o Session type
1. STATEMENT TYPE: It is a type of variable which is automatically declared whenever a statement
starts execution and automatically destroyed once the statement is executed. This type of variable is
identified by single ampersand (&) (Operator overloading program).
2. SESSION TYPE: Whereas session type variable is a type of variable once declared and assigned with a
value will retain the value until the user exits out of the SQL PLUS or the variable is explicitly destroyed.
This type of variable is identified by double ampersand (&&).

Ex: where DEPTNO = &DNO  A Number


Where JOB = ‘&JOB’  A string
Where JOB = ‘&JOB’ and DEPTNO = &DNO;
Ex: select EMPNO, ENAME, SAL, JOB, DEPTNO from emp where DEPTNO = &&DNO;
To control a session type variable, SQL PLUS provides 2 commands:
1. UNDEFINE ( To destroy a session type variable )
2. DEFINE ( Assign a new value to a variable )
Ex : SQL > DEFINE DNO = 30
SQL > UNDEFINE DNO

~O~

Page | 24 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “JOIN”


 Join is basically a concept or mechanism implemented on ‘select’ statement to extract data from
multiple tables.
 To extract data from multiple tables the tables must have some relationship. Depending on the
relationship of the tables join is broadly categorized in following types
1. Equi-join or Natural join
2. Non equi-join
3. Self-join or Inner join
4. Outer join.

1. EQUI-JOIN OR NATURAL JOIN: It is a type of join which will extract data from multiple tables whenever
a common attribute is available. This type of join is otherwise known as NATURAL JOIN.
‘EMP’ TABLE:

‘DEPT’ TABLE:

Above example shows EMP and DEPT tables having a common attribute called DEPTNO. To extract
data from above tables user can use EQUI-JOIN.

SYNTAX:

SELECT TAB1.COL, TAB1.COL, TAB2.COL, TAB2.COL, ……………….. n


FROM TAB1, TAB2, ……………………………………………………......... n
WHERE TAB1. COL = TAB2.COL AND …………………………………..... n ;

Page | 25 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Ex:
Write a query which will display employee number, name, salary, job, department name, location
of each employee.

Ans:

NOTE: Table name prefixed with the column name is optional but it becomes mandatory whenever a
column attribute is fetched.
Ex: Select empno, ename, sal, emp.deptno / dept.deptno, dname, loc
From emp, dept
Where emp.deptno = dept.deptno;

NOTE: If (n) number of tables are joined in a ‘join’ statement user has to write (n-1) no of conditions.

NOTE: Whenever a condition is omitted from the join statement or it is treated as invalid, it shows an
abnormal output technically known as CARTESIAN PRODUCT or CROSS JOIN. In cartesian product
output of each record of child table will be joined with every record of master.

Page | 26 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

2. NON EQUI-JOIN: This is a type of join implemented on select statement to extract data from multiple
tables whenever there is no common attribute but having a relationship.
Ex:
EMP TABLE

SALGRADE TABLE

Above example shows EMP and SALGRADE tables do not have any common attributes but having a
relationship in between SAL column of EMP table and LOWSAL & HISAL of SALGRADE table.

Example of NON-EQUI-JOIN:

Page | 27 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

EXAMPLE OF EQUI + NON-EQUI JOIN:

3. OUTER JOIN (Out of condition): Outer join is a type of join which will extract data from multiple tables
whether a condition is satisfied or not satisfied. In other words, OUTER JOIN is a type of join which will
extract all the records from multiple tables.

Ex:
Write a query which will display employee number, name, salary, job, dept. name, location of those
employees who are working in a particular department as well as those dept. having no employees.

Ans.

Above example is an example of right outer join where child table is having deficiency.

Page | 28 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “TABLE ALIASING”:


 Table alias is basically a concept through which user can provide duplicate name to an existing
table. Table alias is temporary in nature and confined to the ‘select’ statement.
 Ex:
SELECT E.EMPNO, E.ENAME, E. SAL, E.JOB, D.DNAME, D.LOC
FROM EMP E, DEPT D
WHERE E.DEPTNO = D.DEPTNO;
 In the above example ‘E’ and ‘D’ are 2 table aliases respectively given to emp & dept tables.
 We can’t give ‘AS’ keyword in table aliasing and alias can’t have multiple words

4. SELF JOIN: It is a type of join where same table is joined with itself to get the output. Self-join is
otherwise known as INNER JOIN.
Ex:
EMP TABLE AS ‘W’:

EMP TABLE AS ‘M’:

Above example shows EMPNO, MGR are two common attributes.

Page | 29 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

EXAMPLE OF SELF JOIN:

EXAMPLE OF LEFT OUTER-JOIN:

~O~

Page | 30 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DDL (Data Definition Language)

 DDL is otherwise known as OML or Object Manipulation Language responsible to create and manipulate
tables in Oracle database.
 To do so DDL provides the following commands
o CREATE
o ALTER
o DROP
o TRUNCATE
o RENAME

Creation of table structure using ‘CREATE’:

SYNTAX TO CREATE TABLE:

CREATE TABLE < TAB_NAME >


( COL_NAME_1 DATATYPE (SIZE),
COL_NAME_2 DATATYPE (SIZE),
COL_NAME_3 DATATYPE (SIZE),
……………………………………. n );

Ex: The following example will create a simple table physically in Oracle database.

Once the table structure is created to display the table structure user can use DESCRIBE or DESC
command.
Ex: DESC EMPINFO;

Modification of table structure using ‘ALTER’:


 Alteration of table structure means
1. Add a new column after table design
2. Delete an existing column
3. Changing the datatype of a column
4. Changing the size of a column
5. Renaming a column

Page | 31 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 SYNTAX FOR ALTERING A TABLE (ADD / MODIFY):

ALTER TABLE < TAB_NAME >


ADD | MODIFY ( COL_NAME DATATYPE(SIZE) [, COL_NAME DATATYPE(SIZE), ......N] );

EX: ADDITION & MODIFICATION

 In ALTER columns are appended not added and both addition and modification can’t happen at the same
time.

 SYNTAX FOR RENAMING A COLUMN:

ALTER TABLE < TAB_NAME >


RENAME COLUMN < Source C_NAME > TO < Target C_NAME >;

Page | 32 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

EX:

 SYNTAX TO DELETE COLUMN:

ALTER TABLE < TAB_NAME >


DROP COLUMN < COL_NAME >;

[TO DELETE A SINGLE COLUMN]

ALTER TABLE < TAB_NAME >


DROP (COL1, COL2, COL3, ......N);

[TO DELETE MULTIPLE COLUMNS]

Page | 33 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

EX: BOTH FOR SINGLE COLUMN AND MULTI COLUMN DELETION:

Deleting the table structure with data using ‘DROP’:


SYNTAX:

DROP TABLE < TAB_NAME > [PURGE];

(If PURGE keyword is added with the drop then it will delete the table permanently.)

Ex:

Page | 34 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Renaming a Table using ‘RENAME’:


SYNTAX:

RENAME < SOURCE_T_NAME > TO < TARGET_T_NAME >;

EX:

Deleting all records physically remaining the structure using ‘TRUNCATE’:


SYNTAX:

TRUNCATE TABLE < T_NAME >;


(to make the table empty)

Ex:

Page | 35 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH CONSTRAINTS


 CONSTRAINTS are nothing but some rules or restrictions imposed on individual columns to avoid invalid
data entry.
 ORACLE provides following constraints such as
o PRIMARY KEY
o NOT NULL
o UNIQUE
o CHECK
o FOREIGN KEY

1. PRIMARY KEY: This is a constraint which enforces no NULL values and no DUPLICATE values in a column.
Using a PRIMARY KEY, a record can be uniquely identified. (NO NULL + NO DUPLICATE)
2. NOT NULL: This constraint enforces no NULL values in a column but can accept duplicate values.
(NO NULL + DUPLICATE)
3. UNIQUE: This constraint enforces no DUPLICATE values but can accept NULL values. Any column enforced
with UNIQUE constraint can accept multiple NULL values because NULL values can never be DUPLICATED.
(NULL + N0 DUPLICATE)
4. CHECK: This constraint always checks a condition before accepting a value into a column.
5. FOREIGN KEY: This constraint is helpful to establish a relationship between 2 or more than 2 tables using
a common attribute. FOREIGN KEY always refers to same table’s PRIMARY KEY or another table’s
PRIMARY KEY to establish a relationship. FOREIGN KEY is just opposite of PRIMARY KEY that means it can
accept duplicate values as well as null values. It supports the concept of REFERENTIAL INTEGRITY.
(NULL + DUPLICATE)

NOTE: Referential integrity is a concept through which no CHILD RECORD is allowed in the CHILD TABLE until the
MASTER is available.

Page | 36 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

IMPOSEMENT OF CONSTRAINTS:
 Constraints can be imposed during table design in 2 different levels.
o Column level
o Table level

Column level constraint: COLUMN LEVEL constraints are those constraints which are imposed just after
column definition during table design.

 SYNTAX:

CREATE TABLE <TAB_NAME>


( COL_NAME1 DATATYPE(SIZE) CONSTRAINT <CONS_NAME> <CONS_TYPE>,

COL_NAME2 DATATYPE(SIZE) CONSTRAINT <CONS_NAME> <CONS_TYPE>,

…………………………………………………………………………………………………… n );

NOTE: The basic difference between COLUMN LEVEL and TABLE LEVEL is, using COLUMN LEVEL maximum 1
constraint can be imposed at one point of time but using TABLE LEVEL multiple constraints can be imposed at one
point of time to one column.
* NOT NULL  Always column level
FOREIGN KEY  Always table level but forcibly in column level.

NOTE: Whenever a constraint is imposed each and individual constraint is identified through its name, either given
by the user or given by the system. It is advisable to provide a constraint name by the user. User can use the
following naming convention to name a constraint.
SYNTAX – tablename_column_abvtype
Ex: emp_empno_pk
Student_sid_nt
ABRIVIATED FORM OF CONSTRAINTS
Primary key  pk
Not null  nt
Check  ck
Foreign key  fk

Ex:

Above example is an example of column level constraint.

Page | 37 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Table level constraint: TABLE LEVEL constraints are those constraints which are imposed after all column
definition during table design.

 SYNTAX:
CREATE TABLE < TAB_NAME >
( COL_NAME DATATYPE (SIZE),
COL_NAME DATATYPE (SIZE),
COL_NAME DATATYPE (SIZE),
CONSTRAINT < CON_NAME > < CON_TYPE >(COL_NAME),
CONSTRAINT < CON_NAME > < CON_TYPE >(COL_NAME),
………………………………………… n );

 Ex:
 In table level, constraint name is compulsory.
Q. Design a table which will have the following attributes and constraints:
STUDENT

STUDENT ID NUMBER (4) PRIMARY KEY

SNAME VARCHAR2(10) NOT NULL

BRANCH VARCHAR2(10) CHECK  IT/CS/EEE/MCA

SEMESTER VARCHAR2(10) NOT NULL

ANS. CREATE TABLE STUDENT


( SID NUMBER(4) ,
SNAME VARCHAR2(10) CONSTRAINT STUDENT_SNAME_NT NOT NULL,
BRANCH VARCHAR2(10),
SEM VARCHAR2(10) CONSTRAINT STUDENT_SEM_NT NOT NULL,
CONSTRAINT STUDENT_SID_PK PRIMARY KEY (SID),
CONSTRAINT STUDENT_BRANCH_CK CHECK ( BRANCH IN ‘IT’,’CS’, ‘EEE’, ‘MCA’ ) );

Page | 38 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

IMPOSEMENT OF “FOREIGN KEY” CONSTRAINT:


 SYNTAX:

CREATE TABLE <TAB_NAME>


( COL_NAME DATATYPE(SIZE),
COL_NAME DATATYPE(SIZE),
………………………………………………
………………………………………………
CONSTRAINT < CONST_NAME > FOREIGN KEY ( COLUMN_NAME )
REFERENCES < TAB_NAME > (COL_NAME) );

Q. Design a table which will have the following attributes and constraints:
DEPTINFO2

DEPTNO NUMBER (4) PRIMARY KEY

DNAME VARCHAR2(10) NOT NULL + CHECK  SALES/PURCHASE/ADMIN

LOCATION VARCHAR2(10) NOT NULL + CHECK  CTC/BBSR/RKL

EMPINFO2

EMPNO NUMBER (4) PRIMARY KEY

ENAME VARCHAR2(10) NOT NULL + CHECK  LENGTH(NAME) >= 5

SALARY NUMBER (7,2) NOT NULL + UNIQUE + CHECK  2000 – 30000

DJOIN DATE NOT NULL + CHECK  DJOIN >= ’01-JAN-2010’

DEPTNO NUMBER (4) FOREIGN KEY  DEPTINFO2 (DEPTNO)

Ans.

CREATE TABLE DEPTINFO2


( DEPTNO NUMBER(4),
DNAME VARCHAR2(10) CONSTRAINT DEPTINFO2_DNAME_NT NOT NUL,
LOCATION VARCHAR2(10) CONSTRAINT DEPTINFO2_LOCATION_NT NOT NULL,
CONSTRAINT DEPTINFO2_DEPTNO_PK PRIMARY KEY( DEPTNO ),
CONSTRAINT DEPTINFO2_DNAME_CK CHECK (DNAME IN (‘SALES’, ‘PURCHASE’, ‘ADMIN’)),
CONSTRAINT DEPTINFO2_LOCATION_CK CHECK (LOCATION IN (‘CTC’, ‘BBSR’, ‘RKL’)) );

CREATE TABLE EMPINFO2


( EMPNO NUMBER(4),
ENAME VARCHAR2(10) CONSTRAINT EMPINFO2_ENAME_NT NOT NUL,
SAL NUMBER(7,2) CONSTRAINT EMPINFO2_SAL_NT NOT NULL,
DJOIN DATE CONSTRAINT EMPINFO2_DJOIN_NT NOT NULL,
DEPTNO NUMBER(4),
CONSTRAINT EMPINFO2_EMPNO_PK PRIMARY KEY( EMPNO ),
CONSTRAINT EMPINFO2_ENAME_CK CHECK (LENGTH(ENAME) >= 5),
CONSTRAINT EMPINFO2_DJOIN_CK CHECK (DJOIN >= TO_DATE (‘01-JAN-2010’),
CONSTRAINT EMPINFO2_SAL_UK UNIQUE KEY (SAL),
CONSTRAINT EMPINFO2_SAL_CK CHECK (SAL BETWEEN 2000 AND 30000),
CONSTRAINT EMPINFO2_DEPTNO_FK FOREIGN KEY(DEPTNO) REFERENCES DEPTINFO2(DEPTNO));

Page | 39 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “ON DELETE CASCADE”:


 ON DELETE CASCADE is a key word imposed with the foreign key, which enforces a rule that
whenever a master record is deleted from the master table all corresponding child records are
automatically deleted.
 EX:

CREATE TABLE EMPINFO2


( EMPNO NUMBER(4),
ENAME VARCHAR2(10) CONSTRAINT EMPINFO2_ENAME_NT
NOT NUL,
SAL NUMBER(7,2) CONSTRAINT EMPINFO2_SAL_NT NOT NULL,
DJOIN DATE CONSTRAINT EMPINFO2_DJOIN_NT
NOT NULL,
DEPTNO NUMBER(4) CONSTRAINT EMPINFO2_DEPTNO_FK
REFERENCES DEPTINFO2 (DEPTNO)
ON DELETE CASCADE );
(ABOVE EXAMPLE IS AN EXEMPLE OF FOREIGN KEY IMPOSEMENT IN COLUMN LEVEL USING “ON DELETE CASCADE”)
(DELETE FROM DEPTINFO2 WHERE DEPTNO = 20;)

CONSTRAINT MANIPULATION:
 Constraint manipulation is a concept or technique through which user can add a new constraint or
delete an existing constraint after table design.
 A constraint can be added or a constraint can be deleted but a constraint cannot be modified.
 SYNTAX TO ADD A NEW CONSTRAINT:

ALTER TABLE < TAB_ NAME >


ADD CONSTRAINT < CONSTRAINT_NAME > < CONS_TYPE > ( COL_NAME );
 SYNTAX FOR ADDING MULTIPLE CONSTRAINTS TO MULTIPLE COLUMNS:
ALTER TABLE < TAB_ NAME >
ADD ( CONSTRAINT < CONSTRAINT_NAME > < CONS_TYPE > ( COL_NAME ),
CONSTRAINT < CONSTRAINT_NAME > < CONS_TYPE > ( COL_NAME ),
………………………………………………………………………………………… n );
 SYNTAX TO DELETE AN EXISTING CONSTRAINT:
ALTER TABLE < TAB_ NAME >

DROP CONSTRAINT < CONSTRAINT_NAME > ;


 EX:
ALTER TABLE EMPINFO3
ADD CONSTRAINT EMPINFO3_EMPNO_PK PRIMARY KEY(EMPNO);
ALTER TABLE EMPINFO3
ADD ( CONSTRAINT EMPINFO3_SAL_CK CHECK (SAL BETWEEN 2000 AND 50000),
CONSTRAINT EMPINFO3_JOB_UK UNIQUE (JOB) );
(Above example shows constraints are imposed after table design)
NOTE: After table design NOT NULL constraint can’t be given. A NOT NULL constraint can only be imposed after table
design by modifying the column.

Page | 40 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Ex:

( Above example is to change the NOT NULL constraint after table design )

SYNTAX FOR ENABLING OR DISABLING CONSTRAINT:

ALTER TABLE < TAB_NAME >


DISABLE | ENABLE CONSTRAINT < CONST_NAME >

 Enabling or disabling of constraints means activating or deactivating a constraint. Whenever a


constraint is in disabled mode user can enter invalid data in it.
 So before re enabling the constraint user must delete all invalid data entered during disabled time.
 Disabling and enabling a constraint is made for testing purpose. Ex:

~O~

Page | 41 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DATA DICTIONARY / SYSTEM CATALOGUE / METADATA

 Whenever an object is created in an oracle database, not only object is created but also the
information regarding that object will be kept inside a system defined table, technically known as
DATA DICTIONARY / SYSTEM CATALOGUE / METADATA.
 ORACLE provides 3 different types of dictionaries
o GENERAL USER DICTIONARY ( USER_ )
o SUPER USER DICTIONARY ( DBA_ )
o SESSION DICTIONARY ( V$ )
 ORACLE provides several objects for customized database management and those are:
1. TABLE USER_TABLE DBA_TABLE
2. VIEW USER_VIEW DBA_VIEW
3. M.VIEW USER_M.VIEW DBA_M.VIEW
4. SYNONYM USER_SYNONYM DBA_SYNONYM
5. SEQUENCE USER_SEQUENCE DBA_SEQUENCE
6. INDEX USER_INDEX DBA_INDEX
7. TYPE USER_TYPE DBA_TYPE
8. CONSTRAINTS USER_CONSTRAINTS DBA_CONSTRAINTS
 To display the table names:

Page | 42 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Above example shows TABLE_NAME is a column name whereas USER_TABLE is a table name.
 To display the columns of user tables:

 To display all the tables available in ORACLE DATABASE: in SYSTEM user:

 To display all the tables of a particular user from SUPERUSER:


SELECT TABLE_NAME, OWNER FROM DBA_TABLES WHERE OWNER = ‘REQIRED USER NAME’

Page | 43 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 To display the constraint info of a particular table:

IMPLICIT NAMING CONVENTION OF A CONSTRAINT:


If no constraint name is given during table design, the name is automatically given by the system which
looks like the following 

NOTE: A constraint can be deleted in 2 different manners i.e. Explicitly using ALTER Command or
Implicitly using DROP Command.
~O~

Page | 44 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DML (Data Manipulation Language)


 DML is otherwise known as RML or Record Manipulation Language, responsible to manipulate records
of a table. To do so DML provides the following statements:
1. INSERT
2. UPDATE
3. DELETE

 SYNTAX OF INSERT :

INSERT INTO < TAB_NAME >[ ( COL1,COL2,COL3,....N ) ]


VALUES ( VALUE1,VALUE2,VALUE3,........N );

EX:

INSERTION OF NULL VALUE IN A COLUMN:


 User can enter NULL values in a column in 2 different manners
o Explicitly using ‘NULL’ keyword
o Implicitly using column list
 Ex:

Page | 45 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

UPDATE:
SYNTAX:
UPDATE <TAB_NAME>
SET COL_NAME = VALUE [ ,COL_NAME=VALUE, .......... n]
[ WHERE < CONDITION > ];
EX:

( Example of single column wise updating )


Ex:

( Example of multi column wise updating )

NOTE: If WHERE clause is omitted from the update statement it will update all the values of a specific column.
EX:

Page | 46 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DELETE:
SYNTAX

DELETE FROM <TAB_NAME>


[WHERE <CONDITION>];

Ex:

NOTE: Deleting without WHERE will delete all the records of a table. The basic difference between ALTER
and UPDATE is; alter is made for structural change whereas update is made for data change.

~O~

Page | 47 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SOME INTERVIEW RELATED


TABLE CREATION USING QUERY STATEMENT (COPY A TABLE):

Above example will copy structure as well as data to a new table. But whenever a table is copied only NOT NULL
constraints are copied to the new table except other constraints.

To copy specific column as well as specific data 

DELETING IDENTICAL RECORDS FROM A TABLE:

To delete the 3rd record from the above table user can write the following command:

Page | 48 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Whenever a table is created in ORACLE database, the table is created using n+1 column slab. The extra column which
is created called ROWID. ROWID is a physical hidden column responsible to uniquely identify the record by the
system. ROWID always be 18 characters long and can contain alphanumeric data.

Apart from ROWID another column is provided by ORACLE i.e. ROWNUM. It is a virtual column responsible to display
number of records by providing serial number. No record manipulation is allowed through ROWNUM.
EX:

~O~

Page | 49 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

TRANSACTION CONTROL LANGUAGE ( TCL )


 Whenever any DML operation is made in an ORACLE table the DML operations are not going to be saved
unless and until a SAVE command is issued or DISCARD command is issued.
 To do so TCL provides the following statements
o COMMIT
o ROLLBACK
o SAVE POINT

TCL MECHANISM:

 Whenever any DML operation is made in an ORACLE table for the first time, just before the DML operation is
made automatically a temporary memory is created within the server technically known as ROLLBACK
SEGMENT and the table in which the DML operation is going to be made is copied temporarily to the
Rollback Segment technically known as SNAPSHOT.
 Whenever a COMMIT command is issued after a DML operation, ROLLBACK SEGMENT along with the
SNAPSHOT gets deleted and the record or records transacted in the main table becomes permanent.
 If a ROLLBACK command is issued after a DML operation the SNAPSHOT available inside the ROLLBACK
SEGMENT again recopied to its original location with the old data and the rollback segment gets deleted.
 NOTE: Data once committed can’t be rolled back and once rolled back can’t be committed.
 Ex:

SQL> insert into EMPINFO6


Values (………..);
SQL> insert into EMPINFO6
Values (………..);
SQL> COMMIT;

(Above transactions are going to be saved)

SQL> delete from EMPINFO6 where job = ‘MANAGER’;


SQL> ROLLBACK;

(Above example will discard the transactions made by the user)

Page | 50 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Above examples are the examples of explicit COMMIT and explicit ROLLBACK of data by the user. But in
some circumstances data is implicitly committed and rolled-back by the server, technically known as AUTO
COMMIT and AUTO ROLLBACK.
 In the following circumstances data is automatically committed.
o Whenever a DDL or DCL command is issued after any DML operation.
o Whenever user exits out of SQL*PLUS normally after any DML operation using ‘QUIT’ or ‘EXIT’
command.
 In the following circumstances data is automatically rolled back by the server.
o Whenever user exits out of the SQL PLUS abnormally or during system crash.

NOTE: BUFFER  Client side memory


ROLLBACK SEGMENT  Server side memory

 SAVE POINT: Save point is nothing but a logical pointer given to individual transaction or group of
transactions made by the user. Save point is basically made for ROLLBACK purpose. To Roll back to a
particular point excluding that point. Rollback to a particular point doesn’t mean the above transactions are
committed. User has to explicitly use the COMMIT command for saving the transactions.

~O~

Page | 51 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

OBJECTS IN ORACLE DATABASE


TYPE (STRUCTURE) (NESTED TABLES):
 ORACLE not only provides built-in datatypes to declare a column of a table but also facilitate the user to
create user defined datatypes (structure).
 In ORACLE, structure is otherwise known as type declaration.
 Advantages of structure concept is it reduces column redundancy.
 Type declaration also supports nested table concept.
 Ex:

SYNTAX:
CREATE TYPE < TYPE_NAME > AS OBJECT

(COL_NAME DATATYPE (SIZE)

COL_NAME DATATYPE (SIZE)

…………………………………….. n )

Page | 52 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Ex:

Page | 53 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Page | 54 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Page | 55 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Page | 56 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “SYNONYM” (POINTERS):


Synonym is nothing but a schema(user) object responsible to provide duplicate name to a n existing object. Synonym
neither holds the data of an object nor it holds the structure rather than it holds the reference of an object to whom
it is referencing. In general meaning, synonym is nothing but to provide permanent duplicate name.

TYPES:

1. PRIVATE SYNONYM: It is a type of synonym once created on an object can only be accessed within that user
where the original object resides. In other words, private synonym is confined to a specific schema.
2. PUBLIC SYNONYM: It is a type of synonym once created on an object can be globally accessed in any schema
in ORACLE database.

NOTE: No object in ORACLE database can be created as public but through public synonym any object can be
publicly accessed.

SYNTAX :

CREATE [ PUBLIC ] SYNONYM < S_NAME >

FOR [ SCHEMA .] < OBJECT_NAME >


** If public then schema name compulsory.
Ex:

Create synonym et
For employee_tab

Page | 57 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

NOTE:
TABLE_NAME of user synonyms
contains any object name upon
which a synonym is created.

NOTE: Once a public synonym is


created to display a public
synonym or to delete a public
synonym user must enter into
the super user.

(The above example shows that we can also give another synonym name to an existing synonym)

Page | 58 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

PUBLIC SYNONYM: These synonyms can be accessed in all other users. Public synonym can be created inside any
user but information regarding the public synonym is stored inside the superuser or the dba user and to drop the
synonym we have to do it from the superuser account.

Ex:

WORKING WITH “SEQUENCE”:


Sequence is a schema object responsible to generate a linear number either in assending order or in
descending order, even number or odd number. Sequence object is only made for insertion purpose.
Sequence object can only generate numerical values not alpha numerical values.
SYNTAX:
CREATE SEQUENCE <S_NAME>
[ INCREMENT BY <VALUE> ]
[ START WITH <VALUE> ]
[ MAXVALUE N|NOMAXVALUE ]
[ MINVALUE N|NOMINVALUE ]
[ CYCLE | NOCYCLE ]
[ CACHE N|NOCACHE ] ;

Page | 59 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Ex:
Above example will create a sequence whose initial value will be 1. Each time incremented by 1 and
generate infinity value(e27).

Once the sequence is created, to run the sequence 2 attributes are available i.e. NEXTVAL & CURRVAL.
These attributes are suffixed with the sequence name using dot(.) operator.

Ex:

Page | 60 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

CREATING A CYCLIC SEQUENCE:

In the above examples -


Example number 1 will create a sequence whose initial value is 1, each time incremented by 1 and
generate 20 values and do the same for 5 times; example no 2 represents creating a descending sequence
and example no 3 represents altering a sequence. Any clause of a sequence can be altered except “start
with” clause.

SEQUENCE DICTIONARY:

Page | 61 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

IMPLIMENTATION OF SEQUENCE IN A TABLE:

** not to show the “old” & “new” use command  SET VERIFY OFF

WORKING WITH “VIEWS”:


 “View is nothing but a logical subset of data based on one table or more than one table.”
 The primary advantages of view is to protect table structure from invalid users.
 The table based on which a view is created known as a “Base Table”.
 As because view behaves like a table, it is otherwise known as a “Virtual Table”.

TYPES OF VIEWS:

It is broadly categorized in two different types.


1. GENERAL VIEW (LOGICAL)
2. MATERIALIZED VIEW (PHYSICAL)
GENERAL VIEW (LOGICAL): it is a type of view which is devided into two types i.e. SIMPLE VIEW and
COMPLEX VIEW.

Page | 62 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

SYNTAX:
CREATE [ OR RAPLACE ] [ FORCE | NOFORCE ] VIEW <V_NAME>
AS <SELECT STATEMENT>
[ WITH CHECK OPTION ]
[ WITH READ ONLY ];
EX:

(CREATING A SIMPLE VIEW)

Above example shows the creation of a simple view based on employee table. Through above view any
recoord can be inserted, updated, deleted, selected to the employee table but no structural change is
allowed in the view. The following example shows that an error will occur while trying to make any
structural change in the view.

Page | 63 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

(Ex: Error when trying to do any structural change in the view.)

EXAMPLE OF A VIEW BASED ON A CONDITION:

Whenever a view is based on a condition, any record can be inserted through the view to the base
table but those records can not be updated , deleted or selected.
For example:

Page | 64 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Page | 65 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

RESTRICTING INSERTION DEPENDING ON A CONDITION USING “WITH CHECK


OPTION” :

Above example is an example of Pure Logical Subset as because through above view only SALESMAN
records can be inserted, updated, deleted or selected.

CREATING A READ ONLY VIEW USING “WITH READ ONLY” :


Whenever a view is read only, neither structure can be tampered nor data. This type of view is
required for reporting purpose. Ex:

Page | 66 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

CREATING A VIEW FORCIBLY WITHOUT HAVING A BASE TABLE:


 The default behaviour of view is NOFORCE. But when a view is created forcibly without using a base
table, it is not going to work unless and until the base table is created.

Above example will create a view forcibly without having a base table. Once the base table is created
view will start its job.

Page | 67 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH COMPLEX VIEW:

Above is an example of complex view. As because complex view represents data from multiple tables, it
is not advisible to perform any DML operation through the view to the base table.complex views are
basically meant for reporting purpose.

TO DISPLAY THE NAME OF VIEW:

Page | 68 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

TO DELETE A VIEW PHYSICALLY:

A view can be created inside a view but it is not advisible.

A VIEW BASED ON ANOTHER VIEW:

WORKING WITH MATERIALIZED VIEW:


 Materialized view concept is basically known as REMOTING IN ORACLE. This is a view having its
own structure and data. This is basically a copy of a table which is available in the remote database.
 Advantage of this view is whenever the remote table is tampered ( insert/update/delete ) it will
affect the Materialized view in the local database.
 A materialized view can be refreshed either manually or automatically.
 Materialized views are divided into the following types:
1. Read only M.V.
2. Updatable M.V.
 The default view of M.V. is Read Only.

READ ONLY M.V.:


 TO DISPLAY THE DATABASE NAME:

 TO CREATE A MATERIALIZED VIEW (READ ONLY):

 Above example is an example of read-only materialized view which will be refreshed automatically
after each 2 days.

Page | 69 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

UPDATABLE M.V.:
 TO CREATE A MATERIALIZED VIEW (UPDATABLE):

 TO REFRESH A MATERIAL VIEW MANUALLY:

 TO DROP M.V. PHYSICALLY:

 TO DISPLAY VIEW NAME:

Page | 70 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 TO DESCRIBE STRUCTURE OF USER_MVIEWS:

~O~

Page | 71 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

WORKING WITH “INDEX”:


 Index is nothing but a schema object responsible to arrange the records in a proper manner using
reference.
 Advantage of index object is it makes data searching faster.
 Index object is not going to be created on the whole table rather than it has to be created on the
column which is meant for data searching purpose.
 Indexes are divided into 2 types i.e.
1. UNIQUE INDEX
2. NON UNIQUE INDEX
 UNIQUE INDEX is a type of index automatically generated by ORACLE server on those columns
which are enforced with Primary Key or Unique constraint. These indexes are otherwise known as
IMPLICIT INDEXES.
 Whereas NON UNIQUE INDEX are those indexes which are explicitely created by the user on those
columns which have duplicate values. These are also known as EXPLICIT INDEX.

EXPLICIT INDEX:
 Explicit indexes are again divided into 2 types i.e.
a. SINGLE COLUMN INDEXING OR SIMPLE INDEX
b. MULTI COLUMN INDEXING OR COMPOSITE INDEX
 SYNTAX:
CREATE INDEX < i_name >
ON < tab_name > ( col_name [ , col_name, …………. n ] )

 Ex:

Above example is an example of simple index or single column wise indexing.

 Ex:

Above example is an example of complex index.

 To see the index names in the current user:

Page | 72 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 To drop an index:

IMPLICIT INDEX:
 Whenever an index is created automatically by ORACLE server, the name of the index will be same
as the constraint name either given by the user or given by the system and it can’t be explicitly
deleted by the user.
 Ex:

In the above example user defined constraint name EMPTAB_EMPNO_PK and system defined
constraint name SYS_C009762 are also used as the index names for the table.

NOTE:
 An index object can be deleted intwo different manners i.e.
1. Explicitely using DROP command
2. Implicitely whenever a table is DROPPED.
 In ORACLE, two objects are dependent objects and they are CONSTRAINTS & INDEXES, because if the
table is deleted then related constraints and indexes will also be deleted whereas SYNONYMS, TYPES
and other objects will not be deleted.
 More than one index on one column is is not allowed in oracle 11g as well as 10g but was allowed in
9i.
 More than one index to one column makes the data searching slower not faster.

~O~

Page | 73 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

DATA CONTROL LANGUAGE (DCL)


 ORACLE not only facilitates the user to create objects in ORACLE database but also allows the user
to create schema and each schema is protected by a password.
 Schema non technically known as an USER.
 General user  to create objects, manipulate the objects
 Super user  to create and destroy the users.

NOTE: To create and manipulate schemas/ users in ORACLE database, oracle provides a super user called
SYSTEM.

SYNTAX TO CREATE A SCHEMA:

CREATE USER < U_NAME >


IDENTIFIED BY < PASSWORD >;

SYNTAX TO DELETE AN EXISTING SCHEMA:

DROP USER < U_NAME > [ CASCADE ];

** Above syntax is for deleting user with all its objects.

SYNTAX TO CHANGE THE PASSWORD OF EXISTING SCHEMA:


ALTER USER < U_NAME >

IDENTIFIED BY < NEW_PASSWORD >

 This can be written either in the SYSTEM user or in the user who owns the old password.
 It doesn’t require the old password because if the SYSTEM (DBA) wants the password, then it will be
dependent on the general user. But the administrator should not depend on any user.
 But the general user must require the old password in order to change the password

SYNTAX TO LOCK / UNLOCK A SCHEMA:


ALTER USER < U_NAME >
ACCOUNT LOCK / UNLOCK;

 Command will be written in super user.

 Users or schemas never take any memory unless or until objects are put in there. For example
“CREATE USER SYSOFT IDENTIFIED BY bbsr” this example will create a user logically in ORACLE
database.

Page | 74 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

FOR DISPLAYING USER NAMES OR THE NUMBER OF USERS AVAILABLE INSIDE THE
DB:

Page | 75 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

FOR DISPLAYING BOTH USER NAMES AND PASSWORD:

** it shows the passwords in hidden state. In order to get the correct password, a PL/SQL program is
needed.
FOR DISPLAYING STATUS OF USERS WHETHER LOCKED OR UNLOCKED:

Page | 76 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

NOTE: To change the password of a user, user can use a sql * plus command i.e. PASSWORD.

EX:

FOR UNLOCKING AN LOCKED USER:

** ALTER command can either be written within the SYSTEM user or within the SCOTT user itself.

Page | 77 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

PRIVILEGES
 Whenever a user is created in ORACLE database user is not going to be activated unless or until
some rules are assigned in it and those rules are technically known as PRIVILEGES.
 Privileges are broadly categorized into two different types i.e.
1. SYSTEM PRIVILEGE
2. OBJECT PRIVILEGE
 A system privilege is the right to perform a particular action or to perform an action on any object
of a particular type. Objects include tables, views, materialized views, synonyms, indexes,
sequences, cache groups, replication schemes and PL/SQL functions, procedures and packages.
Only the instance administrator or a user with ADMIN privilege can grant or revoke system
privileges.
 An object privilege is the right to perform a particular action on an object or to access another
user's object.
 An object's owner has all object privileges for that object, and those privileges cannot be revoked.
 The object's owner can grant object privileges for that object to other database users.
 A user with ADMIN privilege can grant and revoke object privileges from users who do not own the
objects on which the privileges are granted.
 Frequently used SYSTEM PRIVILEGES are:

Privilege Description
ADMIN Enables a user to perform administrative tasks including check pointing, backups,
migration, and user creation and deletion.

ALTER ANY CACHE GROUP Enables a user to alter any cache group in the database.

ALTER ANY INDEX Enables a user to alter any index in the database.

Note: There is no ALTER INDEX statement.

ALTER ANY MATERIALIZED Enables a user to alter any materialized view in the database.
VIEW
Note: There is no ALTER MATERIALIZED VIEW statement.

ALTER ANY PROCEDURE Enables a user to alter any PL/SQL procedure, function or package in the database.

ALTER ANY SEQUENCE Enables a user to alter any sequence in the database.

Note: There is no ALTER SEQUENCE statement.

ALTER ANY TABLE Enables a user to alter any table in the database.

ALTER ANY VIEW Enables a user to alter any view in the database.

Note: There is no ALTER VIEW statement.

CACHE_MANAGER Enables a user to perform operations related to cache groups.

CREATE ANY CACHE GROUP Enables a user to create a cache group owned by any user in the database.

CREATE ANY INDEX Enables a user to create an index on any table or materialized view in the database.

CREATE ANY MATERIALIZED Enables a user to create a materialized view owned by any user in the database.
VIEW

Page | 78 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Privilege Description
CREATE ANY PROCEDURE Enables a user to create a PL/SQL procedure, function or package owned by any
user in the database.

CREATE ANY SEQUENCE Enables a user to create a sequence owned by any user in the database.

CREATE ANY SYNONYM Enables a user to create a private synonym owned by any user in the database.

CREATE ANY TABLE Enables a user to create a table owned by any user in the database.

CREATE ANY VIEW Enables a user to create a view owned by any user in the database.

CREATE CACHE GROUP Enables a user to create a cache group owned by that user.

CREATE MATERIALIZED VIEW Enables a user to create a materialized view owned by that user.

CREATE PROCEDURE Enables a user to create a PL/SQL procedure, function or package owned by that
user.

CREATE PUBLIC SYNONYM Enables a user to create a public synonym.

CREATE SEQUENCE Enables a user to create a sequence owned by that user.

CREATE SESSION Enables a user to create a connection to the database.

CREATE SYNONYM Enables a user to create a private synonym.

CREATE TABLE Enables a user to create a table owned by that user.

CREATE VIEW Enables a user to create a view owned by that user.

DELETE ANY TABLE Enables a user to delete from any table in the database.

DROP ANY CACHE GROUP Enables a user to drop any cache group in the database.

DROP ANY INDEX Enables a user to drop any index in the database.

DROP ANY MATERIALIZED Enables a user to drop any materialized view in the database.
VIEW

DROP ANY PROCEDURE Enables a user to drop any PL/SQL procedure, function or package in the database.

DROP ANY SEQUENCE Enables a user to drop any sequence in the database.

DROP ANY SYNONYM Enables a user to drop a synonym owned by any user in the database.

DROP ANY TABLE Enables a user to drop any table in the database.

DROP ANY VIEW Enables a user to drop any view in the database.

DROP PUBLIC SYNONYM Enables a user to drop a public synonym.

EXECUTE ANY PROCEDURE Enables a user to execute any PL/SQL procedure, function or package in the
database.

FLUSH ANY CACHE GROUP Enables a user to flush any cache group in the database.

INSERT ANY TABLE Enables a user to insert into any table in the database. It also enables the user to
insert into any table using the synonym, public or private, to that table.

LOAD ANY CACHE GROUP Enables a user to load any cache group in the database.

Page | 79 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Privilege Description
REFRESH ANY CACHE GROUP Enables a user to flush any cache group in the database.

SELECT ANY SEQUENCE Enables a user to select from any sequence or synonym on a sequence in the
database.

SELECT ANY TABLE Enables a user to select from any table, view, materialized view, or synonym in the
database.

UNLOAD ANY CACHE GROUP Enables a user to unload any cache group in the database.

UPDATE ANY TABLE Enables a user to update any table or synonym in the database.

XLA Enables a user to connect to a database as an XLA reader.

 Frequently used OBJECT PRIVILEGES are:

Privilege Object type Description


DELETE Table Enables a user to delete from a table.

EXECUTE PL/SQL package, procedure or Enables a user to execute a PL/SQL package, procedure or
function function directly.

FLUSH Cache group Enables a user to flush a cache group.

INDEX Table or materialized view Enables a user to create an index on a table or materialized
view.

INSERT Table or synonym Enables a user to insert into a table or into the table through a
synonym.

LOAD Cache group Enables a user to load a cache group.

REFERENCES Table or materialized view Enables a user to create a foreign key dependency on a table or
materialized view.

The REFERENCES privilege on a parent table implicitly


grants SELECT privilege on the parent table.

REFRESH Cache group Enables a user to refresh a cache group.

SELECT Table, sequence, view, materialized Enables a user to select from a table, sequence, view,
view, or synonym materialized view, or synonym.

The SELECT privilege enables a user to perform all operations


on a sequence.

A user can be granted the SELECT privilege on a synonym or a


view without being explicitly granted the SELECT privilege on
the originating table.

UNLOAD Cache group Enables a user to unload a cache group.

UPDATE Table Enables a user to update a table.

Page | 80 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Among above system privileges CREATE SESSON privilege is the primary privilege responsible to
activate a user.

NOTE: “CREATE SESSION” is a privilege responsible to allow the user to logging into a user by creating
SESSION IDs. SESSION ID is a temporary memory responsible to execute a command in the server
side issued from a specific client.

 Above privileges can either be granted to a user or to an object and likewise revoked from a user or
from an object. To do so DCL provides 2 commands i.e.
1. GRANT
2. REVOKE
 SYNTAX TO GRANT SYSTEM PRIVILEGES:
GRANT SP1, SP2, SP3, …………. N
TO USER_NAME | ROLE;

 SYNTAX TO REVOKE SYSTEM PRIVILEGES:


REVOKE SP1, SP2, SP3, …………. N
FROM USER_NAME | ROLE;
NOTE: SYSTEM PRIVILEGES are those privileges which are granted or revoked only from the system user,
whereas OBJECT PRIVILEGES are those privileges which are granted or revoked only from that user
who owns the object.

 SYNTAX TO GRANT OBJECT PRIVILEGES:


GRANT OP1, OP2, OP3, …………. N
ON < Obj_name >
TO < USER_NAME >
[ WITH GRANT OPTION ]

 SYNTAX TO REVOKE OBJECT PRIVILEGES:


REVOKE OP1, OP2, OP3, …………. N
ON < Obj_name >
FROM < USER_NAME >
[ WITH GRANT OPTION ]

 Examples of SYSTEM PRIVILEGES:

Page | 81 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 Above example will assign some system privileges or revoke system privileges according to user
requirements.

NOTE: Revoking create session privilege is another way of locking a user.

Working with Object Privileges:

 In this example user SCOTT is granting


only INSERT, SELECT and UPDATE
(SALARY COLUMN) privileges to the user
INDIA.
 Thus user INDIA can only be able to use
SELECT command for data retrieval and
INSERT command for inserting rows and
UPDATE command for updating data.
 But trying to update other columns
except the SALARY column will give an
error “INSUFFICIENT PRIVILEGES”.

NOTE: To access an object of one user in


another, user must prefix the schema name
before the object name to which the
corresponding object belongs.

Page | 82 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

 In this example REVOKING previously


GRANTED privileges, gives user INDIA no
access to the existing EMPTAB table of
user SCOTT.

Working with “WITH GRANT OPTION”:

 In this example user SCOTT is granting for


SELECT, INSERT, UPDATE on EMPTAB
table WITH GRANT OPTION to the user
INDIA so that user INDIA is able to grant
privileges on EMPTAB table of user SCOTT
to another user ODISHA.

Page | 83 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Working with “ROLE”:


 Role is nothing but a container which contains system privileges to be granted to one user or
several other users.
 Advantage of ROLE is; it supports flexibility during system privilege assignment
 A ROLE can only be created within the super-user and only contains system privileges.
 EX:

 Above example will create a role i.e. MYROLE and assign privileges to the role and assign the role to
the existing user ODISHA.
 Example to display the PRIVILEGES inside a ROLE:

 For displaying all the roles:

 Apart from the user defined roles some built in roles are provided by ORACLE to make a user
operational. Examples of these are:

Page | 84 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

Page | 85 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA ORACLE 11g - SQL MOB: 9861033385

From the above roles CONNECT, RESOURCES, OLAP_USER are general user roles whereas DBA is a super
user role.

 For displaying privileges of DBA user:

~O~

~ THE END ~

Page | 86 SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012

You might also like