0% found this document useful (0 votes)
4 views94 pages

1) SQL Running Notes

The document provides an overview of Oracle 19c, covering fundamental concepts such as data, information, databases, and the role of Database Management Systems (DBMS). It discusses the types of databases (OLTP and OLAP), models of DBMS, and the features of Oracle as a relational database management system. Additionally, it includes details on SQL, its sub-languages, and data types used in Oracle, along with practical instructions for user management and common issues encountered in Oracle DB server.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views94 pages

1) SQL Running Notes

The document provides an overview of Oracle 19c, covering fundamental concepts such as data, information, databases, and the role of Database Management Systems (DBMS). It discusses the types of databases (OLTP and OLAP), models of DBMS, and the features of Oracle as a relational database management system. Additionally, it includes details on SQL, its sub-languages, and data types used in Oracle, along with practical instructions for user management and common issues encountered in Oracle DB server.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

ORACLE19c

=========
Topic-1 : DBMS(17-06-2022)
==========================
What is Data?
- data is raw fact(there is no meaning).

Ex:
smith 10021

What is Information?
- processing data is called as "information".
Ex: CustomerNames CustomerID
============ ===========
smith 10021
- information is always provide meaning full statements.

What is Database?
- it is a collection of interrelated data/ information that has been organized in proper
systematically(i.e table) manner.

What is DBMS?
- it is a s/w which is used to manage and maintain data/ information in database.
- by using DBMS s/w we can do,
> create database(memory)
> stored data/information
> manipulate data/information
> retrieving data / information
> deleting data / information

What are Data storages?


- it is a location where we can store data /information.
1. papers & books- before computers
2. flatfile - after computers
3. DBMS/database

2. flat file:
=============
- data can stored in file with the help of OS.

Disadvantages:
==============
i) Data redundancy
ii) Data inconsistency
iii) Data retrieval
iv) Data integrity
v) Data security
vi) Data indexing

i) Data redundancy:
====================
- storing same information in multiple files in computer.
1
ii) Data inconsistency:
=======================
- once we change any modifications in one file then the corresponding copy file will not effected
this problem is called as "data inconsistency".

iii) Data retrieval:


====================
- to retrieving the required data from data storage but it is very difficult from flat file because to
retrieve data from flatfile we need develop an application program by using some high level languages like
c,c++,java,.net...etc.

iv) Data integrity:


====================
- integrity is nothing but to validate data before storing into data storage but it is not possible in flat
files.

v) Data security:
=================
- there is no security for flat file data.

vi) Data indexing:


==================
- to accessing data from data storage much more faster. but flat file not allowed this mechanism.

Note: to overcome the disadvantages of flat file and books & papers we use a concept is called as "DBMS"
(database management system).

What is DBMS?
- it is a s/w which is used to manage and maintain data/information in database.
- by using DBMS s/w we can do,
> create database(memory)
> stored data/information
> manipulate data/information
> retrieving data / information
> deleting data / information

What is Database?
- it is a collection of interrelated data/ information that has been organized in proper
systematically(i.e table) manner.

Types of databases?
===================
- there are two types databases in real world.

1. OLTP(online transaction processing)


2. OLAP(online analytical processing)

1. OLTP:
========
- these databases are used for storing "day-to-day" transactional data/information for running
business.

2
- we can perform live operations(insert,update,delete,small data select)

Ex: oracle,sqlserver,mysql,db2,sybase,..........etc

Ex: Banking
x-customer open new a/c: 21-05-2015

25-05-2015:
===========
day-1 :Deposite transaction,Withdraw transaction:

2. OLAP:
========
- these databases are used for storing "historical data / big data".
- we can perform only operation i.e "select" operation.

Ex: Data ware house

Models of DBMS:
===============
1. Hierarchical database management system(HDBMS)
Ex: IMS s/w (Information management system)
2. Network database management system(NDBMS)
Ex: IDBMS s/w (Integrated database management system)

Note: these two models are outdated models.

3. Relational database management system(RDBMS)

i) Object relational DBMS(ORDBMS):


=================================
- data can be stored in "table" format.
table = collection rows & columns
- these databases are complete depends on "SQL".

Ex s/w : Oracle,sqlserver,mysql,db2,sybase,informix,ingrees,teradata,maxdb.....etc

ii) Object Oriented DBMS(OODBMS):


=================================
- data can be stored in "objects" format.
- complete depends on "OOPS" concept.
- OODBMS are called as "NO SQL" databases.

Ex s/w : MongoDB,Cassandra.....etc
====================================================================

Topic-2: ORACLE
======== =======
- oracle is a rdbms(ordbms) product/ DB software/ back end tool from "oracle corporation" in 1979.
- it is used to store data/information permanently

3
(i.e HD) along with security.
- it can deployee(install) in any operating system
like windows,linux,unix,mac,solaries....etc
- so that oracle is a platform independent an RDBMS product.

Versions of oracle:
===================
from oracle 1.0 --------- oracle19C version.

file1 file2
====== =====
y x ---- inconsistency

y y ---- consistency

Working with oracle:


====================
- oracle s/w is available in two editions.

i) oracle express edition


==========================
> supporting partial feature

Ex: recyclebin,falshback,purge,
partition tables.....etc are not allowed.

ii) oracle enterprise edition:


==============================
> supports all features.

How to download Oracle19c enterprise edition s/w:


=================================================

How to install Oracle19c enterprise edition s/w:


================================================

Note:
=====
- there are two components are installed in system.
1. client component
2. server component
1. client component:
====================
- a user can perform 3 operations:
i) connect to oracle server
ii) to send request to oracle server
iii) to get response from oracle server
Ex:
===
sqlplus,toad,sql developer,pl/sql developer....etc

4
2. server component:
====================
- it again having two more sub components are,

i) instance
ii) database

i) instance:
============
- it is a temporary memory
- data can be stored in temporary.
- this component memory is allocating by system from RAM.

ii) database:
=============
- it is permanent memory
- allocating by system from HD.
- data can be stored permanent.

client - server integrated:


===========================

NOTE:
=====
- Now a user want to work on oracle db then we follow two steps mechanism.

1. connect to oracle db server.


===============================
- sqlplus tool

2. communicate with oracle db.


===============================
- SQL

SQLplus vs SQL:
===============
sqlplus sql
======= =====
1. it is a db tool. it is db language.

2. introduced by oracle introduced by IBM.


corporation.

3. connecting to oracle communicate with DB.


server
4. can work as an editor it provide languages to perform
for writing & executing some operations over DB.
sql queries. (DDL,DML,DQL/DRL,TCL,DCL)

step1: HOW TO CONNECT TO ORACLE DB SERVER:


===========================================
- go to all programs
5
- click on sqlplus icon
enter username : system(default user)
enter password : tiger (at the time of installation)
connected.
Note:
=====
problem-1:
===========
- when we connect to oracle db server with "system" user sometimes we face a problem is "TNS:
protocal adapter error". to overcome this problem follow the following solution is,

solution:
=========
- go to services
- go to oracleserviceORCL and click on it
> go to select "startup type" is "automatic"
> click on "start" button
> click on ok.

problem-2:
==========
Enter user-name: system/tiger

ERROR: ORA-28000: The account is locked.

solution:
=========
- go to click on sqlplus
- enter username : \sys as sysdba
- enter password : sys
connected.

syntax to lock / unlock a user in oracle db server:


====================================================
ALTER USER <USER NAME> ACCOUNT LOCK / UNLOCK;

EX: ALTER USER SYSTEM ACCOUNT UNLOCK;

SQL> CONNECT
ENTER USERNAME : system
ENTER PASSWORD : tiger
CONNECTED.

HOW TO CREATE A NEW USERNAME & PASSWORD IN ORACLE DB SERVER:


============================================================
SYNTAX:
=======
create user <username> identified by <password>;

Ex:
SQL> CREATE USER MYDB4PM IDENTIFIED BY ABC;

6
User created.

NOTE:
=====
- every new user is called as dummy user in oracle because this user is not having any privilege
(permissions) like connect,create table,insert data, .....etc.so that admin should given permissions to new
user with help of "grant" command.

- every new user is called as "schema" in oracle.whereas schema is nothing but it is a collection of
objects such as "tables,views,synonyms,procedure,triggers,....etc".

syntax to granting connect permission to MYDB4PM user:


======================================================
sql> conn
enter username : system/tiger
syntax:
=======
grant <privilege name> to <user name>;

ex:
grant connect to MYDB4PM;

SQL> CONN
Enter user-name: MYDB4PM/ABC
Connected.

HOW TO CHANGE A USER PASSWORD:


==============================
SQL> PASSWORD
Changing password for MYDB4PM
Old password:ABC
New password:123
Retype new password:123
Password changed

HOW TO CREATE A NEW PASSWORD IF WE FORGOT:


===========================================
SYNTAX:
=======
alter user <username> identified by <new password>;

Ex:
Enter user-name: system/tiger
Connected.
SQL> ALTER USER MYDB4PM IDENTIFIED BY MYDB4PM;

HOW TO SEE / VIEW USERNAMES IN ORACLE IF WE FORGOT:


==================================================
SYNTAX:
=======
select * from all_users;

7
Mr.Aravind
9154898074

Topic-3: SQL
======== ====
- sql is a db language which was introduced by "IBM".it is used to communicate with DB.
- sql is not case sensitive language that means we can write sql queries in either upper case / lower
case / combination of upper & lower cases.

Ex:
SELECT * FROM EMPLOYEE;----executed
select * from emp;----executed
SelecT * From Emp;----executed
- every sql query should ends with ";" semicolon.

Sub languages of SQL:


=====================

1. Data Definition Language(DDL):


==================================
- create
- alter
- alter - modify
- alter - add
- alter - rename
- alter - drop
- rename
- truncate
- drop

New features:
=============
> recyclebin
> flashback
> purge

2. Data Manipulation Language(DML):


===================================
- insert
- update
- delete

New commands:
============
- insert all
- merge

3. Data Query / Retrieval Language(DQL / DRL):


==============================================
- select

8
4. Transaction Control Language(TCL):
======================================
- commit
- rollback
- savepoint

5. Data Control Language(DCL):


==============================
- grant
- revoke
=============================================================
datatypes in oracle:
====================
- is an attribute to specify what type of value is storing into a column.

> numeric datatypes


> string datatypes / character datatypes
> long datatype
> date datatypes
> raw & long raw datatypes
> lob datatypes(large objects datatypes)

numeric datatypes:
===================
i) int
ii) number(p,s)

i) int:
======
- storing integer format values only.

Ex:
SNO int --------> SNO number(38)

SNO number(5)
==============
0
12
121
9999
10000
99999

ii) number(p,s):
=================
- storing integer and also float values.

> to store integer values : number(p)


> to store float values : number(p,s)

9
P(precision)
============
- counting all digits including left & right digits of decimal expression.

Ex:
56.25 precision = 4
8734.45 precision = 6
987970.134 precision = 9

S(scale):
=========
- counting the right side digits only.

Ex:
56.25 scale = 2 precision = 4
8734.45 scale = 2 precision = 6
97978960.6534 scale = 4 precision = 12

Ex:
price number(7,2)
=================
0.0 -----9999.99
10000.00
99999.99

> string datatypes / character datatypes:


=========================================
- storing string format data only.
- string can be represent with '<string>'.

Ex:

Name char(10)
=============
smith ----> error

'smith'---> allowed

123 -----> error

'123' ----> allowed

string format data


||
characters only alphanumeric string
string data data
|| ||
(a - z / A-Z) ( a-z / A-Z ,
0 - 9,
Ex: 'smith', 'SMITH' @,#,$,%,&,_ ,..etc)

10
Ex: pancardno,mailid,password,..
'[email protected]','sai@24'.

- string datatypes are again classified into two types:

1. Non-unicode datatypes
> are storing "localized data".(i.e english lang.only)

i) char(size)
ii) varchar2(size)

2. Unicode datatypes
> are storing "globalized data"(i.e all national lang's)

i) Nchar(size)
ii) Nvarchar2(size)

Here, "N" ---- national language.

i) char(size):
==============
- it fixed length datatype.(static)
- max. size is 2000 bytes
- 1 char = 1 byte.
- wasted memory

ename char(10)
==============
'hello'----> hello (5 bytes / 10 bytes = 5 bytes(wasted))

'hel' -----> hel( 3 bytes / 10 bytes = 7 bytes)

'he' ------> he (2 bytes / 10 bytes = 8 bytes)

ii) varchar2(size):
===================
- it is a variable length datatype.(dynamic)
- max.size 4000 bytes
- 1 char = 1 byte
- save memory

Ex:
ename varchar2(10)
=================
'hello'----> hello (5 bytes / 5 bytes = 0 bytes(wasted))
'hel' -----> hel( 3 bytes / 3 bytes = 0 bytes)
'he' ------> he (2 bytes / 2 bytes = 0 bytes)

i) Nchar(size):

11
===============
- it fixed length datatype.(static)
- max. size is 2000 bytes
- 1 char = 1 byte.
- wasted memory
- storing unicode char's(i.e all national language's char's)

ii) Nvarchar2(size):
=====================
- it variable length datatype.(dynamic)
- max. size is 4000 bytes
- 1 char = 1 byte.
- saved memory
- storing unicode char's(i.e all national language's char's)

Long datatype:
==============
- it is a variable length datatype(dynamic)
- max size 2GB.
- storing non-unicode & unicode char's.
- 1 char = 1 byte
- a table is having only one long datatype column.

Date datatypes:
===============
- storing date & time information.

i) date:
========
- can store date & time information of a particular day.
- here time is optional.when user not insert time information
then system will take '00:00:00 am' (or) '12:00:00 am' by
default.
- oracle database default date format is
'dd-mon-yyyy/yy hh:mi:ss am/pm'
1 1 2 1 1 1 ---------> 7 bytes

- date datatype is occupied a fixed memory i.e 7 bytes.


- date & time should be under single quotes.

ii) timestamp:
==============
- can store date & time along with milliseconds.

' dd-mon-yyyy/yy hh:mi:ss.ms am/pm '


1 1 2 1 1 1 4-------> 11 bytes.
- here 11 bytes are fixed memory.

Raw & Long raw:


===============

12
- are storing image file / audio file / video files in the form of 01010100101010010100 binary
format.

Raw : 2000 bytes


Long Raw : 2gb

- these datatypes are called as " binary datatypes" in oracle.

LOB datatypes:
==============
- large objects datatypes.

i) CLOB:
========
- character large object.
- can store non-unicode char's.
- max size is 4gb.

ii) NCLOB:
==========
- National character large object.
- can store unicode char's(all natonal lang's)
- max size is 4gb

iii) BLOB:
==========
- binary large object.
- store image/audio/video files in the form of
10010101010100 binary format.
- max size is 4gb.

non-unicode char's:
===================
char(size) -2000 bytes
varchar2(size) -4000 bytes
long -2gb
Clob - 4gb

unicode char's:
===================
Nchar(size) - 2000 bytes
Nvarchar2(size) - 4000 bytes
long - 2gb
NClob - 4gb

binary data:
============
raw - 2000 bytes
long raw - 2gb
Blob - 4gb
=============================================================

13
DDL:
====
create:
=======
- is used to create a new db object such as tables, views, synonyms, sequences, procedure,
functions,.....etc

syntax for creating a new table in oracle:


==========================================
syntax:
=======
create table <table name>(<column name1> <datatype>[size],<column name2> <datatype>[size],
...............................
...............................);(in a single table = 1000 columns)

step1:
======
username : system/tiger(admin)

step2:
======
create user mydb4pm identified by mydb4pm;

step3:
======
grant connect to mydb4pm;
grant create table to mydb4pm;

step4:
======
username : mydb4pm/mydb4pm(user)
EX:
create table students(stid int,sname char(10),sfee number(6,2)) )
to view the structure of a table in oracle:
===========================================
syntax:
=======
desc <table name>; (desc = describe)
Ex:
SQL> DESC STUDENTS;
to view list of tables in oracle:
================================
syntax:
=======
select * from tab;
Ex:
select * from tab;

2) ALTER:
=========
- is used to change the structure of a table.

14
- this command is having 4 sub commands those are,

i) Alter - Modify:
==================
- to change datatype and size of datatype of a particular column in a table.

syntax:
=======
alter table <table name> modify <column name> <new datatype>[new size];

EX:
SQL> ALTER TABLE STUDENTS MODIFY SNAME VARCHAR2(5);

ii) Alter - Add:


=================
- to add a new column to an existing table.

syntax:
=======
alter table <table name> add <new column name> <datatype>[size];

EX:
SQL> ALTER TABLE STUDENTS ADD SADDRESS VARCHAR2(10);

iii) Alter - Rename:


====================
- to change a column name in a table

syntax:
=======
alter table <table name> rename <column> <old column name> to <new column name>;

EX:
SQL> ALTER TABLE STUDENTS RENAME COLUMN SNAME TO STUDENTNAME;

iv) Alter - Drop:


=================
- to delete a column from a table.

syntax:
=======
alter table <table name> drop <column> <column name>;

EX:
SQL> ALTER TABLE STUDENTS DROP COLUMN SFEE;

3) RENAME:
==========
- to change a table name.

syntax:

15
=======
rename <old table name> to <new table name>;

EX:
SQL> RENAME STUDENTS TO SDETAILS;
SQL> RENAME SDETAILS TO STDUENTS;

4) TRUNCATE:
============
- to delete all rows but not columns from a table.
- permanent rows deletion. (we cannot restore)
- cannot delete a specific row because it doesn’t support "where" condition.

syntax:
=======
truncate table <table name>;

Ex:
SQL> TRUNCATE TABLE STUDENTS;

5) DROP:
========
- to drop / delete a table(i.e rows x columns) from database.

syntax:
=======
drop table <table name>;

EX:
DROP TABLE STUDENTS;

NOTE:
=====
from oracle10g enterprise edition once we drop a table from a database i.e temporary.so that we
can restore deleted table into database by using following commands are.

1. recyclebin:
==============
- it is similar to windows recyclebin in computer.
- it is a pre-defined / system defined table in oracle.
which is used to store the information about dropped tables.

To view the structure of recyclebin:


===================================
syntax:
=======
desc recyclebin;

EX:
SQL> DESC RECYCLEBIN;

16
To view the information of dropped tables in recyclebin:
=========================================================
syntax:
=======
select object_name,original_name from recyclebin;

EX:
SQL> SELECT OBJECT_NAME,ORIGINAL_NAME FROM RECYCLEBIN;

OBJECT_NAME
ORIGINAL_NAME
--------------------------------- -----------------------------------------------
BIN$37vn0OMvT0Cc7M3TIV9viA==$0 STUDENTS

2.FLASHBACK:
============
- this command is used to restore deleted tables into db memory.

syntax:
=======
flashback table <table name> to before drop;

Ex:
SQL> FLASHBACK TABLE STUDENTS TO BEFORE DROP;

3. PURGE:
=========
-this command is used to delete / drop a table permanently.

i) to delete a specific table from recyclebin permanently:


==========================================================
syntax:
=======
purge table <table name>;

EX:
SQL> PURGE TABLE TEST1;

ii) to delete all tables from recyclebin permanently:


==========================================================
syntax:
=======
purge recyclebin;

EX:
PURGE RECYCLEBIN;

iii) to delete table from database permanently:


================================================
syntax:
=======

17
drop table <table name> purge;

EX:
DROP TABLE STUDENTS PURGE;

NOTE:
=====
- here "recyclebin,flashback,purge are introduced in oracle10g enterprise edition".

2. Data Manipulation Language(DML):


===================================
i) Insert:
===========
- it is used to insert a new row(data) into a table.

syntax1:
========
insert into <table name> values(v1,v2,.....);

EX:SQL> CREATE TABLE EMP(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10));


SQL> INSERT INTO EMP VALUES(1021,'SMITH',25000);
NOTE: no.of columns in the table = no.of values in the query.
=====
syntax2:
========
insert into <tn>(required columns) values(required values);

EX:
SQL> INSERT INTO EMP(EID)VALUES(1023);
SQL> INSERT INTO EMP(EID,ENAME)VALUES(1024,'WARD');
SQL> INSERT INTO EMP(EID,ENAME,SAL)VALUES(1025,'MILLER',18000);
SQL> INSERT INTO EMP(SAL,EID,ENAME)VALUES(18000,1026,'JONES');

NOTE:
=====
- in this method we can insert values for required columns only and missing columns will take "null"
by default.

HOW TO INSERT MULTIPLE ROWS INTO A TABLE:


=========================================
i) & : is used to insert values to columns dynamically.

syntax1:
========
insert into <tn> values(&col1,&col2,......);

EX:
SQL> INSERT INTO EMP VALUES(&EID,'&ENAME',&SAL);
Enter value for eid: 1026
Enter value for ename: SCOTT
Enter value for sal: 35000

18
SQL> / (TO RE-EXECUTE THE LAST EXECUTED SQL QUERY IN SQLPLUS EDITIOR)

Enter value for eid: 1027


Enter value for ename: MILLER
Enter value for sal: 48000

SQL> /
..............................................................................

syntax2:
========
insert into <tn>(col1,col2,....)values(&COL1,...);

EX:
SQL> INSERT INTO EMP(EID)VALUES(&EID);
Enter value for eid: 1029

SQL> /
........................
=============================================================================
DQL/DRL:
========
i) select:
==========
- to retrieving all rows from a table at a time.
(or)
- to retrieving a specific row by using "where" condition.

syntax:
=======
select * / <list of columns> from <table name> [ where <condition> ];
Here, " * " ----- all columns in a table.

EX:
SELECT * FROM DEPT;
(OR)
SELECT DEPTNO,DNAME,LOC FROM DEPT;

SELECT * FROM EMP WHERE EMPNO=7788;


SELECT * FROM EMP WHERE JOB='CLERK';
SELECT EMPNO,ENAME,SAL FROM EMP;
SELECT * FROM EMP WHERE COMM IS NULL;

NOTE:
=====
- when we want to display data in proper systematically order of a big data tables in sql plus
environment then we need to set the following properties are

1) pagesize n:
===============

19
- by default a page can have 14 rows.
- "n" ---- no.of rows in a page.
- maximum size of pagesize property is 0-50000.

syntax:
=======
sql> set pagesize n;

ex: sql> set pagesize 500;

2) lines n:
===========
- by default each line will occupied 80 bytes of memory.
- here "n" no.of bytes in each line.
- maximum bytes of each line is 32767 bytes.

syntax:
=======
set lines n;
ex: set lines 100;

ALIAS NAMES:
============
- it is a temporary name.
- we can create alias names on two level in DB.
i) column level alias: - created alias name on columns.
================
ii) table level alias: - created alias name on table.
==============
syntax:
=======
select <column name1> <column alias name1>,
<column name2> <column alias name2>,......
from <table name> <table alias name>;

EX:
SQL> SELECT DEPTNO X,DNAME Y,LOC Z FROM DEPT D;
CONCATENATION OPERATOR( || ):
=============================
- adding two or more than two string expressions.
syntax:
========
<string1>||<string2>||<string3||......
EX:
SQL> SELECT 'Mr.'||ENAME||' '||'WORKING AS A'||' '||JOB FROM EMP;
OUTPUT:
=======
Mr.SMITH WORKING AS A CLERK
DISTINCT KEYWORD: - to eliminate duplicate values from a column.
==================

20
syntax: distinct <column name>
=======
EX:
SQL> SELECT DISTINCT JOB FROM EMP;
SQL> SELECT DISTINCT DEPTNO FROM EMP ORDER BY DEPTNO;

HOW TO CREATE A NEW TABLE FROM AN OLD TABLE:


============================================
i) with copy of all rows & columns:
===================================
syntax:
=======
create table <new table name> as select * from <old table name>;
(or)
create table <new tn> as select * from <old tn>[ where <true condition>];

EX:
SQL> CREATE TABLE NEWDEPT1 AS SELECT * FROM DEPT;
(OR)
SQL> CREATE TABLE NEWDEPT1 AS SELECT * FROM DEPT WHERE 1=1;

ii) with copy of columns but not rows:


=====================================
syntax:
=======
create table <new table name> as select * from <old table name> where <false condition>;

EX:
SQL> CREATE TABLE NEWDEPT2 AS SELECT * FROM DEPT WHERE 1=2;

iii) with specific columns:


===========================
syntax:
=======
create table <new table name> as select <list of columns> from <old table name>;

EX:
SQL> CREATE TABLE NEWEMP1 AS SELECT EMPNO,ENAME,SAL FROM EMP;

iv) with specific rows:


=======================
syntax:
=======
create table <new table name> as select * from <old table name> where <condition>;
EX:
SQL> CREATE TABLE NEWEMP2 AS SELECT * FROM EMP WHERE JOB='SALESMAN';

HOW COPY DATA FROM ONE TABLE TO ANOTHER TABLE:


==============================================
syntax:
=======

21
insert into <destination table name> select * from <source table name>;

rules:
======
1. no.of column in both tables should same.
2. order of columns and datatypes of columns in both tables must match.

EX:
SQL> INSERT INTO NDEPT2 SELECT * FROM DEPT;

INSERT ALL:
===========
- insert all command is used to insert rows into multiple table but rows must be an existing table.

syntax:
=======
insert all into <tn1> values(<col1>,<col2>,......)
into <tn2> values(<col1>,<col2>,.................)
into <tn3> values(<col1>,<col2>,.................)
..................................................
..................................................
into <tn n> values(<col1>,<col2>,................)
select * from <old table name>;

EX:
SQL> INSERT ALL INTO TEST1 VALUES(DEPTNO,DNAME,LOC)
INTO TEST2 VALUES(DEPTNO,DNAME,LOC)
INTO TEST3 VALUES(DEPTNO,DNAME,LOC)
SELECT * FROM DEPT;

MERGE: AFTER JOINS


======
FUNCTIONS:
==========
- to perform some task and must return a value.
1. pre-defined functions
> built- in functions
> use in SQL & PL/SQL.

2. user - defined functions


> created by user
> using in PL/SQL.

1. pre-defined functions:
=========================
i) single row functions (scalar functions)
ii) multiple row functions(grouping / aggregative functions)

i) single row functions:


========================
- these functions are returns a single value.

22
> numeric functions
> string / character functions
> date functions
> conversion functions
> analytical functions

syntax to call a function:


==========================
select <fname>(values) from dual;

What is dual?
=============
- pre-defined table.
- is also called as a "dummy table" in oracle.
- use to test function functionalities.
- is having only a single row & a single column.

to view the structure of dual table:


====================================
syntax: desc dual;
========
to view data of dual table:
============================
syntax:
=======
select * from dual;

Numeric functions:
===================
i) abs():
=========
- to convert (-ve) values into (+ve) values.
syntax: abs(n)
=======
EX:
SQL> SELECT ABS(-11) FROM DUAL;
ABS(-11) = 11
----------

EX:
SQL> SELECT ENAME,SAL,COMM,ABS(COMM-SAL) RESULT FROM EMP;

ii) ceil():
===========
- it return a value which is greater than or is equals to the given expression.
syntax: ceil(n)
=======
EX:
SQL> SELECT CEIL(9.0) FROM DUAL;
CEIL(9.0) = 9
----------

23
SQL> SELECT CEIL(9.3) FROM DUAL;
CEIL(9.3) = 10
----------
SQL> SELECT CEIL(9.8) FROM DUAL;
CEIL(9.8) = 10
----------

iii) floor():
=============
- it return a value which is less than or is equals to the given expression.
syntax: floor(n)
=======
EX:
SQL> SELECT FLOOR(9.0) FROM DUAL;
FLOOR(9.0) = 9
----------
SQL> SELECT FLOOR(9.3) FROM DUAL;
FLOOR(9.3) = 9
----------
SQL> SELECT FLOOR(9.8) FROM DUAL;
FLOOR(9.8) = 9
----------

iv) mod(): - it returns a remainder value.


===========
syntax: mod(m,n)
=======
EX:
SQL> SELECT MOD(10,2) FROM DUAL;
MOD(10,2) = (10%2) = reminder 0
----------
v) power(): - it returns the power of given expression.
===========
syntax: power(m,n)
=======
EX:
SQL> SELECT POWER(2,3) FROM DUAL;
POWER(2,3) =2 Power 3 = 8
---------
vi) round():
============
- it returns the nearest value to the given expression.
- consider 0.5 value.
syntax: round(expression,[decimal values])
EX:
SQL> SELECT ROUND(45.34) FROM DUAL;
ROUND(45.34) =45
SQL> SELECT ROUND(45.50) FROM DUAL;
ROUND(45.50) =46
SQL> SELECT ROUND(45.87) FROM DUAL;
ROUND(45.87) = 46

24
NOTE:
=====
if an expression is having less than 0.5 then add 0 to given expression.
if an expression is having greater / is equals to then add 1 to given expression.
0.3 < 0.5 ---> adding 0
0.5 >= 0.5 ---> adding 1
0.6 >= 0.5 ---> adding 1

Functions in oracle:
-------------------------------------
> To Perform Task & Must Return Value.
> Oracle Supports Two Types Functions. Those Are
1) Pre-Define / Built in Functions (Use in Sql & Pl/Sql)
2) User Define Functions (Use in Pl/Sql)
1) Pre-Define Functions:
---------------------------------------------
> These Are Again Classified into Two Categories.
A) Single Row Functions (Scalar Functions)
B) Multiple Row Functions (Grouping Functions)
Single Row Functions:
--------------------------------------------
> These Functions Are Returns A Single Row (Or) A Single Value.
> Numeric Functions
> String Functions
> Date Functions
> Conversion Functions
How To Call a Function:
------------------------------
Syntax:
---------------
Select <Fname>(Values) From Dual;
What Is Dual:
------------------------
> Pre-Define Table In Oracle.
> Having Single Column & Single Row
> Is Called As Dummy Table In Oracle.
> Testing Functions (Pre-Define & User Define) Functionalities.
To View Strc.Of Dual Table:
----------------------------------------------------
Sql> Desc Dual;
To View Data Of Dual Table:
----------------------------------------------------
Sql> Select * From Dual;
Numeric Functions:
--------------------------------------
1) Abs():
> Converts (-Ve) Value Into (+Ve) Value.
Syntax:
---------------
Abs(Number)
Ex:

25
Sql> Select Abs(-12) From Dual; --------> 12
Sql> Select Ename,Sal,Comm,Abs(Comm-Sal) From Emp;
2) Ceil():
> Returns A Value Which Is Greater Than Or Equal To Given Value.
Syntax:
---------------
Ceil(Number)
Ex:
Sql> Select Ceil(9.0) From Dual;------9
Sql> Select Ceil(9.3) From Dual;-------10
3) Floor():
Syntax:
Floor(Number)
Ex:
Sql> Select Floor(9.0) From Dual;------9
Sql> Select Floor(9.8) From Dual;------9

4) Mod():
Returns Remainder Value.
Syntax:
Mod(M,N)
Ex:
Sql> Select Mod(10,2) From Dual;-------0
5) Power():
The Power Of Given Expression
Syntax:
Power(M,N)
Ex:
Sql> Select Power(2,3) From Dual;----------8
Round():
> Nearest Value Given Expression.
Syntax:
Round(Number,[Decimal Places])
Ex:
Sql> Select Round(5.50) From Dual;------6
Sql> Select Round(32.456,2) From Dual;------32.46
Trunc:
-------
> Returns A Value Which Will Specified Number Of Decimal Places.
Syntax:
Trunc(Number,Decimal Places)
Ex:
Sql> Select Trunc(5.50) From Dual;---------5
Sql> Select Trunc(32.456,2) From Dual;----32.45

String Functions:
--------------------
Length():
------------------
> Length Of Given String.
Syntax:

26
Length(String)
Ex:
Sql> Select Length('Hello') From Dual;------------------------5
Sql> Select Length('Good Morning') From Dual;--------12
Sql> Select Ename,Length(Ename) From Emp;
Sql> Select * From Emp Where Length(Ename)=4;
Lower():
----------------
To Convert Upper Case Char's Into Lower Case Char's.
Syntax:
Lower(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Sql> Update Emp Set Ename=Lower(Ename) Where Job='Clerk';
Upper():
---------------
Syntax:
Upper(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Initcap():
------------------
To Convert First Char. Is Capital.
Syntax:
Initcap(String)

Ex:
Sql> Select Initcap('Hello') From Dual;
Sql> Select Initcap('Good Morning') From Dual;
Ltirm():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Left
Side
Of Given String.
Syntax:
Ltrim(String1[,String2])
Ex:
Sql> Select Ltrim(' Sai') From Dual;
Sql> Select Ltrim('Xxxxxxsai','X') From Dual;
Sql> Select Ltrim('123SAI','123') From Dual;
Rtrim():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Right Side Of Given String.
Syntax:
Rtrim(String1[,String2])
Ex:
Sql> Select Rtrim('Saixxxxxxx','X') From Dual;
Trim():
------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Both Sides Of Given String.
Syntax:

27
----------------
Trim('Trimming Char' From 'String')
Ex:
Sql> Select Trim('X' From 'Xxxxxxsaixxxx') From Dual;

Lpad():
------------
To Fill A String With Specific Char. On Left Side Of Given
String.
Syntax:
---------------
Lpad(String1,Length,String2)
Ex:
Sql> Select Lpad('Hello',10,'@') From Dual;
@@@@@Hello
Rpad():
-------------
To Fill A String With Specific Char. On Right Side Of Given
String.
Syntax:
---------------
Rpad(String1,Length,String2)
Ex:
Sql> Select Rpad('Hello',10,'@') From Dual;
Hello@@@@@
Concat():
-----------------
Adding Two String Expressions.
Syntax:
--------------
Concat(String1,String2)
Ex:
Sql> Select Concat('Good','Bye') From Dual;
Replace():
-------------------
To Replace One String With Another String.
Syntax:
---------------
Replace(String1,String2,String3)

Ex:
Sql> Select Replace('Hello','Ell','Xyz') From Dual;
Hxyzo
Sql> Select Replace('Hello','L','Abc') From Dual;
Heabcabco
Translate():
------------------------
To Translate A Single Char With Another Single Char.
Syntax:
--------------
Translate(String1,String2,String3)

28
Ex:
Sql> Select Translate('Hello','Elo','Xyz') From Dual;
Hxyyz
Sol: E = X , L=Y , O=Z
Hello => Hxyyz
Ex:
Sql> Select Ename,Sal,Translate(Sal,'0123456789','$B@Gh*V#T%')
Salary From Emp;
Ename Sal Salary
---------- --------------- -------------------------
Smith 800 T$$
Sol: 0=$,1=B,2=@,3=G,4=H,5=*,6=V,7=#,8=T,9=%.
Substr():
-----------------
It Returns Req.Substring From Given String Expression.
Syntax:
---------------
Substr(String1,<Starting Position Of Char.>,<Length Of Char's>)
Ex:
Sql> Select Substr('Hello',2,3) From Dual; Ell

Sql> Select Substr('Welcome',4,2) From Dual; Co


Sql> Select Substr('Welcome',-6,3) From Dual; Elc
Instr():
--------------
Returns Occurence Position Of A Char. In The Given String.
Syntax:
---------------
Instr(String1,String2,<Starting Position Of Char.>,<Occurence
Position Of Char.>)

Ex:
Sql> Select Instr('Hello Welcome','O') From Dual;---------> 5
Sql> Select Instr('Hello Welcome','Z') From Dual;-----> 0
Sql> Select Instr('Hello Welcome','O',1,2) From Dual;-----11
Sql> Select Instr('Hello Welcome','E',5,2) From Dual;-------13
Sql> Select Instr('Hello Welcome','E',1,4) From Dual;--------8
Note:
----------
Position Of Char's Always Fixed Either Count From Left To Right (Or) Right To Left.
Sol: Hello Welcome
12345 6 78910111213
Ex:
Sql> Select Instr('Hello Welcome','E',-1,3) From Dual;--------2
Sql> Select Instr('Hello Welcome','L',-4,3) From Dual;-------3
Sql> Select Instr('Hello Welcome','L',-6,3) From Dual;----------0

Date Functions:
------------------
1) Sysdate:
---------------------

29
> Current Date Information Of The System.
Ex:
Sql> Select Sysdate From Dual;
Sql> Select Sysdate+10 From Dual;
Sql> Select Sysdate-10 From Dual;
Add_Months():
--------------------------
> Adding No.Of Months To The Date.
Syntax:
---------------
Add_Months(Date,<No.Of Months>)
Ex:
Sql> Select Add_Months(Sysdate,3) From Dual;
Sql> Select Add_Months(Sysdate,-3) From Dual;
Last_Day():
---------------------
> Returns The Last Day Of The Month.
Syntax:
--------------
Last_Day(Date)
Ex:
Sql> Select Last_Day(Sysdate) From Dual; Next_Day():
--------------------
> Returns The Next Specified Day From The Given Date.
Syntax:
---------------
Next_Day(Date,'<Day Name>')

Ex:
Sql> Select Next_Day(Sysdate,'Sunday') From Dual;
Months_Between():
------------------------------------
> Returns No.Of Months Between Two Date Expressions.
Syntax:
---------------
Months_Between(Date1,Date2)
Ex:
Sql> Select Months_Between('05-Jan-81','05-Jan-80') From Dual;----- 12
Sql> Select Months_Between('05-Jan-80','05-Jan-81') From Dual;----- -12
Note: Here, Date1 Is Always Greater Than Date2 Otherwise
Oracle Returns Nagative Value.
Conversion Functions:
-------------------------
1. To_Char()
2. To_Date()
To_Char():
-------------------
> Date Type To Char Type To Display Date In Different Fromat.
Syntax:
To_Char(Date,[<Format>])
Year Formats:

30
---------------------------
Yyyy - 2020
Yy - 20
Year - Twenty Twenty
Cc - Centuary 21
Ad / Bc - Ad Yaer / Bc Year
Ex:
Sql> Select To_Char(Sysdate,'Yyyy Yy Year Cc Ad') From Dual;

To_Char(Sysdate,'Yyyyyyyearccad')
----------------------------------------------------------
2020 20 Twenty Twenty 21 Ad
Q: To Display Employee Who Are Joined In Year 1982
By Using To_Char() Function ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')=1982;
Q: To Display Employee Who Are Joined In Year 1980,1982,1987
By Using To_Char() Function ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')
In(1980,1982,1987);
Month Format:
----------------------------
Mm - Month Number
Mon - First Three Char From Month Spelling
Month - Full Name Of Month
Ex:
Sql> Select To_Char(Sysdate,'Mm Mon Month') From Dual;
To_Char(Sysdate,
----------------
08 Aug August
Sql> Select To_Char(Sysdate,'Mm Mon Month') From Dual;
To_Char(Sysdate,
----------------
08 Aug August
Q: To Display Employee Who Are Joined In Feb,May,Dec Months
By Using To_Char() ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Mm')
In(02,05,12);

Q: To Display Employee Who Are Joined In Feb 1981


By Using To_Char() ?
Sol:
Sql> Select * From Emp Where
To_Char(Hiredate,'Mmyyyy')='021981';
Day Formats:
-------------------------
Ddd - Day Of The Year.
Dd - Day Of The Month.
D - Day Of The Week

31
Sun - 1
Mon - 2
Tue - 3
Wen - 4
Thu - 5
Fri - 6
Sat - 7
Day - Full Name Of The Day
Dy - First Three Char's Of Day Spelling
Ex:Sql> Select To_Char(Sysdate,'Ddd Dd D Day Dy') From Dual;
To_Char(Sysdate,'Ddddd
----------------------------------------------
220 07 6 Friday Fri
Q: To Display Employee Who Are Joined On "Friday" By Using
To_Char() ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Day')='Friday';
Q: To Display Employee On Which Day Employees Are Joined ?
Sol:
Sql> Select Ename||' '||'Joined On'||' '||To_Char(Hiredate,'Day')
From Emp;

Note:
------
In Oracle Whenever We Using To_Char() And Also Within To_Char()
When We use Day / Month Format Then Oracle Server Internally
Allocate Some Extra Memory For Day/Month Format Of Data.
To Overcome The Above Problem That Is To Remove Extra

Memory Which Was Allocate By Oracle Server Then We Use A Pre-


Define Specifier Is

Called "Fm" (Fill Mode).


Ex:
Select * From Emp Where To_Char(Hiredate,'Fmday')='Friday';
Quater Format:
----------------------------
Q - One Digit Quater Of The Year
1 - Jan - Mar
2 - Apr - Jun
3 - Jul - Sep
4 - Oct - Dec
Ex:
Sql> Select To_Char(Sysdate,'Q') From Dual;
T
---
3
Q : Who Are Joined In 2ND Quater Of 1981 ?
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')='1981'
And To_Char(Hiredate,'Q')=2;

32
Week Format:
--------------------------
Ww - Week Of The Year
W - Week Of Month
Ex:
Sql> Select To_Char(Sysdate,'Ww W') From Dual;

To_C
---------
32 2
Time Format:
-------------------------
Hh - Hour Part
Hh24- 24 Hrs Fromat
Mi - Minute Part
Ss - Seconds Part
Am / Pm - Am Tme (Or) Pm Time
Ex:
Sql> Select To_Char(Sysdate,'Hh:Mi:Ss Am') From Dual;
To_Char(Sys
------------------------
12:04:21 Pm
To_Date():
------------------
To Convert Char Type To Oracle Date Format Type.
Syntax:
To_Date(String[,Fromat])
Ex:
Sql> Select To_Date('08/August/2020') From Dual;
To_Date('
---------
08-Aug-20
Sql> Select To_Date('08-Aug-2020')+10 From Dual;
To_Date('
---------
18-Aug-20

Multiple Row Functions:


-----------------------------------------------
These Functions Are Returns Either Group Of Values (Or) A Single Value.
Sum():
-----------
> It Returns Sum Of A Specific Column Values.
Ex:
Sql> Select Sum(Sal) From Emp;
Sql> Select Sum(Sal) From Emp Where Job='Clerk';
Avg():
----------
> It Returns Average Of A Specific Column Values.
Ex:
Sql> Select Avg(Sal) From Emp;

33
Sql> Select Avg(Sal) From Emp Where Deptno=10;
Min():
----------
> It Returns Min.Value From Group Of Values.
Ex:
Sql> Select Min(Hiredate) From Emp;
Sql> Select Min(Hiredate) From Emp Where Job='Manager';
Sql> Select Min(Sal) From Emp;
Max():
-----------
> It Returns Max.Value From Group Of Values.
Ex:
Sql> Select Max(Sal) From Emp;
Count():
----------------
> It Returns No.Of Rows In A Table / No.Of Values In A Column
> Three Types,
I) Count(*)
Ii) Count(<Column Name>)
Iii) Count(Distinct <Column Name>)

Ex:
Test
--------
Sno Name
--- -----
101 A
102 B
103
104 C
105 A
106 C
Count(*):
----------------
> Counting All Rows (Duplicates & Nulls) In A Table.
Ex:
Sql> Select Count(*) From Test;
Count(*)
------------------
6
Count(<Column Name>):
--------------------------------------------
> Counting All Values Including Duplicate Values But Not Null Values
From A Column.
Ex:
Sql> Select Count(Name) From Test;
Count(Name)
-----------------------
5
Count(Distinct <Column Name>):
--------------------------------------------------------------

34
> Counting Unique Values From A Column.Here "Distinct" Keyword
Is Eliminating Duplicate Values.
Ex:
Sql> Select Count(Distinct Name) From Test;------- 3

CLAUSES:
========
- is a statement which is used to add to sql query for providing some facilities are "filtering rows, sorting
values,grouping similar data,finding sub total and grand total" based on columns automatically.

- where
- order by
- group by
- having
- rollup
- cube

where:
=====
- is used to filtering rows before grouping data in a table.
- is used in "select,update,delete" commands only.

syntax:
=======
where <filtering condition>

EX:
select * from emp where empno=7788;
update emp set sal=45000 where job='clerk';
delete from emp where deptno=10;

ORDER BY:
=========
- to arrange values in ascending / descending order.
- by default 'ascending' order.
- if we want to arrange values in descending order
then we a keyword is called as "desc".
- use in "select" command only.

syntax:
=======
select * / <list of columns> from <tn> order by
<col1> asc/desc,<col2> asc/desc,.......;

EX:
SQL> SELECT * FROM EMP ORDER BY ENAME;
SQL> SELECT ENAME FROM EMP ORDER BY ENAME;
SQL> SELECT ENAME FROM EMP ORDER BY ENAME DESC;

SQL> SELECT * FROM EMP ORDER BY HIREDATE;


SQL> SELECT * FROM EMP ORDER BY HIREDATE DESC;

35
SQL> SELECT * FROM EMP ORDER BY SAL;
SQL> SELECT * FROM EMP ORDER BY SAL DESC;

EX: waq to display employees who are working under deptno is 30 and arrange those employees salaries in
descending order?
SQL> SELECT * FROM EMP WHERE DEPTNO=30 ORDER BY SAL DESC;

EX: waq to arrange employees deptno's in ascending order and those employees salaries are arrange in
descending from each deptno wise?
SQL> SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC;

NOTE:
=====
- order by clause can apply on not only column names even though we can apply on position of columns in
select query.

EX:
SELECT * FROM EMP ORDER BY 6;
SELECT EMPNO,ENAME,SAL FROM EMP ORDER BY 3;
SELECT ENAME,SAL FROM EMP ORDER BY 2;
SELECT SAL FROM EMP ORDER BY 1;

ORDER BY CLAUSE ON NULLS:


=========================
case-1: by default ascending order:
==================================
EX: SQL> SELECT * FROM EMP ORDER BY COMM;
FIRST : NUMBERS
LATER : NULLS

case-2: by default descending order:


==================================
EX: SQL> SELECT * FROM EMP ORDER BY COMM DESC ;
FIRST : NULLS
LATER : NUMBERS

NOTE:
====
- to arrange the above nulls in correct order by order by clause then we need "null clauses" those are,
1. nulls first :
================
- it will arrange nulls first and later numbers in ascending order.
Ex: SQL> SELECT * FROM EMP ORDER BY COMM NULLS FIRST;

2. nulls last:
==============
- it will arrange numbers first and later nulls in descending order.

EX:
SQL> SELECT * FROM EMP ORDER BY COMM DESC NULLS LAST;

36
GROUP BY:
=========
- is used to grouping similar data based on columns automatically.
- when we use "group by" clause we must use "grouping / aggregative" functions to get the final result.
- can be used in "select" command only.

syntax:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....from <table name> group by <col1>,<col2>,........;

Ex:
group by
|
job( count(job))
|
clerk || salesman || president || manager || analyst
clerk salesman manager analyst
clerk salesman manager
clerk salesman
(4) (4) (1) (3) (2)

EX: waq to find out the no.of employees from each job wise?
SQL> SELECT JOB,COUNT(JOB) NO_OF_EMPLOYEES FROM EMP GROUP BY JOB;

EX: waq to find out the no.of employees from each job along with their deptno wise?
SQL> SELECT JOB,DEPTNO,COUNT(JOB) FROM EMP GROUP BY JOB,DEPTNO;

EX: waq to display sum of salaries from each deptno wise?


SQL> SELECT DEPTNO,SUM(SAL) SUM_OF_SALARY FROM EMP GROUP BY DEPTNO ORDER BY DEPTNO;

EX: waq to display no.of employees,sum of salary,min,max and avg salary of each deptno wise?
SQL> SELECT DEPTNO,COUNT(DEPTNO) NO_OF_EMPLOYEES,SUM(SAL) SUM_OF_SALARY,MIN(SAL)
MIN_SALARY,MAX(SAL) MAX_SALARY,AVG(SAL) AVG_SAL FROM EMP GROUP BY DEPTNO ORDER BY
DEPTNO;

HAVING:
=======
- to filtering rows after grouping data in a table.
- it can use after "group by" clause.
syntax:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....
from <table name> group by <col1>,<col2>,.....having <filtering condition>;

EX: waq to display jobs in which job the no.of employees are more than 3?
SQL> SELECT JOB,COUNT(JOB) NO_OF_EMPLOYEES FROM EMP GROUP BY JOB HAVING COUNT(JOB)>3;

EX: waq to display deptno's in which deptno the sum of salary is less than to 10000?
SQL> SELECT DEPTNO,SUM(SAL) SUM_OF_SALARY FROM EMP GROUP BY DEPTNO HAVING SUM(SAL)
<10000 ORDER BY DEPTNO;

37
ALL CLAUSES IN A SINGLE SELECT QUERY:
=====================================
SYNTAX:
=======
select <col1>,<col2>,.....,<aggregative function name1>,....
from <table name>
[where <filtering condition>
group by <col1>,<col2>,.....
having <filtering condition>
order by <column name1> <asc/desc>,......];

EX: SQL> SELECT DEPTNO,COUNT(DEPTNO) FROM EMP WHERE SAL>1000 GROUP BY DEPTNO HAVING
COUNT(DEPTNO)>3 ORDER BY DEPTNO DESC;

ROLLUP & CUBE:


==============
- to find out sub total & grand total based on columns automatically.
- rollup is find out sub & grand total based on a single column.
- cube is find out sub & grand total based on multiple columns.
- these two clauses are working with "group by" clause.

syntax for rollup:


==================
select <col1>,<col2>,.....,<aggregative function name1>,....
from <table name> group by rollup(<col1>,<col2>,.....);
....... ...........
||
operational supporting column columns

rollup with a single column:


============================
EX: SQL> SELECT DEPTNO,COUNT(DEPTNO) FROM EMP GROUP BY ROLLUP(DEPTNO);

rollup with MULTIPLE columns:


============================
EX: SQL> SELECT DEPTNO,JOB,COUNT(DEPTNO) FROM EMP GROUP BY ROLLUP(DEPTNO,JOB);
EX: SQL> SELECT JOB,DEPTNO,COUNT(JOB) FROM EMP GROUP BY ROLLUP(JOB,DEPTNO);

JOINS:
======
- generally in RDBMS data can be organized into multiple tables.so that from those multiple tables
if we want to retrieval the required data then we use a technique is called as "joins".
- joins are used to retrieval data from multiple tables at a time.
- joins statements can be written in two ways:

1. Non-ansi joins(oracle8i version)


=================
> equi join
> non-equi join
> self join

38
2. Ansi joins(oracle9i version)
=============
> inner join
> outer join - left outer join - right outer join - full outer join
> cross join
> natural join

Why Ansi joins:


===============
- non-ansi joins are not a portability so that we use ansi joins because ani joins are portability it means that
we can move a join statement from one to another database without doing any modification as it is we can
move it.

Note:
=====
1. to join two or more than two tables by using "where" clause condition then we called as "non-ansi"
joins.

syntax:
=======
select * from <tn1>,<tn2> where <joining condition>;

2. to join two or more than two tables by using "on" clause condition then we called as "ansi" joins.

syntax:
=======
select * from <tn1> <join key> <tn2> on <joining condition>;

1. equi / inner join:


=====================
- when we retrieve data from multiple tables based on an " = " operator is called as equi / inner join.

- when we use equi join then we should have a common column in both tables.
- datatypes of columns must be match.
- having relationship in between tables is just optional.
- it retrieval matching rows only.

Ex: waq to retrieve course and the corresponding student details from course,student tables by using equi
join?

non-ansi format:
================
SQL> SELECT * FROM COURSE,STUDENT WHERE COURSE.CID =STUDENT.CID;
(OR)
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID =S.CID;
(OR)
SQL> SELECT STID,SNAME,CNAME,CFEE FROM COURSE C,STUDENT S
WHERE C.CID=S.CID;

ansi format:
================

39
SQL> SELECT * FROM COURSE INNER JOIN STUDENT ON COURSE.CID =STUDENT.CID;
(OR)
SQL> SELECT * FROM COURSE C INNER JOIN STUDENT S ON C.CID =S.CID;
(OR)
SQL> SELECT STID,SNAME,CNAME,CFEE FROM COURSE C INNER JOIN STUDENT S
ON C.CID=S.CID;

WHERE C.CID= S.CID


(OR)
ON C.CID=S.CID

COURSE STUDENT
====== =======
CID CID
==== ===
11
23
32
3
NULL
RULE OF JOINS:
==============
a row in a table is comparing with all rows of another table.

EX: waq to display students who are joined in oralce course?

non-ansi join:
==============
SQL> SELECT STID,SNAME,CNAME FROM COURSE C,STUDENT S WHERE C.CID=S.CID AND
CNAME='ORACLE';

ansi join:
==============
SQL> SELECT STID,SNAME,CNAME FROM COURSE C inner join STUDENT S on C.CID=S.CID AND
CNAME='ORACLE';

EX:
waq to display employees who are working in the location is chicago?

non-ansi join:
===============
SQL> SELECT ENAME,LOC FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO AND LOC='CHICAGO';

ansi-join
=========
SQL> SELECT ENAME,LOC FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO AND LOC='CHICAGO';

EX:
waq to display sum of salaries of each department names wise?

non-ansi join:

40
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO GROUP BY DNAME;

ansi join:
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO GROUP BY
DNAME;

EX:
waq to display sum of salaries of department names in which department total salary is more than 10000?
non-ansi join:
==============
SQL> SELECT DNAME,SUM(SAL) FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO GROUP BY DNAME
HAVING SUM(SAL)>10000;

ansi join:
==========
SQL> SELECT DNAME,SUM(SAL) FROM EMP E inner join DEPT D on E.DEPTNO=D.DEPTNO GROUP BY
DNAME HAVING SUM(SAL)>10000;

OUTER JOINS:
============
- retrieving matching and also unmatching rows from multiple tables.

i) left outer join:


===================
- retrieval matching & unmatching rows from left side table AND matching rows from the right side table.

ansi join:
==========
SQL> SELECT * FROM COURSE C LEFT OUTER JOIN STUDENT S ON C.CID=S.CID;

non-ansi join:
==============
- when we want to write outer joins statements in non-ansi format then we use a join operator is called as
(+).

EX:
SELECT * FROM COURSE C,STUDENT S WHERE C.CID=S.CID(+);

ii) right outer join:


====================
- retrieving matching rows from both tables but unmatching rows from the right side table only.

ansi join:
==========
SQL> SELECT * FROM COURSE C RIGHT OUTER JOIN STUDENT S ON C.CID=S.CID;

non-ansi join:
==============
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID(+)=S.CID;

41
iii) full outer join:
=====================
- retrieving matching & unmatching rows from both tables.

ansi join:
==========
SQL> SELECT * FROM COURSE C FULL OUTER JOIN STUDENT S ON C.CID=S.CID;

non-ansi join:
==============
SQL> SELECT * FROM COURSE C,STUDENT S WHERE C.CID(+)=S.CID
2 UNION
3 SELECT * FROM COURSE C,STUDENT S WHERE C.CID=S.CID(+);

NON-EQUI JOIN:
==============
- when we retrieving data from multiple tables based on any operator except an " = " operator.
- we can use the following operators are ,"<,>,<=,>=,!=,and,between,or,.....etc"

non-ansi:
=========
SQL> SELECT * FROM TEST11 T1,TEST12 T2 WHERE T1.SNO>T2.SNO;

ansi:
=====
SQL> SELECT * FROM TEST11 T1 join TEST12 T2 on T1.SNO>T2.SNO;

EX: waq to display employees whose salary is between low salary and high salary?

non-ansi:
=========
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP,SALGRADE WHERE SAL BETWEEN LOSAL AND HISAL;
(or)
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP,SALGRADE WHERE (SAL>=LOSAL) AND (SAL<=HISAL);

ansi:
=====
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP join SALGRADE on SAL BETWEEN LOSAL AND HISAL;
(or)
SQL> SELECT ENAME,SAL,LOSAL,HISAL FROM EMP join SALGRADE on (SAL>=LOSAL) AND (SAL<=HISAL);

CROSS JOIN:
===========
- joining two or more than two tables without any condition.
- each row in a table will joins with each row another tablefor example a table is having (m) no.of rows and
other table is having (n) no.of rows then the result is (mxn) rows.

Ex:
non-ansi:
SQL> SELECT * FROM COURSE,STUDENT;

42
ansi:
SQL> SELECT * FROM COURSE CROSS JOIN STUDENT;

Ex:
non-ansi:
=========
SQL> SELECT I1.INAME,I1.PRICE,I2.INAME,I2.PRICE, I1.PRICE+I2.PRICE TOTAL_AMOUNT FROM ITEMS1
I1,ITEMS2 I2;

ansi:
=====
SQL> SELECT I1.INAME,I1.PRICE,I2.INAME,I2.PRICE, I1.PRICE+I2.PRICE TOTAL_AMOUNT FROM ITEMS1 I1
cross join ITEMS2 I2;

INAME PRICE INAME PRICE TOTAL_AMOUNT


---------- ---------- ---------- ---------- ------------
PIZZA 180 PEPSI 20 200
PIZZA 180 COCACOLA 15 195

NATURAL JOIN:
============
- is similar to equi join.

Equi join natural join


========= =============
- not avoid duplicate columns - avoiding duplicate columns in result set. in result set

- equi join condition - this join condition can be can be written by user. written by system by default.
(explicit condition) (implicit condition)

EX:
ansi:
SQL> SELECT * FROM COURSE C NATURAL JOIN STUDENT S;

non-ansi:
=========
SQL> SELECT S.CID,CNAME,CFEE,STID,SNAME FROM COURSE C,STUDENT S WHERE C.CID=S.CID;

SELF JOIN:
==========
- it can use on a single table operations.
- joining a table by itself is called as "self join".
- when we implement self join we should create alias names on a table otherwise we cannot go for self
join.
- once we created alias name on a table internally system is preparing a virtual table on each alias name.
Ex:
emp e1,emp e2,emp e3

- we can create any no.of alias names on a single table but each alias name should be different.

43
purpose of self join:
======================
case-1:
=======
comparing a single column values by it self with in the table.

case-2:
=======
comparing two different columns values to each other with in the table.

comparing a single column values by it self with in the table:


==============================================================
EX:
waq to display employees who are working in the same location the employee "smith" is also working?

non-ansi:
==========
SQL> SELECT T1.ENAME,T1.LOC FROM TEST T1,TEST T2 WHERE T1.LOC=T2.LOC AND T2.ENAME='SMITH';

ansi:
==========
SQL> SELECT T1.ENAME,T1.LOC FROM TEST T1 join TEST T2 on T1.LOC=T2.LOC AND T2.ENAME='SMITH';

OUTPUT:
ENAME LOC
---------- ----------
SMITH HYD
JONES HYD

EX:
waq to display employees whose salary is same as the employee 'scott'?
non-ansi
===========
SQL> SELECT E1.ENAME,E1.SAL FROM EMP E1,EMP E2 WHERE E1.SAL=E2.SAL AND E2.ENAME='SCOTT';

ansi
===========
SQL> SELECT E1.ENAME,E1.SAL FROM EMP E1 join EMP E2 on E1.SAL=E2.SAL AND E2.ENAME='SCOTT';

ENAME SAL
---------- ----------
SCOTT 3000
FORD 3000

case-2:
=======
comparing two different columns values to each other with in the table.
========================================================================
Ex:
waq to find out managers and their employees from emp table?

44
SQL> SELECT M.ENAME MANAGERS,E.ENAME EMPLOYEES FROM EMP E,EMP M WHERE
M.EMPNO=E.MGR;

EX:
waq to display employees who are joined before their manager?
SQL> SELECT E.ENAME EMPLOYEES,E.HIREDATE E_DOJ, M.ENAME MANAGERS,M.HIREDATE M_DOJ FROM
EMP E,EMP M WHERE M.EMPNO=E.MGR AND E.HIREDATE<M.HIREDATE;

HOW TO JOIN MORE THAN TWO TABLES:


=================================
SYNTAX FOR NON-ANSI JOINS:
==========================
SELECT * FROM <TN1>,<TN2>,<TN3>,<TN4>,.........WHERE <JOIN CONDITION1>
AND <JOIN CONDITION2> AND <JOIN CONDITION3> AND...........;

EQUI JOIN:
==========
EX:
SQL> SELECT * FROM COURSE C,STUDENT S,REGISTER R,T4 WHERE C.CID=S.CID AND S.CID=R.CID;

SYNTAX FOR ANSI JOINS:


==========================
SELECT * FROM <TN1> <JOIN KEY><TN2> ON <JOIN CONDITION1>
<JOIN KEY> <TN3> ON <JOIN CONDITION2>
<JOIN KEY> <TN4> ON <JOIN CONDITION3>
.......................................
.......................................
<JOIN KEY> <TN n> ON <JOIN CONDIITON n-1);

INNER JOIN:
============
SQL> SELECT * FROM COURSE C INNER JOIN STUDENT S ON C.CID=S.CID INNER JOIN REGISTER R ON
S.CID=R.CID;

SET OPERATORS vs JOINS:


========================
SET OPERATORS JOINS
============= ======
1. combined data in row wise. 2. COLUMNS WISE

2. VERTICAL MANNER 2. HORIZENTAL MANNER

3. THE STRUCTURE OF TABLES 3. DIFFERENT STRC.


SHOULD BE SIMILAR.

DATA INTEGRITY:
===============
- to maintain accurate & consistency data in database tables.
1. declarative integrity

45
- pre-defined rules
- by using constraints(sql)

2. procedural integrity
- user-defined rules
- by using triggers(pl/sql)

1. declarative integrity:
==========================
i) entity integrity
ii) referencial integrity
iii) domain integrity

i) entity integrity:
===================
- entity = table
- it ensure that each row in a table should be unique.
- can be implemented by using "unique , primary key".

ii) referencial integrity:


===========================
- to making relationship between tables.
- by using "foreign key" / " references key".

iii) domain integrity:


======================
- domain = a column.
- to check a value before inserting into a column.
- by using "check,default,not null"

constraints:
============
- are used to restricted unwanted data/information into a table.

types of constraints:
======================
i) unique
ii) not null
iii) check
iv) primary key
v) foreign key
vi) default

Note:
=====
- it can be defined at two levels.

i) column level constraint:


============================
- we defined at each column wise.

46
syntax:
=======
create table <tn>
(<column name1> <dt>[size] <constraint type>,
<column name2> <dt>[size] <constraint type>,
...........................................
);

ii) table level constraint:


===========================
- we defined constraint at table level(i.e end of the table definition).

syntax:
========
create table <table name>
(
<column name1> <dt>[size],
<column name2> <dt>[size],
<column name3> <dt>[size],
........................
.........................
<constraint type>(<col1>,<col2>,......)----> composite constraint.
);

Unique:
=======
- to restricted duplicates but allowed nulls.

EX:
column level:
==============
SQL> CREATE TABLE TEST1(SNO INT UNIQUE,NAME VARCHAR2(10) UNIQUE);

TESTING:
INSERT INTO TEST1 VALUES(1,'A');---ALLOWED
INSERT INTO TEST1 VALUES(1,'A');---NOT ALLOWED
INSERT INTO TEST1 VALUES(NULL,NULL);--ALLOWED

table level:
============
SQL> CREATE TABLE TEST2(SNO INT,NAME VARCHAR2(10),UNIQUE(SNO,NAME));
----------------
TESTING: |
SQL> INSERT INTO TEST2 VALUES(1,'A');----ALLOWED composite unique
SQL> INSERT INTO TEST2 VALUES(1,'A');---NO constraint
SQL> INSERT INTO TEST2 VALUES(1,'B');---ALLOWED

NOT NULL:
==========
- to restricted nulls but allowed duplicates.
- it cannot defined at table level.

47
EX:
column level:
=============
SQL> CREATE TABLE TEST3(SNO INT NOT NULL,NAME VARCHAR2(10) NOT NULL);

TESTING:
SQL> INSERT INTO TEST3 VALUES(1,'A');---ALLOWED
SQL> INSERT INTO TEST3 VALUES(1,'A');---ALLOWED
SQL> INSERT INTO TEST3 VALUES(NULL,NULL);----NO

PRIMARY KEY:
============
- to restricted duplicates & nulls.
- is a combination of "unqiue and not null".
- a table is having only one PK.

EX:
column level:
=============
SQL> CREATE TABLE TEST4(EID INT PRIMARY KEY,ENAME VARCHAR2(10));

TESTING:
SQL> INSERT INTO TEST4 VALUES(101,'SMITH');---ALLOWED
SQL> INSERT INTO TEST4 VALUES(101,'ALLEN');---NO
SQL> INSERT INTO TEST4 VALUES(NULL,'ALLEN');---NO

table level:
============
SQL> CREATE TABLE TEST5(EID INT,ENAME VARCHAR2(10),primary key(eid,ename));
-----------------------
TESTING: <composite PK>
SQL> INSERT INTO TEST5 VALUES(101,'SMITH');---ALLOWED
SQL> INSERT INTO TEST5 VALUES(101,'ALLEN');---allowed
SQL> INSERT INTO TEST5 VALUES(101,'ALLEN');---NO
CHECK:
======
- to check values before inserting into a column.

Ex:
column level:
=============
SQL> CREATE TABLE TEST6(ENAME VARCHAR2(10) UNIQUE NOT NULL,
SAL NUMBER(10) CHECK(SAL>8000));

TESTING:
INSERT INTO TEST6 VALUES('SMITH',7500);---NOT ALLOWED
INSERT INTO TEST6 VALUES('SMITH',8001);---ALLOWED

table level:
============

48
SQL> CREATE TABLE TEST7(ENAME VARCHAR2(10),SAL NUMBER(10),
CHECK(ENAME=UPPER(ENAME) AND SAL>=8000));

TESTING:
SQL> INSERT INTO TEST7 VALUES('sai',8500);---NOT
SQL> INSERT INTO TEST7 VALUES('SAI',7500);---NOT
SQL> INSERT INTO TEST7 VALUES('SAI',8500);---ALLOWED

FOREIGN KEY:
============
- to making relationship between tables.

rules:
======
1. common column in both tables.
2. common column datatype must match in both tables.
3. a table should have a PK and another table should have FK.
(PK and FK column should be common column in tables)
4. a PK table is called as parent and a FK table is called as child.
5. a FK column values must be PK column values only.

Ex: (parent) (child)


sno(pk) sno(fk)
======= =======
11
22
33
4---error

6. by default a FK column is allowed duplicates & nulls.

Ex: (parent) (child)


sno(pk) sno(fk)
======= =======
11
22
33
1
1
2
2
3
null (orphan)

Ex:
SQL> CREATE TABLE DEPT1(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE

SQL> INSERT INTO DEPT1 VALUES(10,'JAVA');


SQL> INSERT INTO DEPT1 VALUES(20,'DB');
SQL> COMMIT;

49
SQL> CREATE TABLE EMP1(EID INT,ENAME VARCHAR2(10),DEPTNO INT REFERENCES DEPT1(DEPTNO));---
CHILD TABLE

SQL> INSERT INTO EMP1 VALUES(1,'SMITH',10);


SQL> INSERT INTO EMP1 VALUES(2,'ALLEN',10);
SQL> INSERT INTO EMP1 VALUES(3,'JAMES',20);
...........................................
...........................................

NOTE:
=====
- once we created relationship between tables there are two rules are come into picture those are:

rule-1(insertion)
=================
- we cannot insert values into child table those values are not found in parent table.
NO PARENT = NO CHILD

Ex:
INSERT INTO EMP1 VALUES(6,'ADAMS',30);
ERROR at line 1:
ORA-02291: integrity constraint (MYDB4PM.SYS_C007588) violated -
parent key not found.

rule-2(deletion)
=================
- we cannot delete a row from parent table those row values are existing in child table without addressing
to child.

EX:
DELETE FROM DEPT1 WHERE DEPTNO=10;

ERROR at line 1:
ORA-02292: integrity constraint (MYDB4PM.SYS_C007588) violated -
child record found.

HOW TO ADDRESSING TO CHILD?


===========================
i) on delete cascade
ii) on delete set null

Ex with on delete cascade:


==========================
- it ensure that once we delete a row from a parent table then the corresponding child rows also deleted
from child table automatically.

Ex:
SQL> CREATE TABLE DEPT2(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE

50
SQL> INSERT INTO DEPT2 VALUES(10,'JAVA');
SQL> INSERT INTO DEPT2 VALUES(20,'DB');
SQL> COMMIT;

SQL> CREATE TABLE EMP2(EID INT,ENAME VARCHAR2(10),DEPTNO INT


REFERENCES DEPT2(DEPTNO) ON DELETE CASCADE);---CHILD TABLE

SQL> INSERT INTO EMP2 VALUES(1,'SMITH',10);


SQL> INSERT INTO EMP2 VALUES(2,'ALLEN',10);
SQL> INSERT INTO EMP2 VALUES(3,'JAMES',20);
...........................................
...........................................

TESTING:
========
DELETE FROM DEPT2 WHERE DEPTNO=10;---ALLOWED

Ex with on delete set null:


==========================
- it ensure that once we delete a row from a parent table then the corresponding child rows are convert
into null in child table automatically.

Ex:
SQL> CREATE TABLE DEPT3(DEPTNO INT PRIMARY KEY,
DNAME VARCHAR2(10));---PARENT TABLE

SQL> INSERT INTO DEPT3 VALUES(10,'JAVA');


SQL> INSERT INTO DEPT3 VALUES(20,'DB');
SQL> COMMIT;

SQL> CREATE TABLE EMP3(EID INT,ENAME VARCHAR2(10),DEPTNO INT


REFERENCES DEPT3(DEPTNO) ON DELETE SET NULL);---CHILD TABLE

SQL> INSERT INTO EMP3 VALUES(1,'SMITH',10);


SQL> INSERT INTO EMP3 VALUES(2,'ALLEN',10);
SQL> INSERT INTO EMP3 VALUES(3,'JAMES',20);
...........................................
...........................................

TESTING:
========
DELETE FROM DEPT3 WHERE DEPTNO=10;---ALLOWED

PRE-DEFINED CONSTRAINT KEY NAME:


================================
EX:
SQL> CREATE TABLE TEST8(SNO INT PRIMARY KEY,
2 NAME VARCHAR2(10) UNIQUE);

TESTING
SQL> INSERT INTO TEST8 VALUES(1,'A');

51
SQL> INSERT INTO TEST8 VALUES(1,'B');--ERROR
ERROR at line 1:
ORA-00001: unique constraint (MYDB4PM.SYS_C007596) violated

COLUMN_NAME CONSTRAINT_KEY_NAME
=========== ===================
SNO SYS_C007596
NAME SYS_C007597

USER DEFINED CONSTRAINT KEY NAME:


=================================
SYNTAX:
=======
CREATE TABLE <TN>
(
<COLUMN NAME1> <DT>[SIZE] <CONSTRAINT> <UD CONSTRAINT KEY NAME> <CONSTRAINT TYPE>,
<COLUMN NAME2> <DT>[SIZE] <CONSTRAINT> <UD CONSTRAINT KEY NAME> <CONSTRAINT TYPE>,
..................................................................................
..................................................................................
);

EX:
SQL> CREATE TABLE TEST9
2 (
3 SNO INT CONSTRAINT SNO_PK PRIMARY KEY,
4 NAME VARCHAR2(10) CONSTRAINT NAME_UQ UNIQUE
5 );

Table created.

SQL> INSERT INTO TEST9 VALUES(1,'A');


SQL> INSERT INTO TEST9 VALUES(1,'B')
ERROR at line 1:
ORA-00001: unique constraint (MYDB4PM.SNO_PK) violated

COLUMN_NAME CONSTRAINT_KEY_NAME
=========== ===================
SNO SNO_PK
NAME NAME_UQ

DATA DICTIONARY (OR) READ ONLY TABLES:


=======================================
- when we install oracle s/w internally system is prepared
some pre-defined tables are called as "data dictionaries".
in these datadictionaries system will store the information
about tables,constraints,synonyms,views,indexes,.....etc.

- we cannot perform dml operations on datadictionaries but


we can read with help of "select" commands so that datadictionaries
are also called as "read only tables" in oracle.

52
- if we want to view all datadictionaries in oracle db then
we follow the following syntax is

syntax:
======
select * from dict;

NOTE:
=====
- To view column name along with constraint name of
a particular table in oracle db then we use a datadictionary
is called as "user_cons_columns".

EX:
SQL> DESC USER_CONS_COLUMNS;
SQL> SELECT COLUMN_NAME,CONSTRAINT_NAME
2 FROM USER_CONS_COLUMNS
3 WHERE TABLE_NAME='TEST9';

COLUMN_NAME CONSTRAINT_NAME
------------------ --------------------------------------------------------------------------------------------------------------
SNO SNO_PK
NAME NAME_UQ

HOW TO ADD CONSTRAINT TO AN EXISTING TABLE:


===========================================
SYNTAX:
=======
ALTER TABLE <TN> ADD CONSTRAINT <CONSTRAINT KEY NAME> <CONSTRAINT TYPE>(COLUMN NAME);

i) adding primary key:


======================
Ex:
SQL> CREATE TABLE PARENT(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10));
SQL> ALTER TABLE PARENT ADD CONSTRAINT EID_PK PRIMARY KEY(EID);

ii) adding unique,check constraints:


=====================================
SQL> ALTER TABLE PARENT ADD CONSTRAINT ENAME_UQ UNIQUE(ENAME);
SQL> ALTER TABLE PARENT ADD CONSTRAINT SAL_CHK CHECK(SAL>8000);

NOTE:
=====
if we want to view a check constraint conditional value
of a column in a particular table then we use a data dictionary
is called as "user_constraints".

Ex:
SQL> DESC USER_CONSTRAINTS;
SQL> SELECT SEARCH_CONDITION FROM USER_CONSTRAINTS
2 WHERE TABLE_NAME='PARENT';

53
SEARCH_CONDITION
------------------
SAL>8000

iii) adding not null constraint:


=================================
syntax:
======
alter table <tn> modify <column name> constraint <constraint key name> not null;

Ex:
SQL> ALTER TABLE PARENT MODIFY ENAME CONSTRAINT ENAME_NN NOT NULL;

iv) adding foreign key constraint:


===================================
syntax:
=======
alter table <tn> add <constraint> <constraint key name> foreign key(<common column of child table>)
references <parent table name>(<common column of parent table>) on delete cascade / on delete set null;

EX:
SQL> CREATE TABLE CHILD(DNAME VARCHAR2(10),EID INT);
Table created.

SQL> ALTER TABLE CHILD ADD CONSTRAINT EID_FK


2 FOREIGN KEY(EID) REFERENCES PARENT(EID)
3 ON DELETE CASCADE;

HOW TO DROP A CONSTRAINT FROM AN EXISTING TABLE:


================================================
SYNTAX:
=======
alter table <tn> drop <constraint> <constraint key name>;

i) dropping primary key:


========================
case-1: without relationship:
=============================
SQL> ALTER TABLE PARENT DROP CONSTRAINT EID_PK;

case-2: with realtionship:


===========================
SQL> ALTER TABLE PARENT DROP CONSTRAINT EID_PK CASCADE;

ii) dropping unique,check and not null:


=======================================
Ex:
SQL> ALTER TABLE PARENT DROP CONSTRAINT ENAME_UQ;
SQL> ALTER TABLE PARENT DROP CONSTRAINT SAL_CHK;
SQL> ALTER TABLE PARENT DROP CONSTRAINT ENAME_NN;

54
HOW TO RENAME CONSTRAINT NAME:
===============================
SYNTAX:
=======
alter table <tn> rename <constraint> <old constraint key name>
to <new constraint key name>;

EX:
SQL> CREATE TABLE TEST10(SNO INT PRIMARY KEY);

COLUMN_NAME CONSTRAINT_NAME
-------------------------- ------------------------------------------------------------------------------------------------------
SNO SYS_C007605

EX:
SQL> ALTER TABLE TEST10 RENAME CONSTRAINT
2 SYS_C007605 TO PK_SNO;

COLUMN_NAME CONSTRAINT_NAME
-------------------------- ------------------------------------------------------------------------------------------------------
SNO PK_SNO

HOW TO DISABLE / ENABLE CONSTRAINT ON EXISTING TABLE:


======================================================
- by default all constraints are enable mode(working).if we want to disable a constraint then we follow the
following syntax:
=======
alter table <tn> disable <constraint> <constraint key name>;

Ex:
SQL> CREATE TABLE TEST11 (ENAME VARCHAR2(10),SAL NUMBER(10) CHECK(SAL>=10000));

TESTING:
SQL> INSERT INTO TEST11 VALUES('SMITH',10000);--allowed
SQL> INSERT INTO TEST11 VALUES('ALLEN',12000);--allowed
SQL> INSERT INTO TEST11 VALUES('WARD',8000);--not allowed

- if we want to insert salary which is less than to 10000 into sal column then we need to disable check
constraint like below,

Ex:
alter table test11 disable constraint SYS_C007606;

TESTING:
SQL> INSERT INTO TEST11 VALUES('WARD',8000);--allowed

- if we want to enable a check constraint on existing column in a table then we must use a keyword is
called as "novalidate".

WHAT IS NOVALIDATE:

55
===================
- it is a default key which will not check existing values in a column but checking new values into a column.

EX:
SQL> ALTER TABLE TEST11 ENABLE NOVALIDATE CONSTRAINT SYS_C007606;

TESTING:
INSERT INTO TEST11 VALUES('SCOTT',5000)---not allowed
INSERT INTO TEST11 VALUES('SCOTT',50000)---allowed

DEFAULT CONSTRAINT:
===================
- it is a special type of constraint which is used to assign a user defined default value to a column.

Ex:
SQL> CREATE TABLE TEST12(SNO INT,LOC VARCHAR2(10) DEFAULT 'HYD');

TESTING:
INSERT INTO TEST12(SNO,LOC) VALUES(1,'MUMBAI');---allowed
INSERT INTO TEST12(SNO)VALUES(2);---allowed

SNO LOC
---------- ----------
1 MUMBAI
2 HYD

HOW TO ADD A DEFAULT VALUE TO AN EXISTING TABLE:


================================================
SYNTAX:
=======
ALTER TABLE <TN> MODIFY <COLUMN NAME> DEFAULT <VALUE>;

EX:
SQL> CREATE TABLE TEST13(ENAME VARCHAR2(10),SAL NUMBER(10));
SQL> ALTER TABLE TEST13 MODIFY SAL DEFAULT 5000;

TESTING:
SQL> INSERT INTO TEST13(ENAME)VALUES('A');

NOTE:
=====
- if we want to view a default value of a column of a particular table then we use a datadictionary is called
as "user_tab_columns".

EX:
SQL> DESC USER_TAB_COLUMNS;
SQL> SELECT COLUMN_NAME,DATA_DEFAULT FROM
2 USER_TAB_COLUMNS WHERE TABLE_NAME='TEST13';

COLUMN_NAME DATA_DEFAULT
---------------------- ----------------------------------------------------------

56
SAL 5000

HOW TO REMOVE A DEFAULT VALUE FROM AN EXISTING TABLE:


=====================================================
SYNTAX:
=======
ALTER TABLE <TN> MODIFY <COLUMN NAME> DEFAULT <VALUE>;

EX:
SQL> ALTER TABLE TEST13 MODIFY SAL DEFAULT NULL;

COLUMN_NAME DATA_DEFAULT
---------------------- ----------------------------------------------------------
SAL NULL

TRANSACTION CONTROL LANGUAGE(TCL):


==================================
- a transaction is nothing to perform some
operation over Db.
- there are two types of transactions are
> DDL transactions
> DML transactions
- in oracle ddl commands are auto commit operations.
- in oracle dml commands are not auto commit.so that
user has to commit dml operations over db by
explicitly.
- by using TCL commands,
i) commit
ii) rollback
iii) savepoint
i) commit:
===========
- to make a transaction is permanent.

a) implicit commit:
- these transactions are committed by system by default.
Ex:
DDL commands

b) explicit commit:
- these transaction are committed by user as per requirement.
Ex:
DML commands

syntax:
=======
commit;

Ex:
CREATE TABLE BRANCH(BCODE INT,BNAME VARCHAR2(10),BLOC VARCHAR2(10));

57
SQL> INSERT INTO BRANCH VALUES(1021,'SBI','HYD');
SQL> COMMIT;

SQL> UPDATE BRANCH SET BLOC='PUNE' WHERE BCODE=1021;


SQL> COMMIT;

SQL> DELETE FROM BRANCH WHERE BCODE=1021;


SQL> COMMIT;

NOTE: ONCE WE COMMIT A TRANSACTION THEN WE CANNOT ROLLBACK(CANCEL).

2) ROLLBACK:
============
- To cancel a transaction.

syntax:
=======
rollback;

Ex:
insert into branch values(1021,'sbi','hyd');
rollback;

3) SAVEPOINT:
=============
- when we created a save pointer internally system is allocating a special memory for a save pointer and
which will store a transaction which we want to rollback(cancel) in the feature.

syntax to create a savepoint:


=============================
savepoint <pointer name>;

syntax to rollback a savepoint:


===============================
rollback to <pointer name>;

ex:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1025;

SQL> SAVEPOINT P1;


SQL> DELETE FROM BRANCH WHERE BCODE=1023;

case-1:
========
rollback to p1;------> rollback 1023 only

case-2:
=======
rollback / commit

58
ALL TRANSACTIONS:
==================

ALL DB's ARE having "ACID" properties by default.

Atomicity:
==========
- atomic = single

ATM (a\c: 7000)


=========
withdraw : - insert atm card
- select lang
- click on banking
- select withdraw
- select curr / save
- enter 3000
- pinno
- yes / no

consistency:
============
- accurate information

x (a/c:10000)<------------> y(a/c:3000)
3000 --------------> 3000
====== =======
7000 6000
3000
=======
10000

isolation:
==========
- each transaction is independent

durability:
SUBQUERY:
=========
- A query inside another query is called as "Sub-query / Nested query".

syntax:
=======
select * from <tn> where <condition>(select * from ....(select * from ....));

- a sub-query statement is having two more queries those are,


i) Inner query / Child query / Sub-query
ii) Outer query / Parent query / Main-query

- as per the execution process of subquery statement it again classified into two types,
1. Non-corelated subquery

59
2. Co-related subquery

1. Non-corelated subquery:
===========================
- first inner query later outer query.

2. Co-related subquery:
=======================
- first outer query later inner query.

1. Non-corelated subquery
=========================
> single row subquery
> multiple row subquery
> multiple column subquery
> inline view

single row subquery:


====================
- when a subquery returns a single value.
- we can use the following operators are "=,<,>,<=,>=,!="

Ex:
waq to display employee details who are earning the first highest salary from emp table?
=======================================
|| subquery statement = outer query + inner query ||
=======================================
step1:inner query:
==================
select max(sal) from emp;------> 5000

step2: outer query:


===================
select * from emp where sal=(inner query);

step3: subquery=(outer+inner)
=============================
select * from emp where sal=(select max(sal) from emp);

EX:
waq to display the senior most details from emp table?
select * from emp where hiredate=(select min(hiredate) from emp);

Ex:
waq to display employees details whose salary is more than the maximum salary of the job is salesman?
select * from emp where sal >(select max(sal) from emp where job='SALESMAN')

Ex:
waq to find out second highest salary from emp table?
SQL> SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP);

60
Ex:
waq to display employee details who are getting 2nd highest salary?
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP));

Ex:
waq to display employee details who are getting 3rd highest salary?
SELECT * FROM EMP WHERE SAL=
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP)));

Nth N+1
==== ====
1ST 2Q,2ND 3Q,3RD 4Q,30TH 31Q &150TH 151Q

HOW TO OVERCOME THE ABOVE PROBLEM?


==================================
II) MULTIPLE ROW SUBQUERY:
===========================
- when a subquery return more than one value.
- we can use the following operators are "IN,ANY,ALL".

Ex:
waq to display employees whose employees job is same as the employee "smith" or "martin" jobs?
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE ENAME='SMITH'
OR ENAME='MARTIN');
(OR)
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE
ENAME IN('SMITH','MARTIN'));

Ex:
waq to display employees who are earning highest and lowest salary from emp table?
SQL> SELECT * FROM EMP WHERE SAL IN
(SELECT MAX(SAL) FROM EMP UNION SELECT MIN(SAL) FROM EMP);

Ex:
waq to display employees who are getting maximum salary from each job?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP GROUP BY JOB);

ANY,ALL OPERATORS:
==================
ANY:
====
- it returns true if any one value is satisfied from the given list of values.

EX:
X(25) >ANY(10,20,30)

IF X=45 ---- TRUE ,X=09 ---- FALSE, X=25 ---- TRUE

61
ALL:
====
- it returns true if all values are satisfied from the given list of values.

EX:
X(25) >ALL(10,20,30)

IF X=45 ---- TRUE,X=09 ---- FALSE,X=25 ---- false

Ex:
waq to display employees whose salary is more than any 'salesman' salary?
SQL> SELECT * FROM EMP WHERE SAL >ANY(SELECT SAL FROM EMP WHERE JOB='SALESMAN');

Ex:
waq to display employees whose salary is more than all 'salesman' salaries?
SQL> SELECT * FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP WHERE JOB='SALESMAN');

MULTIPLE COLUMN SUBQUERY:


=========================
- comparing multiple columns values of inner query with multiple columns values of outer query is called as
MCSQ.

syntax:
=======
select * from <tn> where(<col1>,,col2>,....) in(select <col1>,<col2>,....);

Ex:
waq to display employees whose employee job,mgr are same as the job,mgr of the employee "scott"?
SQL> SELECT * FROM EMP WHERE(JOB,MGR) IN (SELECT JOB,MGR FROM EMP
WHERE ENAME='SCOTT');

PSEUDO COLUMNS:
===============
I) ROWID
II) ROWNUM
- these columns are working just like a table columns.

I) ROWID:
=========
- whenever we insert a new row into a table internally oracle server is creating a unique row
identification / row address to each row wise in a table.
- these rowid's are permanent id's ,stored in database memory.

EX:
SQL> SELECT ENAME,ROWID FROM EMP;
SQL> SELECT ENAME,DEPTNO,ROWID FROM EMP WHERE DEPTNO=10;

HOW TO DELETE MULTIPLE DUPLICATE ROWS EXCEPT ON DUPLICATE ROW FROM A TABLE:
===========================================================================
EX_TABLE:
=========

62
SQL> SELECT * FROM TEST;

SNO NAME
---------- ----------
1A
1A
1A
2B
3C
3C
4D
4D
4D
5E
5E

SOL:
SQL> DELETE FROM TEST WHERE ROWID NOT IN(SELECT MAX(ROWID) FROM TEST
GROUP BY SNO);

II) ROWNUM:
===========
- is used to generate row numbers to each row wise / to each group of rows wise automatically.
- these are temporary numbers , not saved in database memory.
- to perform " top N / Nth operations" over database table.

Ex:
SQL> SELECT ROWNUM,ENAME FROM EMP;
SQL> SELECT ROWNUM,ENAME,DEPTNO FROM EMP WHERE DEPTNO=10;

Ex:
waq to fetch the 1st row from emp table by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM=1;

Ex:
waq to fetch the 2ND ROW from emp table by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM=2;
no rows selected

NOTE:
=====
- generally rownum is always starts with 1 for every selected row in a table. so to overcome this problem
we use the following operators are "<,<=".

SOLUTION:
SQL> SELECT * FROM EMP WHERE ROWNUM<=2
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM=1;

Ex:
waq tp display top 5 rows from emp by using rownum?

63
SQL> SELECT * FROM EMP WHERE ROWNUM<=5;

Ex:
waq to display 5th row from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=5
2 minus
3 SELECT * FROM EMP WHERE ROWNUM<=4;

EX:
waq to fetch from 3rd row to 10th row from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=10
2 minus
3 SELECT * FROM EMP WHERE ROWNUM<3;

EX:
waq to fetch the last two rows from emp by using rownum?
SQL> SELECT * FROM EMP WHERE ROWNUM<=14
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM<=12;
(OR)
SQL> SELECT * FROM EMP
2 MINUS
3 SELECT * FROM EMP WHERE ROWNUM<=(SELECT COUNT(*)-2 FROM EMP);

INLINE VIEW:
============
- it is special type of subquery.
- providing a select query inplace of table name in select statement is called as "inline view".
- in inline view mechanism the result of inner query will act as a table for outer query.

syntax:
========
SELECT * FROM <SELECT QUERY>;

purpose of inline view:


=======================
1. Generally subquery is not allowed "order by" clause.so to
overcome this use "inline view".

2. Generally column alias names are not allowed in where clause


condition.so to overcome this we use "inline view".

Ex:
waq to display empno,ename,sal and annual salary of employees whose annual salary is more than 30000?

SQL> SELECT EMPNO,ENAME,SAL,SAL*12 ANNSAL FROM EMP WHERE


ANNSAL>30000;
ERROR at line 1:
ORA-00904: "ANNSAL": invalid identifier

SOLUTION:

64
SQL> SELECT * FROM (SELECT EMPNO,ENAME,SAL,SAL*12 ANNSAL FROM EMP)
WHERE ANNSAL>30000;

EX:
waq to fetch the first five highest salaries employees from emp table by using rownum along with inline
view?
SQL> SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
2 WHERE ROWNUM<=5;

EX:
waq to fetch the fifth highest salaries employee from emp table by using rownum along with inline view?
SQL> SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
2 WHERE ROWNUM<=5
3 minus
4 SELECT * FROM(SELECT * FROM EMP ORDER BY SAL DESC)
5 WHERE ROWNUM<=4;

How to use rownum alias along with inline view:


================================================
Ex:
waq to fetch 9th row from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,ENAME FROM EMP) WHERE R=9;
(OR)
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP) WHERE R=9;

Ex:
waq to fetch 1st,3rd,5th,10th position rows from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP) WHERE R IN(1,3,5,10);

EX:
waq to fetch the even position rows from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP) WHERE MOD(R,2)=0;

EX:
waq to fetch the first row and the last row from emp by using rownum alias along with inline view?
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP)
2 WHERE R=1 OR R=14;
(OR)
SQL> SELECT * FROM(SELECT ROWNUM R,EMP.* FROM EMP)
2 WHERE R=1 OR R=(SELECT COUNT(*) FROM EMP);

ANALYTICAL FUNCTIONS:
=====================
I) ROW_NUMBER()
II) RANK()
III) DENSE_RANK()

I) ROW_NUMBER():
=================
- is used to generate row numbers to each row wise / to each group of rows wise in a table automatically.
- is not comparing data in a table.

65
II) RANK():
===========
- is used to assign rank numbers to each row wise / to each group of wise in a table automatically.
- is used to comparing data in a table.
- it will skip the next rank number in order when we have
duplicates.

III) DENSE_RANK():
==================
- is used to assign rank numbers to each row wise / to each group of wise in a table automatically.
- is used to comparing data in a table.
- it will not skip the next rank number in order
when we have duplicates.

syntax:
=======
analytical function name()over([partition by <column name>]
order by <column name> <asc/desc>)

Here,
partition by clause is optional order by clause is mandatory

EX:

ENAME SALARY ROW_NUMBER() RANK() DENSE_RANK()


A 85000 1 1 1
B 72000 2 2 2
C 72000 3 2 2
D 68000 4 4 3
E 58000 5 5 4
F 46000 6 6 5

EX.on without partition by clause:


==================================
EX:
SQL> SELECT ENAME,SAL,ROW_NUMBER()OVER(ORDER BY SAL DESC) ROW_NUMBER FROM EMP;
SQL> SELECT ENAME,SAL,RANK()OVER(ORDER BY SAL DESC) RANKS FROM EMP;
SQL> SELECT ENAME,SAL,DENSE_RANK()OVER(ORDER BY SAL DESC) RANKS FROM EMP;

EX.on with partition by clause:


===============================
SQL> SELECT ENAME,DEPTNO,SAL,ROW_NUMBER()OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)
ROW_NUMBER FROM EMP;

SQL> SELECT ENAME,DEPTNO,SAL,RANK()OVER (PARTITION BY DEPTNO ORDER BY SAL DESC) RANKS


FROM EMP;

SQL> SELECT ENAME,DEPTNO,SAL,DENSE_RANK()OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)


RANKS FROM EMP;

66
EX:
waq to display employees who are earning 3rd highest salary from each deptno wise by using dense_rank()
along with inline view?
SQL> SELECT * FROM(SELECT EMPNO,ENAME,DEPTNO,SAL,DENSE_RANK() OVER(PARTITION BY DEPTNO
ORDER BY SAL DESC) RANKS FROM EMP) WHERE RANKS=3;

EX:
waq to display 4th senior most employee from each job wise by using dense_rank() along with inline view?
SQL> SELECT * FROM(SELECT EMPNO,ENAME,JOB,HIREDATE,DENSE_RANK()OVER(PARTITION BY JOB
ORDER BY HIREDATE) RANKS FROM EMP) WHERE RANKS=4;

2) CO-RELATED SUBQUERY:
=======================
- first outer query is executed and later inner query.

syntax to find out "Nth" high / low salary from a table:


========================================================
SELECT * FROM <TN> <TABLE ALIAS NAME1> WHERE N-1=(SELECT COUNT(DISTINCT <COLUMN NAME>)
FROM <TN> <TABLE ALIAS NAME2> WHERE <TABLE ALIAS NAME2>.<COLUMN NAME>< / > <TABLE ALAIS
NAME1>.<COLUMN NAME>);

Here,
< ---- for lowest salary
> ---- for highest salary

SQL> SELECT * FROM TEST;

ENAME SAL
---------- ----------
SMITH 45000
ADAMS 37000
JONES 85000
MILLER 12000
WARD 28000
SCOTT 85000

EX:
waq to find out 1st highest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 0=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL > T1.SAL);

ENAME SAL
---------- ----------
SCOTT 85000
JONES 85000

EX:
waq to find out 5th highest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 4=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL > T1.SAL);

67
EX:
waq to find out 1st lowest salary employee details by using co-related subquery?
SQL> SELECT * FROM TEST T1 WHERE 0=(SELECT COUNT(DISTINCT SAL)
FROM TEST T2 WHERE T2.SAL < T1.SAL);

DB SECURITY:
============
- all databases are supporting the following two types of
security mechanisms those are,
1. Authentication
2. Authorization

1. Authentication:
===================
- to check user credential(username & password) before
connect / login into oracle db server.
- these user credential are created by DBA.

How to create a new user in oracle:


===================================
create user <username> identified by <password>;

Ex:
create user U1 identified by U1;

2. Authorization:
=================
- to give permissions to user to perform some operations
over database.
- these permissions are also giving by DBA by using
"DCL" commands.
i) grant:
=========
- to give permission to user.
syntax:
=======

68
grant <privilege name> to <username>;

ii) revoke:
===========
- to cancel permission from user.
syntax:
=======
revoke <privilege name> from <username>;

PRIVILEGES:
===========
- is nothing but right giving by DBA only.
i) system privileges
ii) object privileges

i) system privileges:
======================
- these privileges are giving by DBA only.
- system privilege are "connect,create table,unlimited tablespace,
create view,create synonym,create sequence,create materialized view,
create procedure,create index,create cluster,........etc.

syntax:
=======
grant <system privilege name> to <username>;

Ex:
CONN: system/tiger
sql> create user u1 identified by u1;

conn: u1/u1
error

conn: system/tiger
sql> grant connect to u1;

conn: u1/u1
connected
create table test1(sno int,name varchar2(10));
error

conn: system/tiger
sql> grant create table to u1;
sql> insert into test1 values(1,'smith');
error

conn: system / tiger


sql> grant unlimited tablespace to u1;

conn: u1/u1
sql> insert into test1 values(1,'smith');

69
1 row created.

sql> update test1 set sno=101 where sno=1;


sql> delete from test1;

How to remove connectivity permission from U1 user:


===================================================
conn : system/tiger
sql> revoke connect from u1;

conn : u1/u1
error

2. OBJECT PRIVILEGES:
=====================
- these permissions are giving by DBA and DB developer(user).
- these permissions are nothing "select,insert,update,
delete" (or) "all" keyword.

syntax:
========
grant <object privilege name> on <object name/table name> to <username>;

Case-1: DBA-to-User:
====================
conn : system/tiger
sql> create user u2 identified by u2;
sql> grant connect to u2;

conn : u2/u2
sql> select * from dept;
(or)
sql> select * from system.dept;
error

sql> insert into system.dept values(50,'dba','hyd');


error
sql> update system.dept set loc='pune' where deptno=30;
error
sql> delete from system.dept where deptno=10;
error

Note:
=====
- the user "u2" is not having object privileges(permissions)
to perform "select,insert,update,delete" operations on
dept table.so that system admin want to give permissions to
user u2 like below,

conn : system/tiger
sql> grant select,insert,update,delete on dept to u2;

70
(or)
sql> grant all on dept to u2;

conn : u2/u2
sql> select * from system.dept;---allowed
sql> insert into system.dept values(50,'dba','hyd');---allowed
sql> update system.dept set loc='pune' where deptno=30;---allowed
sql> delete from system.dept where deptno=10;----allowed

How to cancel all object privileges of a user:


==============================================
conn : system/tiger
sql> revoke all on dept from u2;

Case-2: DB developer(User)-to-User:
===================================
- when a user u1 want to give object privileges to another
user u2 then u1 should take permission from DBA with "with
grant option" statement then only user u1 can give object
privileges to another user u2.

EX:
conn: system/tiger
sql> create user u11 identified by u11;
sql> create user u12 identified by u12;

sql> grant connect to u11;


sql? grant connect to u12;

conn : u11/u11
sql> select * from system.dept;
error

conn : u12/u12
sql> select * from system.dept;
error

conn : system/tiger
sql> grant select on dept to u11;(granting without "with grant option")

conn : u11/u11
sql> select * from system.dept;---allowed

sql> grant select on system.dept to u12;


error

conn : system / tiger


sql> revoke select on dept from u11;
sql> grant select on dept to u11 with grant option;

conn : u11/u11

71
sql> select * from system.dept;
sql> grant select on system.dept to u12;---->allowed

conn : u12 / u12


sql> select * from system.dept;---allowed

ROLE:
=====
- a role is nothing but giving group of privileges
to a group of users who are working on same project in real
time.
- created by DBA only.

EX: X-project
|
mod1 | mod2 | mod3
|||
3emp 5emp 2emp
|||
role1
|
create table privilege

step1: create a role


=====================
syntax:
=======
create role <role name>;

step2: assigning privileges to a role:


======================================
syntax:
=======
grant <privilege name> to <role name>;

step3: assigning a role to users:


=================================
syntax:
=======
grant <role name> to <users>;

EX:
conn : system/tiger
SQL> CREATE USER U1 IDENTIFIED BY U1;
SQL> CREATE USER U2 IDENTIFIED BY U2;
SQL> CREATE USER U3 IDENTIFIED BY U3;

SQL> GRANT CONNECT TO U1;


SQL> GRANT CONNECT TO U2;
SQL> GRANT CONNECT TO U3;

72
CONN : U1/U1
SQL> CREATE TABLE TEST1(SNO INT);
ERROR

CONN : U2/U2
SQL> CREATE TABLE TEST1(SNO INT);
ERROR

CONN : U3/U3
SQL> CREATE TABLE TEST1(SNO INT);
ERROR

CONN : system/tiger
SQL> CREATE ROLE R1;
SQL> GRANT CREATE TABLE TO R1;
SQL> GRANT R1 TO U1,U2,U3;

CONN : U1/U1
SQL> CREATE TABLE TEST1(SNO INT);----allowed

CONN : U2/U2
SQL> CREATE TABLE TEST1(SNO INT);----allowed

CONN : U3/U3
SQL> CREATE TABLE TEST1(SNO INT);---allowed

SQL:
> DDL
> DML
> DRL/DQL ------> any developers(user)
> TCL

> DCL -------> dba only


SYNONYMS:
=========
- it is a db object which is used to create
a permanent alias name for table / object name.

purpose:
========
1. to reduce the lengthy table name.
2. to hide username and table name.

types of synonyms:
==================
1. private synonym
2. public synonym

1. private synonym:

73
====================
- these are default synonyms.
- these are created by users who are having permission.

syntax:
=======
create synonym <synonym name> for [username].<table name>;

ex:
conn : system/tiger
sql> create user u1 identified by u1;
sql> grant connect,create table,unlimited tablespace
to u1;

conn : u1/u1
sql> create table college_enrollment_details
(stid int,sname varchar2(10));

sql> insert into college_enrollment_details


values(1,'a');

sql> update college_enrollment_details set


sname='smith' where stid=1;

sql> delete from college_enrollment_details where stid=1;

sql> create synonym s1 for college_enrollment_details;


ERROR at line 1:
ORA-01031: insufficient privileges

conn : system/tiger
sql> grant create synonym to u1;

conn : u1/u1
sql> create synonym s1 for college_enrollment_details;

sql> insert into s1 values(1,'a');


sql> update s1 set sname='smith' where stid=1;
sql> delete from s1 where stid=1;

Note:
=====
- if we want to view private synonyms in oracle
then we use a datadictionary is called as
"user_synonyms".

Ex:
SQL> DESC USER_SYNONYMS;
SQL> SELECT TABLE_OWNER,SYNONYM_NAME,TABLE_NAME
2 FROM USER_SYNONYMS;

74
TABLE_OWNER SYNONYM_NAME TABLE_NAME
------------ ----------------- ---------------------------------------------------
U1 S1 COLLEGE_ENROLLMENT_DETAILS

How to drop a private synonym:


==============================
syntax:
=======
drop synonym <synonym name>;

Ex:
drop synonym s1;

ii) public synonyms:


===================
- these are creted by DBA only.
- to hide username and table name.

syntax:
=======
create public synonym <synonym name> for [username].<table name>;

EX:
conn : system/tiger
sql> create user u2 identified by u2;
sql> create user u3 identified by u3;
sql> grant connect to u2,u3;

sql> create public synonym ps11 for system.dept;


sql> grant select on ps11 to u2,u3;

conn : u2/u2
sql> select * from ps11;

conn : u3/u3
sql> select * from ps11;

Note:
=====
- if we want to view public synonyms in oracle
the we use a datadictionary is "all_synonyms".

Ex:
sql> DESC ALL_SYNONYMS;
SQL> SELECT TABLE_OWNER,SYNONYM_NAME,TABLE_NAME
2 FROM ALL_SYNONYMS WHERE TABLE_NAME='DEPT';

TABLE_OWNER SYNONYM_NAME TABLE_NAME


------------- -------------- -----------------------------------------------------
SYSTEM PS1 DEPT

75
HOW TO DROP A PUBLIC SYNONYM:
=============================
SYNTAX:
=======
DROP PUBLIC SYNONYM <SYNONYM NAME>;
EX:
DROP PUBLIC SYNONYM PS11;
Ex:
COLLEGE_ENROLLMENT_DETAILS

SELECT * FROM S1;


INSERT INTO S1 VALUES(...);
UPDATE S1 SET ......;
DELETE FROM S1 ......;

CREATE SYNONYM S1 FOR COLLEGE_ENROLLMENT_DETAILS;

Ex:
SELECT * FROM S2;

CREATE SYNONYM S2 FOR SYSTEM.DEPT;


VIEWS:
======
- it is a db object.
- it is a subset of a base table(main table).
- it is virtual / logical table of base table because view doesnot store data.
- it is creating with help of "select query" to retrieving the required data/information from a base table.
- whenever we perform dml operations on view internally those operations are executed on base table
and reflected to view.
- view will act as an interface between user and database tables.

purpose:
========
1. security
> column level
> row level
2. can stored query.
3. to convert complex query into simple query.
4. to check data integrity rules while inserting/ accessing data from a base table.

TYPES OF VIEWS:
===============
1. simple views
2. complex views

1. simple views:
================
- when we created a view to access the required data / information from a single base table is called as
"smiple view".
- by default simple views are supporting dml operations.

76
syntax:
=======
create view <view name> as <select query>;

Ex:
create a view to access data from dept table?
SQL> CREATE VIEW V1 AS SELECT * FROM DEPT;

TESTING:
SQL> INSERT INTO V1 VALUES(50,'DBA','HYD');
SQL> UPDATE V1 SET LOC='PUNE' WHERE DEPTNO=50;
SQL> DELETE FROM V1 WHERE DEPTNO=50;

Ex:
create a view to access empno,ename,sal from emp
table?
SQL> CREATE VIEW V2 AS SELECT EMPNO,ENAME,SAL FROM EMP;

TESTING:
SQL> INSERT INTO V2 VALUES(1122,'YUVIN',4000);

Ex:
create a view to access employees details who are working under deptno
is 20?
SQL> CREATE VIEW V3 AS SELECT * FROM EMP WHERE DEPTNO=20;

VIEW OPTIONS:
=============
i) with check option:
=====================
- it is a constraint which is used to check values with user defined condition was given in the select query at
the time of view creation.
- by using "with check option" statement we can restricted rows on base table through a view.

EX:
create view to display and accept employees details whose
salary is 3000?
SQL> CREATE VIEW V4 AS SELECT EMPNO,ENAME,SAL FROM EMP WHERE SAL=3000;

Testing:
SQL> INSERT INTO V4 VALUES(1122,'YUVIN',1500);---allowed
SQL> INSERT INTO V4 VALUES(1123,'BHUVIN',4500);---allowed
SQL> INSERT INTO V4 VALUES(1124,'SUMAN',3000);---allowed

- if we want to restrict employee details on base table


whose salary is not equal to 3000 then we use "with check option".

Ex:
SQL> CREATE VIEW V5 AS SELECT EMPNO,ENAME,SAL FROM EMP
2 WHERE SAL=3000 WITH CHECK OPTION;

77
TESTING:
SQL> INSERT INTO V5 VALUES(1125,'WARNER',1200);---not allowed
SQL> INSERT INTO V5 VALUES(1125,'WARNER',5000);---not allowed
SQL> INSERT INTO V5 VALUES(1125,'WARNER',3000);---- allowed

ii) with read only:


===================
- by default simple views are supporting DML operations.if user
want to restricted DML operations on base table through a view then
we use "with read only" statement.

EX:
SQL> CREATE VIEW V6 AS SELECT * FROM DEPT WITH READ ONLY;

TESTING:
INSERT INTO V6 VALUES(50,'SAP','PUNE')
ERROR at line 1:
ORA-42399: cannot perform a DML operation on a read-only view

2) COMPLEX VIEWS:
=================
- when we created a view based on,
> multiple tables
> group by
> having
> distinct
> aggregative / grouping functions
> set operators
> joins
> subquery
- by default complex view is not allowed DML operations.
EX:
SQL> CREATE VIEW V8 AS
2 SELECT DEPTNO,SUM(SAL) SUM_OF_SALARY FROM EMP GROUP BY DEPTNO;

TESTING:
INSERT INTO V8 VALUES(40,4500)
ERROR at line 1:
ORA-01733: virtual column not allowed here

FORCE VIEW:
===========
- when we created a view without base table is called as "force view".

syntax:
=======
create force view <view name> as <select query>;

Ex:
SQL> CREATE FORCE VIEW FV1 AS SELECT * FROM TEST88;
Warning: View created with compilation errors.

78
NOTE:
=====
- here view is created but not working if we want to active a
force view then we should create a base table on the name of
test88.

ex:
SQL> CREATE TABLE TEST88(SNO INT);
SQL> INSERT INTO TEST88 VALUES(1021);

SQL> SELECT * FROM TEST88;

SNO
----------
1021

SQL> SELECT * FROM FV1;

SNO
----------
1021

MATERIALIZED VIEW:
==================
- it is also created based on a base table just like a view
but view doesnot store data whereas mview can store data.

VIEWS MVIEWS
====== =======
1. not storing data. 1. store data.

2. we cannot access view 2. it can access mview.


once we drop a base table.

3. dependent object 3. independent object

4. we can perform dml operations 4. we cannot perform dml


on view on mview.

syntax:
=======
create materialized view <view name> as <select query>;

EX:
create table test66(sno int,name varchar2(10));
create view v66 as select * from test66;
create materialized view mv66 as select * from test66;

insert into test66 values(1,'smith');


select * from test66;

79
select * from v66;
select * from mv66;

- when we called mview then it doesnot display any data by default.


so that if we want to see data in mview then we should follow the
following refreshing methods on mviews.those are,

REFRESHING METHODS:
===================
I) ON DEMAND:
============
- it is a default refresh method to refreshing a mview in database.

syntax:
=======
execute dbms_mview.refresh('mview name');

Ex:
execute dbms_mview.refresh('mv66');
select * from mv66;

II) ON COMMIT:
===============
SYNTAX:
=======
CREATE MATERIALIZED VIEW <VIEW NAME>
REFRESH ON COMMIT
AS <SELECT QUERY>;

EX:
SQL> CREATE TABLE TEST77(EID INT,ENAME VARCHAR2(10));
Table created.

SQL> CREATE VIEW V77 AS SELECT * FROM TEST77;


View created.

SQL> CREATE MATERIALIZED VIEW MV77


2 REFRESH ON COMMIT
3 AS
4 SELECT * FROM TEST77;
ERROR at line 4:
ORA-12054: cannot set the ON COMMIT refresh attribute for the materialized view

- to overcome the above error then we apply primary key constraint


on test77 table like below,

SQL> ALTER TABLE TEST77 ADD CONSTRAINT EID_PK PRIMARY KEY(EID);

SQL> CREATE MATERIALIZED VIEW MV77


2 REFRESH ON COMMIT
3 AS

80
4 SELECT * FROM TEST77;

Materialized view created.

TESTING:
INSERT INTO TEST77 VALUES(1,'MILLER');
COMMIT;

SELECT * FROM TEST77;


SELECT * FROM V77;
SELECT * FROM MV77;

NOTE:
======
- to view all materialized views in oracle then we use a datadictionary
is called as "user_mviews".

EX:
SQL> DESC USER_MVIEWS;
SQL> SELECT MVIEW_NAME FROM USER_MVIEWS;

MVIEW_NAME
------------
MV77
MV66

SYNTAX TO DROP A MVIEW:


=======================
DROP MATERIALIZED VIEW <VIEW NAME>;

EX:
DROP MATERIALIZED VIEW MV66;

SEQUENCE:
=========
- it is db object which is used to generate the sequence numbers
on a particular column automatically.
- it will provide "auto incremental value" facility.

syntax:
======
create sequence <sequence name>
[start with n]
[minvalue n]
[increment by n]
[maxvalue n]
[no cycle / cycle]
[no cache / cache n];

start with n:
=============

81
- it specify starting value of a sequence.
here "n" is number.

minvalue n:
===========
- it shows minimum value in the sequence. here "n" is number.

increment by n:
===============
- it specify the incremental value in between sequence numbers.here "n" is number.

maxvalue n:
===========
- it shows the maximum value in the sequence.here "n" is number.

no cycle:
=========
- it is a default attribute.when we create a sequence object with "no cycle" then the set of sequence
numbers are not repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3;

output:
=======
1
2
3----seq.stop

cycle:
=======
- when we create a sequence object with "cycle" then the set of
sequence numbers are repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3
cycle;
output:
=======
1
2
3
1
2
3
1
2

82
3..............

NO CACHE:
=========
- it is a defult attribute.when we created a sequence
with "no cache" then the set sequence numbers are saved into
database memory.
- so that whenever user want to access the required data
based on sequence number then that user request will to database
each and every time so that the no.of user requests are incresing
the burdon on database and degrade the performance of database.

CAHCE n:
========
- when we created a sequence object with "cache" then
the set sequence numbers are saved in database and also a
copy of sequence numbers are kept into cache memory so that
whenever a user want to access data based on sequence number
then the user request will to cache memory instead of database
memory.so that the no.of user request's will reduce and improve
the performance of database.a cache file size starts with minimum
2kb.

NOTE:
=====
- when we work on sequence object to generate sequence numbers
then we use the following two pseudo columns are
i) nextval: generating next by next value.
ii) currval : can see the current value in the sequence

1
2
3 nextval = 6,currval=5
4
5

EX1:
SQL> CREATE SEQUENCE SQ1
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3;

TESTING:
========
SQL> CREATE TABLE TEST22(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST22 VALUES(SQ1.NEXTVAL,'&NAME');
Enter value for name: A
/
Enter value for name: B
/

83
Enter value for name: C
/
Enter value for name: D
ERROR at line 1:
ORA-08004: sequence SQ1.NEXTVAL exceeds MAXVALUE and
cannot be instantiated

SQL> SELECT * FROM TEST22;

SNO NAME
---------- ----------
1A
2B
3C

ALTERING A SEQUENCE:
====================
SYNTAX:
=======
ALTER SEQUENCE <SEQUENCE NAME> <ATTRIBUTE NAME> n;

EX:
SQL> ALTER SEQUENCE SQ1 MAXVALUE 5;
Sequence altered.

Enter value for name: D


/
Enter value for name: E

SQL> SELECT * FROM TEST22;

SNO NAME
---------- ----------
1A
2B
3C
4D
5E

EX2:
SQL> CREATE SEQUENCE SQ2
2 START WITH 1
3 MINVALUE 1
4 INCREMENT BY 1
5 MAXVALUE 3
6 CYCLE
7 CACHE 2;

Sequence created.

TESTING:

84
SQL> CREATE TABLE TEST23(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST23 VALUES(SQ2.NEXTVAL,'&NAME');
Enter value for name: X
/
.......................
/
........................

EX3:
SQL> CREATE SEQUENCE SQ3
START WITH 3
MINVALUE 1
INCREMENT BY 1
MAXVALUE 5
CYCLE
CACHE 2;

TESTING:
SQL> CREATE TABLE TEST24(SNO INT,NAME VARCHAR2(10));

SQL> INSERT INTO TEST24 VALUES(SQ3.NEXTVAL,'&NAME');


Enter value for name: A
/
.......................
/
........................

NOTE:
=====
- if we want to view all sequence objects in oracle then
use a datadictionary is "user_sequences".

EX:
SQL> DESC USER_SEQUENCES;
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;

HOW TO DROP A SEQUENCE OBJECT:


==============================
SYNTAX:
=======
DROP SEQUENCE <SEQUENCE NAME>;

EX:
DROP SEQUENCE SQ1;
==============================================================

SEQUENCE:
=========
- it is db object which is used to generate the sequence numbers
on a particular column automatically.

85
- it will provide "auto incremental value" facility.

syntax:
======
create sequence <sequence name>
[start with n]
[minvalue n]
[increment by n]
[maxvalue n]
[no cycle / cycle]
[no cache / cache n];

start with n:
=============
- it specify starting value of a sequence.
here "n" is number.

minvalue n:
===========
- it shows minimum value in the sequence.
here "n" is number.

increment by n:
===============
- it specify the incremental value in between sequence numbers.
here "n" is number.

maxvalue n:
===========
- it shows the maximum value in the sequence.
here "n" is number.

no cycle:
=========
- it is a default attribute.when we create a sequence object
with "no cycle" then the set of sequence numbers are not repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3;

output:
=======
1
2
3----seq.stop

cycle:
=======
- when we create a sequence object with "cycle" then the set of

86
sequence numbers are repeated.
EX:
start with 1
minvalue 1
increment by 1
maxvalue 3
cycle;
output:
=======
1
2
3
1
2
3
1
2
3..............

NO CACHE:
=========
- it is a defult attribute.when we created a sequence with "no cache" then the set sequence numbers are
saved into database memory.
- so that whenever user want to access the required data based on sequence number then that user
request will to database each and every time so that the no.of user requests are increasing the burdon on
database and degrade the performance of database.

CAHCE n:
========
- when we created a sequence object with "cache" then the set sequence numbers are saved in database
and also a copy of sequence numbers are kept into cache memory so that whenever a user want to access
data based on sequence number then the user request will to cache memory instead of database memory.
so that the no.of user request's will reduce and improve the performance of database.a cache file size
starts with minimum 2kb.

NOTE:
=====
- when we work on sequence object to generate sequence numbers then we use the following two pseudo
columns are
i) nextval: generating next by next value.
ii) currval : can see the current value in the sequence

1
2
3 nextval = 6,currval=5
4
5

EX1:
CREATE SEQUENCE SQ1 START WITH 1 MINVALUE 1 INCREMENT BY 1 MAXVALUE 3;

87
TESTING:
========
SQL> CREATE TABLE TEST22(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST22 VALUES(SQ1.NEXTVAL,'&NAME');
Enter value for name: A
/
Enter value for name: B
/
Enter value for name: C
/
Enter value for name: D
ERROR at line 1:
ORA-08004: sequence SQ1.NEXTVAL exceeds MAXVALUE and
cannot be instantiated

SQL> SELECT * FROM TEST22;

SNO NAME
---------- ----------
1A
2B
3C

ALTERING A SEQUENCE:
====================
SYNTAX:
=======
ALTER SEQUENCE <SEQUENCE NAME> <ATTRIBUTE NAME> n;

EX:
SQL> ALTER SEQUENCE SQ1 MAXVALUE 5;
Sequence altered.

Enter value for name: D


/
Enter value for name: E

SQL> SELECT * FROM TEST22;

SNO NAME
---------- ----------
1A
2B
3C
4D
5E

EX2:
SQL> CREATE SEQUENCE SQ2 START WITH 1 MINVALUE 1 INCREMENT BY 1 MAXVALUE 3 CYCLE CACHE 2;
Sequence created.

88
TESTING:
SQL> CREATE TABLE TEST23(SNO INT,NAME VARCHAR2(10));
SQL> INSERT INTO TEST23 VALUES(SQ2.NEXTVAL,'&NAME');
Enter value for name: X
/
.......................
/
........................

EX3:
SQL> CREATE SEQUENCE SQ3
START WITH 3
MINVALUE 1
INCREMENT BY 1
MAXVALUE 5
CYCLE
CACHE 2;

TESTING:
SQL> CREATE TABLE TEST24(SNO INT,NAME VARCHAR2(10));

SQL> INSERT INTO TEST24 VALUES(SQ3.NEXTVAL,'&NAME');


Enter value for name: A
/
.......................
/
........................

NOTE:
=====
- if we want to view all sequence objects in oracle then
use a datadictionary is "user_sequences".

EX:
SQL> DESC USER_SEQUENCES;
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;

HOW TO DROP A SEQUENCE OBJECT:


==============================
SYNTAX:
=======
DROP SEQUENCE <SEQUENCE NAME>;

EX:
DROP SEQUENCE SQ1;
==============================================================
PARTITION TABLE:
================
1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION

89
1. RANGE PARTITION
===================
- created partition table based on the given range value.

syntax:
=======
create table <tn>(<col1> <dt>[size],.....................)
partition by range(<key column name>)
(partition <partition name1> values less than(value),
partition <partition name2> values less than(value),
....................................................
....................................................);

Ex:
CREATE TABLE TEST1(EID INT,ENAME VARCHAR2(10),SAL NUMBER(10)) PARTITION BY RANGE(SAL)
(PARTITION P1 VALUES LESS THAN(500),PARTITION P2 VALUES LESS THAN(1000),PARTITION P3 VALUES
LESS THAN(2000));

INSERT INTO TEST1 VALUES(1,'SMITH',1500);


INSERT INTO TEST1 VALUES(2,'ALLEN',450);
INSERT INTO TEST1 VALUES(3,'WARD',150);
INSERT INTO TEST1 VALUES(4,'JONES',850);

HOW TO CALL A SPECIFIC PARTITION FROM A TABLE:


==============================================
SYNTAX:
=======
SELECT * FROM <TN> PARTITION(<PARTITION NAME>);

EX:
SELECT * FROM TEST1 PARTITION(P1);

EID ENAME SAL


---------- ---------- ----------
2 ALLEN 450
3 WARD 150

2. LIST PARTITION:
===================
- created partition table based on the given list of values.

syntax:
=======
create table <tn>(<col1> <dt>[size],............................)
partition by list(<key column name>)
(partition <partition name1> values(v1,v2,......),
partition <partition name2> values(v1,v2,........),
.................................................,
.................................................,
partition others values(default));

90
Ex:
CREATE TABLE TEST2(CID INT,CNAME VARCHAR2(10))PARTITION BY LIST(CNAME)(PARTITION P1
VALUES('ORACLE','MYSQL'),PARTITION P2 VALUES('JAVA','PHP','.NET'),PARTITION OTHERS VALUES
(DEFAULT));

INSERT INTO TEST2 VALUES(1,'ORACLE');


INSERT INTO TEST2 VALUES(2,'JAVA');
INSERT INTO TEST2 VALUES(3,'.NET');
INSERT INTO TEST2 VALUES(4,'C');

CALLING A PARTICULAR PARTITION:


===============================
SELECT * FROM TEST2 PARTITION(P1);

CID CNAME
---------- ----------
1 ORACLE

3) HASH PARTITION:
=================
- CREATED PARTITION TABLE BASED ON HASH ALGORITHM BY ORACLE SERVER
BY DEFUALT.

SYNTAX:
=======
CREATE TABLE <TN>(<COL1> <DT>[SIZE],.......)
PARTITION BY HASH(COLUMN NAME) PARTITIONS <NUMBER>;

EX:
CREATE TABLE TEST3(ENAME VARCHAR2(10),SAL NUMBER(10)) PARTITION BY HASH(SAL) PARTITIONS 5;

NOTE:
=====
- IF WE WANT VIEW ALL PARTITIONS OF A PARTICULAR TABLE THEN WE USE THE FOLLOWING
DATADICTIONARY IS "USER_TAB_PARTITIONS".

EX:
DESC USER_TAB_PARTITIONS;
SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS WHERE TABLE_NAME='TEST3';

HOW TO ADD A PARTITION TO AN EXISTING TABLE:


============================================
SYNTAX FOR RANGE PARTITION:
===========================
ALTER TABLE <TN> ADD PARTITION <PARTITION NAME> VALUES LESS THAN(VALUE);

SYNTAX FOR LIST PARTITION:


=========================
ALTER TABLE <TN> ADD PARTITION <PARTITION NAME> VALUES(V1,V2,....);

91
EX:
SQL> ALTER TABLE TEST1 ADD PARTITION P4 VALUES LESS THAN(3000);

HOW TO DROP A PARTITION FROM A TABLE:


=====================================
SYNTAX:
=======
ALTER TABLE <TN> DROP PARTITION <PARTITION NAME>;

EX:
SQL> ALTER TABLE TEST1 DROP PARTITION P1;

locks:
======
- to prevent unauthorized access for our resource.
1. row level locking
2. table level locking

1. row level locking:


=====================
i) single row lock
ii) multiple rows lock

i) single row lock:


====================
- system can lock a single row in a table.

USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm
SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET
SAL=1100 WHERE EMPNO=7369; SAL=2200 WHERE EMPNO=7369;
[ row is locked ] [ we cannot perform update
-operation ]

SQL> commit / rollback; 1 row updated.


[ lock is releasing]

ii) multiple rows lock:


========================
- when we lock multiple rows in a table we must use
"for update" clause in select query.

USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm

SQL> SELECT * FROM MYDB4PM.EMP SQL> UPDATE EMP SET WHERE DEPTNO=10 FOR UPDATE; SAL=3300
WHERE DEPTNO=10;
[ rows are locked ] [ we cannot perform update-operation ]

92
SQL> commit / rollback; 3 rows updated.
[ lock is releasing]

DEAD LOCK:
==========
- both users resources are under waiting position is called as dead lock.

USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm

SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET SAL=5500 SAL=4400 WHERE EMPNO=7369;
WHERE EMPNO=7788;
[ row is locked ] [ row is locked ]

SQL> UPDATE MYDB4PM.EMP SET SQL> UPDATE EMP SET SAL=7700 SAL=6600 WHERE EMPNO=7788;
WHERE EMPNO=7369;
[ we cannot perform update [ we cannot perform update -operation ] -operation ]

ERROR at line 1:
ORA-00060: deadlock detected while waiting for resource

SQL> commit / rollback; 1 ROW UPDATED.


[ lock is releasing]

2) TABLE LEVEL LOCKS:


=====================
- THE ENTIRE TABLE IS LOCK(ALL ROWS)
I) SHARE LOCK
II) EXCLUSIVE LOCK

I) SHARE LOCK:
==============
- IN THIS MECHANISM BOTH USERS CAN LOCK A TABLE.

SYNTAX:
=======
LOCK TABLE <TABLE NAME> IN SHARE MODE;

EX:
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm

SQL> LOCK TABLE MYDB4PM.EMP SQL> LOCK TABLE EMP IN SHARE MODE
IN SHARE MODE;
TABLE(S) LOCKED. TABLE(S) LOCKED.

SQL> COMMIT/ROLLBACK SQL> COMMIT/ROLLBACK


[FOR RELEASING LOCK] [ FOR RELEASING LOCK ]

93
II) EXCLUSIVE LOCK:
===================
- ANY ONE USER CAN LOCK A TABLE.

SYNTAX:
=======
LOCK TABLE <TABLE NAME> IN EXCLUSIVE MODE;

EX:
USER1 USER2
===== =====
conn : system/tiger conn : mydb4pm/mydb4pm

SQL> LOCK TABLE MYDB4PM.EMP SQL> LOCK TABLE EMP IN EXCLUSIVE MODE;
IN EXCLUSIVE MODE; [ WE CANNOT PERFORM EXCLUSIVE MODE]
TABLE(S) LOCKED.

SQL> COMMIT/ROLLBACK TABLE(S) LOCKED.


[FOR RELEASING LOCK]

94

You might also like